CodeGenFunction.h 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044
  1. //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This is the internal per-function state used for llvm translation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  14. #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  15. #include "CGBuilder.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGLoopInfo.h"
  18. #include "CGValue.h"
  19. #include "CodeGenModule.h"
  20. #include "CodeGenPGO.h"
  21. #include "EHScopeStack.h"
  22. #include "clang/AST/CharUnits.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/ExprObjC.h"
  25. #include "clang/AST/Type.h"
  26. #include "clang/Basic/ABI.h"
  27. #include "clang/Basic/CapturedStmt.h"
  28. #include "clang/Basic/OpenMPKinds.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Frontend/CodeGenOptions.h"
  31. #include "llvm/ADT/ArrayRef.h"
  32. #include "llvm/ADT/DenseMap.h"
  33. #include "llvm/ADT/SmallVector.h"
  34. #include "llvm/IR/ValueHandle.h"
  35. #include "llvm/Support/Debug.h"
  36. namespace llvm {
  37. class BasicBlock;
  38. class LLVMContext;
  39. class MDNode;
  40. class Module;
  41. class SwitchInst;
  42. class Twine;
  43. class Value;
  44. class CallSite;
  45. }
  46. namespace clang {
  47. class ASTContext;
  48. class BlockDecl;
  49. class CXXDestructorDecl;
  50. class CXXForRangeStmt;
  51. class CXXTryStmt;
  52. class Decl;
  53. class LabelDecl;
  54. class EnumConstantDecl;
  55. class FunctionDecl;
  56. class FunctionProtoType;
  57. class LabelStmt;
  58. class ObjCContainerDecl;
  59. class ObjCInterfaceDecl;
  60. class ObjCIvarDecl;
  61. class ObjCMethodDecl;
  62. class ObjCImplementationDecl;
  63. class ObjCPropertyImplDecl;
  64. class TargetInfo;
  65. class TargetCodeGenInfo;
  66. class VarDecl;
  67. class ObjCForCollectionStmt;
  68. class ObjCAtTryStmt;
  69. class ObjCAtThrowStmt;
  70. class ObjCAtSynchronizedStmt;
  71. class ObjCAutoreleasePoolStmt;
  72. namespace CodeGen {
  73. class CodeGenTypes;
  74. class CGFunctionInfo;
  75. class CGRecordLayout;
  76. class CGBlockInfo;
  77. class CGCXXABI;
  78. class BlockFlags;
  79. class BlockFieldFlags;
  80. /// The kind of evaluation to perform on values of a particular
  81. /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
  82. /// CGExprAgg?
  83. ///
  84. /// TODO: should vectors maybe be split out into their own thing?
  85. enum TypeEvaluationKind {
  86. TEK_Scalar,
  87. TEK_Complex,
  88. TEK_Aggregate
  89. };
  90. /// CodeGenFunction - This class organizes the per-function state that is used
  91. /// while generating LLVM code.
  92. class CodeGenFunction : public CodeGenTypeCache {
  93. CodeGenFunction(const CodeGenFunction &) = delete;
  94. void operator=(const CodeGenFunction &) = delete;
  95. friend class CGCXXABI;
  96. public:
  97. /// A jump destination is an abstract label, branching to which may
  98. /// require a jump out through normal cleanups.
  99. struct JumpDest {
  100. JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
  101. JumpDest(llvm::BasicBlock *Block,
  102. EHScopeStack::stable_iterator Depth,
  103. unsigned Index)
  104. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  105. bool isValid() const { return Block != nullptr; }
  106. llvm::BasicBlock *getBlock() const { return Block; }
  107. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  108. unsigned getDestIndex() const { return Index; }
  109. // This should be used cautiously.
  110. void setScopeDepth(EHScopeStack::stable_iterator depth) {
  111. ScopeDepth = depth;
  112. }
  113. private:
  114. llvm::BasicBlock *Block;
  115. EHScopeStack::stable_iterator ScopeDepth;
  116. unsigned Index;
  117. };
  118. CodeGenModule &CGM; // Per-module state.
  119. const TargetInfo &Target;
  120. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  121. LoopInfoStack LoopStack;
  122. CGBuilderTy Builder;
  123. /// \brief CGBuilder insert helper. This function is called after an
  124. /// instruction is created using Builder.
  125. void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
  126. llvm::BasicBlock *BB,
  127. llvm::BasicBlock::iterator InsertPt) const;
  128. /// CurFuncDecl - Holds the Decl for the current outermost
  129. /// non-closure context.
  130. const Decl *CurFuncDecl;
  131. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  132. const Decl *CurCodeDecl;
  133. const CGFunctionInfo *CurFnInfo;
  134. QualType FnRetTy;
  135. llvm::Function *CurFn;
  136. /// CurGD - The GlobalDecl for the current function being compiled.
  137. GlobalDecl CurGD;
  138. /// PrologueCleanupDepth - The cleanup depth enclosing all the
  139. /// cleanups associated with the parameters.
  140. EHScopeStack::stable_iterator PrologueCleanupDepth;
  141. /// ReturnBlock - Unified return block.
  142. JumpDest ReturnBlock;
  143. /// ReturnValue - The temporary alloca to hold the return value. This is null
  144. /// iff the function has no return value.
  145. llvm::Value *ReturnValue;
  146. /// AllocaInsertPoint - This is an instruction in the entry block before which
  147. /// we prefer to insert allocas.
  148. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  149. /// \brief API for captured statement code generation.
  150. class CGCapturedStmtInfo {
  151. public:
  152. explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
  153. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
  154. explicit CGCapturedStmtInfo(const CapturedStmt &S,
  155. CapturedRegionKind K = CR_Default)
  156. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
  157. RecordDecl::field_iterator Field =
  158. S.getCapturedRecordDecl()->field_begin();
  159. for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
  160. E = S.capture_end();
  161. I != E; ++I, ++Field) {
  162. if (I->capturesThis())
  163. CXXThisFieldDecl = *Field;
  164. else if (I->capturesVariable())
  165. CaptureFields[I->getCapturedVar()] = *Field;
  166. }
  167. }
  168. virtual ~CGCapturedStmtInfo();
  169. CapturedRegionKind getKind() const { return Kind; }
  170. virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
  171. // \brief Retrieve the value of the context parameter.
  172. virtual llvm::Value *getContextValue() const { return ThisValue; }
  173. /// \brief Lookup the captured field decl for a variable.
  174. virtual const FieldDecl *lookup(const VarDecl *VD) const {
  175. return CaptureFields.lookup(VD);
  176. }
  177. bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
  178. virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
  179. static bool classof(const CGCapturedStmtInfo *) {
  180. return true;
  181. }
  182. /// \brief Emit the captured statement body.
  183. virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
  184. CGF.incrementProfileCounter(S);
  185. CGF.EmitStmt(S);
  186. }
  187. /// \brief Get the name of the capture helper.
  188. virtual StringRef getHelperName() const { return "__captured_stmt"; }
  189. private:
  190. /// \brief The kind of captured statement being generated.
  191. CapturedRegionKind Kind;
  192. /// \brief Keep the map between VarDecl and FieldDecl.
  193. llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
  194. /// \brief The base address of the captured record, passed in as the first
  195. /// argument of the parallel region function.
  196. llvm::Value *ThisValue;
  197. /// \brief Captured 'this' type.
  198. FieldDecl *CXXThisFieldDecl;
  199. };
  200. CGCapturedStmtInfo *CapturedStmtInfo;
  201. /// BoundsChecking - Emit run-time bounds checks. Higher values mean
  202. /// potentially higher performance penalties.
  203. unsigned char BoundsChecking;
  204. /// \brief Sanitizers enabled for this function.
  205. SanitizerSet SanOpts;
  206. /// \brief True if CodeGen currently emits code implementing sanitizer checks.
  207. bool IsSanitizerScope;
  208. /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
  209. class SanitizerScope {
  210. CodeGenFunction *CGF;
  211. public:
  212. SanitizerScope(CodeGenFunction *CGF);
  213. ~SanitizerScope();
  214. };
  215. /// In C++, whether we are code generating a thunk. This controls whether we
  216. /// should emit cleanups.
  217. bool CurFuncIsThunk;
  218. /// In ARC, whether we should autorelease the return value.
  219. bool AutoreleaseResult;
  220. /// Whether we processed a Microsoft-style asm block during CodeGen. These can
  221. /// potentially set the return value.
  222. bool SawAsmBlock;
  223. /// True if the current function is an outlined SEH helper. This can be a
  224. /// finally block or filter expression.
  225. bool IsOutlinedSEHHelper;
  226. const CodeGen::CGBlockInfo *BlockInfo;
  227. llvm::Value *BlockPointer;
  228. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  229. FieldDecl *LambdaThisCaptureField;
  230. /// \brief A mapping from NRVO variables to the flags used to indicate
  231. /// when the NRVO has been applied to this variable.
  232. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  233. EHScopeStack EHStack;
  234. llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
  235. llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
  236. /// Header for data within LifetimeExtendedCleanupStack.
  237. struct LifetimeExtendedCleanupHeader {
  238. /// The size of the following cleanup object.
  239. unsigned Size : 29;
  240. /// The kind of cleanup to push: a value from the CleanupKind enumeration.
  241. unsigned Kind : 3;
  242. size_t getSize() const { return size_t(Size); }
  243. CleanupKind getKind() const { return static_cast<CleanupKind>(Kind); }
  244. };
  245. /// i32s containing the indexes of the cleanup destinations.
  246. llvm::AllocaInst *NormalCleanupDest;
  247. unsigned NextCleanupDestIndex;
  248. /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
  249. CGBlockInfo *FirstBlockInfo;
  250. /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
  251. llvm::BasicBlock *EHResumeBlock;
  252. /// The exception slot. All landing pads write the current exception pointer
  253. /// into this alloca.
  254. llvm::Value *ExceptionSlot;
  255. /// The selector slot. Under the MandatoryCleanup model, all landing pads
  256. /// write the current selector value into this alloca.
  257. llvm::AllocaInst *EHSelectorSlot;
  258. /// Entering and leaving an SEH __try / __finally scope causes stores to this
  259. /// slot.
  260. llvm::Value *ChildAbnormalTerminationSlot;
  261. /// The SEH __abnormal_termination() intrinsic lowers down to loads from this
  262. /// slot from a parent function.
  263. llvm::Value *AbnormalTerminationSlot;
  264. /// The implicit parameter to SEH filter functions of type
  265. /// 'EXCEPTION_POINTERS*'.
  266. ImplicitParamDecl *SEHPointersDecl;
  267. /// Emits a landing pad for the current EH stack.
  268. llvm::BasicBlock *EmitLandingPad();
  269. llvm::BasicBlock *getInvokeDestImpl();
  270. template <class T>
  271. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  272. return DominatingValue<T>::save(*this, value);
  273. }
  274. public:
  275. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  276. /// rethrows.
  277. SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  278. /// A class controlling the emission of a finally block.
  279. class FinallyInfo {
  280. /// Where the catchall's edge through the cleanup should go.
  281. JumpDest RethrowDest;
  282. /// A function to call to enter the catch.
  283. llvm::Constant *BeginCatchFn;
  284. /// An i1 variable indicating whether or not the @finally is
  285. /// running for an exception.
  286. llvm::AllocaInst *ForEHVar;
  287. /// An i8* variable into which the exception pointer to rethrow
  288. /// has been saved.
  289. llvm::AllocaInst *SavedExnVar;
  290. public:
  291. void enter(CodeGenFunction &CGF, const Stmt *Finally,
  292. llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
  293. llvm::Constant *rethrowFn);
  294. void exit(CodeGenFunction &CGF);
  295. };
  296. /// Returns true inside SEH __try blocks.
  297. bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
  298. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  299. /// current full-expression. Safe against the possibility that
  300. /// we're currently inside a conditionally-evaluated expression.
  301. template <class T, class... As>
  302. void pushFullExprCleanup(CleanupKind kind, As... A) {
  303. // If we're not in a conditional branch, or if none of the
  304. // arguments requires saving, then use the unconditional cleanup.
  305. if (!isInConditionalBranch())
  306. return EHStack.pushCleanup<T>(kind, A...);
  307. // Stash values in a tuple so we can guarantee the order of saves.
  308. typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
  309. SavedTuple Saved{saveValueInCond(A)...};
  310. typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
  311. EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
  312. initFullExprCleanup();
  313. }
  314. /// \brief Queue a cleanup to be pushed after finishing the current
  315. /// full-expression.
  316. template <class T, class... As>
  317. void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
  318. assert(!isInConditionalBranch() && "can't defer conditional cleanup");
  319. LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
  320. size_t OldSize = LifetimeExtendedCleanupStack.size();
  321. LifetimeExtendedCleanupStack.resize(
  322. LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
  323. char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
  324. new (Buffer) LifetimeExtendedCleanupHeader(Header);
  325. new (Buffer + sizeof(Header)) T(A...);
  326. }
  327. /// Set up the last cleaup that was pushed as a conditional
  328. /// full-expression cleanup.
  329. void initFullExprCleanup();
  330. /// PushDestructorCleanup - Push a cleanup to call the
  331. /// complete-object destructor of an object of the given type at the
  332. /// given address. Does nothing if T is not a C++ class type with a
  333. /// non-trivial destructor.
  334. void PushDestructorCleanup(QualType T, llvm::Value *Addr);
  335. /// PushDestructorCleanup - Push a cleanup to call the
  336. /// complete-object variant of the given destructor on the object at
  337. /// the given address.
  338. void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
  339. llvm::Value *Addr);
  340. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  341. /// process all branch fixups.
  342. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  343. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  344. /// The block cannot be reactivated. Pops it if it's the top of the
  345. /// stack.
  346. ///
  347. /// \param DominatingIP - An instruction which is known to
  348. /// dominate the current IP (if set) and which lies along
  349. /// all paths of execution between the current IP and the
  350. /// the point at which the cleanup comes into scope.
  351. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  352. llvm::Instruction *DominatingIP);
  353. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  354. /// Cannot be used to resurrect a deactivated cleanup.
  355. ///
  356. /// \param DominatingIP - An instruction which is known to
  357. /// dominate the current IP (if set) and which lies along
  358. /// all paths of execution between the current IP and the
  359. /// the point at which the cleanup comes into scope.
  360. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  361. llvm::Instruction *DominatingIP);
  362. /// \brief Enters a new scope for capturing cleanups, all of which
  363. /// will be executed once the scope is exited.
  364. class RunCleanupsScope {
  365. EHScopeStack::stable_iterator CleanupStackDepth;
  366. size_t LifetimeExtendedCleanupStackSize;
  367. bool OldDidCallStackSave;
  368. protected:
  369. bool PerformCleanup;
  370. private:
  371. RunCleanupsScope(const RunCleanupsScope &) = delete;
  372. void operator=(const RunCleanupsScope &) = delete;
  373. protected:
  374. CodeGenFunction& CGF;
  375. public:
  376. /// \brief Enter a new cleanup scope.
  377. explicit RunCleanupsScope(CodeGenFunction &CGF)
  378. : PerformCleanup(true), CGF(CGF)
  379. {
  380. CleanupStackDepth = CGF.EHStack.stable_begin();
  381. LifetimeExtendedCleanupStackSize =
  382. CGF.LifetimeExtendedCleanupStack.size();
  383. OldDidCallStackSave = CGF.DidCallStackSave;
  384. CGF.DidCallStackSave = false;
  385. }
  386. /// \brief Exit this cleanup scope, emitting any accumulated
  387. /// cleanups.
  388. ~RunCleanupsScope() {
  389. if (PerformCleanup) {
  390. CGF.DidCallStackSave = OldDidCallStackSave;
  391. CGF.PopCleanupBlocks(CleanupStackDepth,
  392. LifetimeExtendedCleanupStackSize);
  393. }
  394. }
  395. /// \brief Determine whether this scope requires any cleanups.
  396. bool requiresCleanups() const {
  397. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  398. }
  399. /// \brief Force the emission of cleanups now, instead of waiting
  400. /// until this object is destroyed.
  401. void ForceCleanup() {
  402. assert(PerformCleanup && "Already forced cleanup");
  403. CGF.DidCallStackSave = OldDidCallStackSave;
  404. CGF.PopCleanupBlocks(CleanupStackDepth,
  405. LifetimeExtendedCleanupStackSize);
  406. PerformCleanup = false;
  407. }
  408. };
  409. class LexicalScope : public RunCleanupsScope {
  410. SourceRange Range;
  411. SmallVector<const LabelDecl*, 4> Labels;
  412. LexicalScope *ParentScope;
  413. LexicalScope(const LexicalScope &) = delete;
  414. void operator=(const LexicalScope &) = delete;
  415. public:
  416. /// \brief Enter a new cleanup scope.
  417. explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
  418. : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
  419. CGF.CurLexicalScope = this;
  420. if (CGDebugInfo *DI = CGF.getDebugInfo())
  421. DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
  422. }
  423. void addLabel(const LabelDecl *label) {
  424. assert(PerformCleanup && "adding label to dead scope?");
  425. Labels.push_back(label);
  426. }
  427. /// \brief Exit this cleanup scope, emitting any accumulated
  428. /// cleanups.
  429. ~LexicalScope() {
  430. if (CGDebugInfo *DI = CGF.getDebugInfo())
  431. DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  432. // If we should perform a cleanup, force them now. Note that
  433. // this ends the cleanup scope before rescoping any labels.
  434. if (PerformCleanup) {
  435. ApplyDebugLocation DL(CGF, Range.getEnd());
  436. ForceCleanup();
  437. }
  438. }
  439. /// \brief Force the emission of cleanups now, instead of waiting
  440. /// until this object is destroyed.
  441. void ForceCleanup() {
  442. CGF.CurLexicalScope = ParentScope;
  443. RunCleanupsScope::ForceCleanup();
  444. if (!Labels.empty())
  445. rescopeLabels();
  446. }
  447. void rescopeLabels();
  448. };
  449. /// \brief The scope used to remap some variables as private in the OpenMP
  450. /// loop body (or other captured region emitted without outlining), and to
  451. /// restore old vars back on exit.
  452. class OMPPrivateScope : public RunCleanupsScope {
  453. typedef llvm::DenseMap<const VarDecl *, llvm::Value *> VarDeclMapTy;
  454. VarDeclMapTy SavedLocals;
  455. VarDeclMapTy SavedPrivates;
  456. private:
  457. OMPPrivateScope(const OMPPrivateScope &) = delete;
  458. void operator=(const OMPPrivateScope &) = delete;
  459. public:
  460. /// \brief Enter a new OpenMP private scope.
  461. explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
  462. /// \brief Registers \a LocalVD variable as a private and apply \a
  463. /// PrivateGen function for it to generate corresponding private variable.
  464. /// \a PrivateGen returns an address of the generated private variable.
  465. /// \return true if the variable is registered as private, false if it has
  466. /// been privatized already.
  467. bool
  468. addPrivate(const VarDecl *LocalVD,
  469. const std::function<llvm::Value *()> &PrivateGen) {
  470. assert(PerformCleanup && "adding private to dead scope");
  471. if (SavedLocals.count(LocalVD) > 0) return false;
  472. SavedLocals[LocalVD] = CGF.LocalDeclMap.lookup(LocalVD);
  473. CGF.LocalDeclMap.erase(LocalVD);
  474. SavedPrivates[LocalVD] = PrivateGen();
  475. CGF.LocalDeclMap[LocalVD] = SavedLocals[LocalVD];
  476. return true;
  477. }
  478. /// \brief Privatizes local variables previously registered as private.
  479. /// Registration is separate from the actual privatization to allow
  480. /// initializers use values of the original variables, not the private one.
  481. /// This is important, for example, if the private variable is a class
  482. /// variable initialized by a constructor that references other private
  483. /// variables. But at initialization original variables must be used, not
  484. /// private copies.
  485. /// \return true if at least one variable was privatized, false otherwise.
  486. bool Privatize() {
  487. for (auto VDPair : SavedPrivates) {
  488. CGF.LocalDeclMap[VDPair.first] = VDPair.second;
  489. }
  490. SavedPrivates.clear();
  491. return !SavedLocals.empty();
  492. }
  493. void ForceCleanup() {
  494. RunCleanupsScope::ForceCleanup();
  495. // Remap vars back to the original values.
  496. for (auto I : SavedLocals) {
  497. CGF.LocalDeclMap[I.first] = I.second;
  498. }
  499. SavedLocals.clear();
  500. }
  501. /// \brief Exit scope - all the mapped variables are restored.
  502. ~OMPPrivateScope() {
  503. if (PerformCleanup)
  504. ForceCleanup();
  505. }
  506. };
  507. /// \brief Takes the old cleanup stack size and emits the cleanup blocks
  508. /// that have been added.
  509. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
  510. /// \brief Takes the old cleanup stack size and emits the cleanup blocks
  511. /// that have been added, then adds all lifetime-extended cleanups from
  512. /// the given position to the stack.
  513. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  514. size_t OldLifetimeExtendedStackSize);
  515. void ResolveBranchFixups(llvm::BasicBlock *Target);
  516. /// The given basic block lies in the current EH scope, but may be a
  517. /// target of a potentially scope-crossing jump; get a stable handle
  518. /// to which we can perform this jump later.
  519. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  520. return JumpDest(Target,
  521. EHStack.getInnermostNormalCleanup(),
  522. NextCleanupDestIndex++);
  523. }
  524. /// The given basic block lies in the current EH scope, but may be a
  525. /// target of a potentially scope-crossing jump; get a stable handle
  526. /// to which we can perform this jump later.
  527. JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
  528. return getJumpDestInCurrentScope(createBasicBlock(Name));
  529. }
  530. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  531. /// block through the normal cleanup handling code (if any) and then
  532. /// on to \arg Dest.
  533. void EmitBranchThroughCleanup(JumpDest Dest);
  534. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  535. /// specified destination obviously has no cleanups to run. 'false' is always
  536. /// a conservatively correct answer for this method.
  537. bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
  538. /// popCatchScope - Pops the catch scope at the top of the EHScope
  539. /// stack, emitting any required code (other than the catch handlers
  540. /// themselves).
  541. void popCatchScope();
  542. llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
  543. llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
  544. /// An object to manage conditionally-evaluated expressions.
  545. class ConditionalEvaluation {
  546. llvm::BasicBlock *StartBB;
  547. public:
  548. ConditionalEvaluation(CodeGenFunction &CGF)
  549. : StartBB(CGF.Builder.GetInsertBlock()) {}
  550. void begin(CodeGenFunction &CGF) {
  551. assert(CGF.OutermostConditional != this);
  552. if (!CGF.OutermostConditional)
  553. CGF.OutermostConditional = this;
  554. }
  555. void end(CodeGenFunction &CGF) {
  556. assert(CGF.OutermostConditional != nullptr);
  557. if (CGF.OutermostConditional == this)
  558. CGF.OutermostConditional = nullptr;
  559. }
  560. /// Returns a block which will be executed prior to each
  561. /// evaluation of the conditional code.
  562. llvm::BasicBlock *getStartingBlock() const {
  563. return StartBB;
  564. }
  565. };
  566. /// isInConditionalBranch - Return true if we're currently emitting
  567. /// one branch or the other of a conditional expression.
  568. bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
  569. void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) {
  570. assert(isInConditionalBranch());
  571. llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
  572. new llvm::StoreInst(value, addr, &block->back());
  573. }
  574. /// An RAII object to record that we're evaluating a statement
  575. /// expression.
  576. class StmtExprEvaluation {
  577. CodeGenFunction &CGF;
  578. /// We have to save the outermost conditional: cleanups in a
  579. /// statement expression aren't conditional just because the
  580. /// StmtExpr is.
  581. ConditionalEvaluation *SavedOutermostConditional;
  582. public:
  583. StmtExprEvaluation(CodeGenFunction &CGF)
  584. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  585. CGF.OutermostConditional = nullptr;
  586. }
  587. ~StmtExprEvaluation() {
  588. CGF.OutermostConditional = SavedOutermostConditional;
  589. CGF.EnsureInsertPoint();
  590. }
  591. };
  592. /// An object which temporarily prevents a value from being
  593. /// destroyed by aggressive peephole optimizations that assume that
  594. /// all uses of a value have been realized in the IR.
  595. class PeepholeProtection {
  596. llvm::Instruction *Inst;
  597. friend class CodeGenFunction;
  598. public:
  599. PeepholeProtection() : Inst(nullptr) {}
  600. };
  601. /// A non-RAII class containing all the information about a bound
  602. /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
  603. /// this which makes individual mappings very simple; using this
  604. /// class directly is useful when you have a variable number of
  605. /// opaque values or don't want the RAII functionality for some
  606. /// reason.
  607. class OpaqueValueMappingData {
  608. const OpaqueValueExpr *OpaqueValue;
  609. bool BoundLValue;
  610. CodeGenFunction::PeepholeProtection Protection;
  611. OpaqueValueMappingData(const OpaqueValueExpr *ov,
  612. bool boundLValue)
  613. : OpaqueValue(ov), BoundLValue(boundLValue) {}
  614. public:
  615. OpaqueValueMappingData() : OpaqueValue(nullptr) {}
  616. static bool shouldBindAsLValue(const Expr *expr) {
  617. // gl-values should be bound as l-values for obvious reasons.
  618. // Records should be bound as l-values because IR generation
  619. // always keeps them in memory. Expressions of function type
  620. // act exactly like l-values but are formally required to be
  621. // r-values in C.
  622. return expr->isGLValue() ||
  623. expr->getType()->isFunctionType() ||
  624. hasAggregateEvaluationKind(expr->getType());
  625. }
  626. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  627. const OpaqueValueExpr *ov,
  628. const Expr *e) {
  629. if (shouldBindAsLValue(ov))
  630. return bind(CGF, ov, CGF.EmitLValue(e));
  631. return bind(CGF, ov, CGF.EmitAnyExpr(e));
  632. }
  633. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  634. const OpaqueValueExpr *ov,
  635. const LValue &lv) {
  636. assert(shouldBindAsLValue(ov));
  637. CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
  638. return OpaqueValueMappingData(ov, true);
  639. }
  640. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  641. const OpaqueValueExpr *ov,
  642. const RValue &rv) {
  643. assert(!shouldBindAsLValue(ov));
  644. CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
  645. OpaqueValueMappingData data(ov, false);
  646. // Work around an extremely aggressive peephole optimization in
  647. // EmitScalarConversion which assumes that all other uses of a
  648. // value are extant.
  649. data.Protection = CGF.protectFromPeepholes(rv);
  650. return data;
  651. }
  652. bool isValid() const { return OpaqueValue != nullptr; }
  653. void clear() { OpaqueValue = nullptr; }
  654. void unbind(CodeGenFunction &CGF) {
  655. assert(OpaqueValue && "no data to unbind!");
  656. if (BoundLValue) {
  657. CGF.OpaqueLValues.erase(OpaqueValue);
  658. } else {
  659. CGF.OpaqueRValues.erase(OpaqueValue);
  660. CGF.unprotectFromPeepholes(Protection);
  661. }
  662. }
  663. };
  664. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  665. class OpaqueValueMapping {
  666. CodeGenFunction &CGF;
  667. OpaqueValueMappingData Data;
  668. public:
  669. static bool shouldBindAsLValue(const Expr *expr) {
  670. return OpaqueValueMappingData::shouldBindAsLValue(expr);
  671. }
  672. /// Build the opaque value mapping for the given conditional
  673. /// operator if it's the GNU ?: extension. This is a common
  674. /// enough pattern that the convenience operator is really
  675. /// helpful.
  676. ///
  677. OpaqueValueMapping(CodeGenFunction &CGF,
  678. const AbstractConditionalOperator *op) : CGF(CGF) {
  679. if (isa<ConditionalOperator>(op))
  680. // Leave Data empty.
  681. return;
  682. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  683. Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
  684. e->getCommon());
  685. }
  686. OpaqueValueMapping(CodeGenFunction &CGF,
  687. const OpaqueValueExpr *opaqueValue,
  688. LValue lvalue)
  689. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
  690. }
  691. OpaqueValueMapping(CodeGenFunction &CGF,
  692. const OpaqueValueExpr *opaqueValue,
  693. RValue rvalue)
  694. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
  695. }
  696. void pop() {
  697. Data.unbind(CGF);
  698. Data.clear();
  699. }
  700. ~OpaqueValueMapping() {
  701. if (Data.isValid()) Data.unbind(CGF);
  702. }
  703. };
  704. /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
  705. /// number that holds the value.
  706. std::pair<llvm::Type *, unsigned>
  707. getByRefValueLLVMField(const ValueDecl *VD) const;
  708. /// BuildBlockByrefAddress - Computes address location of the
  709. /// variable which is declared as __block.
  710. llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr,
  711. const VarDecl *V);
  712. private:
  713. CGDebugInfo *DebugInfo;
  714. bool DisableDebugInfo;
  715. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  716. /// calling llvm.stacksave for multiple VLAs in the same scope.
  717. bool DidCallStackSave;
  718. /// IndirectBranch - The first time an indirect goto is seen we create a block
  719. /// with an indirect branch. Every time we see the address of a label taken,
  720. /// we add the label to the indirect goto. Every subsequent indirect goto is
  721. /// codegen'd as a jump to the IndirectBranch's basic block.
  722. llvm::IndirectBrInst *IndirectBranch;
  723. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  724. /// decls.
  725. typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy;
  726. DeclMapTy LocalDeclMap;
  727. /// Track escaped local variables with auto storage. Used during SEH
  728. /// outlining to produce a call to llvm.frameescape.
  729. llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
  730. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  731. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  732. // BreakContinueStack - This keeps track of where break and continue
  733. // statements should jump to.
  734. struct BreakContinue {
  735. BreakContinue(JumpDest Break, JumpDest Continue)
  736. : BreakBlock(Break), ContinueBlock(Continue) {}
  737. JumpDest BreakBlock;
  738. JumpDest ContinueBlock;
  739. };
  740. SmallVector<BreakContinue, 8> BreakContinueStack;
  741. CodeGenPGO PGO;
  742. public:
  743. /// Increment the profiler's counter for the given statement.
  744. void incrementProfileCounter(const Stmt *S) {
  745. if (CGM.getCodeGenOpts().ProfileInstrGenerate)
  746. PGO.emitCounterIncrement(Builder, S);
  747. PGO.setCurrentStmt(S);
  748. }
  749. /// Get the profiler's count for the given statement.
  750. uint64_t getProfileCount(const Stmt *S) {
  751. Optional<uint64_t> Count = PGO.getStmtCount(S);
  752. if (!Count.hasValue())
  753. return 0;
  754. return *Count;
  755. }
  756. /// Set the profiler's current count.
  757. void setCurrentProfileCount(uint64_t Count) {
  758. PGO.setCurrentRegionCount(Count);
  759. }
  760. /// Get the profiler's current count. This is generally the count for the most
  761. /// recently incremented counter.
  762. uint64_t getCurrentProfileCount() {
  763. return PGO.getCurrentRegionCount();
  764. }
  765. private:
  766. /// SwitchInsn - This is nearest current switch instruction. It is null if
  767. /// current context is not in a switch.
  768. llvm::SwitchInst *SwitchInsn;
  769. /// The branch weights of SwitchInsn when doing instrumentation based PGO.
  770. SmallVector<uint64_t, 16> *SwitchWeights;
  771. /// CaseRangeBlock - This block holds if condition check for last case
  772. /// statement range in current switch instruction.
  773. llvm::BasicBlock *CaseRangeBlock;
  774. /// OpaqueLValues - Keeps track of the current set of opaque value
  775. /// expressions.
  776. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  777. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  778. // VLASizeMap - This keeps track of the associated size for each VLA type.
  779. // We track this by the size expression rather than the type itself because
  780. // in certain situations, like a const qualifier applied to an VLA typedef,
  781. // multiple VLA types can share the same size expression.
  782. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  783. // enter/leave scopes.
  784. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  785. /// A block containing a single 'unreachable' instruction. Created
  786. /// lazily by getUnreachableBlock().
  787. llvm::BasicBlock *UnreachableBlock;
  788. /// Counts of the number return expressions in the function.
  789. unsigned NumReturnExprs;
  790. /// Count the number of simple (constant) return expressions in the function.
  791. unsigned NumSimpleReturnExprs;
  792. /// The last regular (non-return) debug location (breakpoint) in the function.
  793. SourceLocation LastStopPoint;
  794. public:
  795. /// A scope within which we are constructing the fields of an object which
  796. /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
  797. /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
  798. class FieldConstructionScope {
  799. public:
  800. FieldConstructionScope(CodeGenFunction &CGF, llvm::Value *This)
  801. : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
  802. CGF.CXXDefaultInitExprThis = This;
  803. }
  804. ~FieldConstructionScope() {
  805. CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
  806. }
  807. private:
  808. CodeGenFunction &CGF;
  809. llvm::Value *OldCXXDefaultInitExprThis;
  810. };
  811. /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
  812. /// is overridden to be the object under construction.
  813. class CXXDefaultInitExprScope {
  814. public:
  815. CXXDefaultInitExprScope(CodeGenFunction &CGF)
  816. : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue) {
  817. CGF.CXXThisValue = CGF.CXXDefaultInitExprThis;
  818. }
  819. ~CXXDefaultInitExprScope() {
  820. CGF.CXXThisValue = OldCXXThisValue;
  821. }
  822. public:
  823. CodeGenFunction &CGF;
  824. llvm::Value *OldCXXThisValue;
  825. };
  826. private:
  827. /// CXXThisDecl - When generating code for a C++ member function,
  828. /// this will hold the implicit 'this' declaration.
  829. ImplicitParamDecl *CXXABIThisDecl;
  830. llvm::Value *CXXABIThisValue;
  831. llvm::Value *CXXThisValue;
  832. /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
  833. /// this expression.
  834. llvm::Value *CXXDefaultInitExprThis;
  835. /// CXXStructorImplicitParamDecl - When generating code for a constructor or
  836. /// destructor, this will hold the implicit argument (e.g. VTT).
  837. ImplicitParamDecl *CXXStructorImplicitParamDecl;
  838. llvm::Value *CXXStructorImplicitParamValue;
  839. /// OutermostConditional - Points to the outermost active
  840. /// conditional control. This is used so that we know if a
  841. /// temporary should be destroyed conditionally.
  842. ConditionalEvaluation *OutermostConditional;
  843. /// The current lexical scope.
  844. LexicalScope *CurLexicalScope;
  845. /// The current source location that should be used for exception
  846. /// handling code.
  847. SourceLocation CurEHLocation;
  848. /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
  849. /// type as well as the field number that contains the actual data.
  850. llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *,
  851. unsigned> > ByRefValueInfo;
  852. llvm::BasicBlock *TerminateLandingPad;
  853. llvm::BasicBlock *TerminateHandler;
  854. llvm::BasicBlock *TrapBB;
  855. /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
  856. /// In the kernel metadata node, reference the kernel function and metadata
  857. /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
  858. /// - A node for the vec_type_hint(<type>) qualifier contains string
  859. /// "vec_type_hint", an undefined value of the <type> data type,
  860. /// and a Boolean that is true if the <type> is integer and signed.
  861. /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
  862. /// "work_group_size_hint", and three 32-bit integers X, Y and Z.
  863. /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
  864. /// "reqd_work_group_size", and three 32-bit integers X, Y and Z.
  865. void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  866. llvm::Function *Fn);
  867. public:
  868. CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
  869. ~CodeGenFunction();
  870. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  871. ASTContext &getContext() const { return CGM.getContext(); }
  872. CGDebugInfo *getDebugInfo() {
  873. if (DisableDebugInfo)
  874. return nullptr;
  875. return DebugInfo;
  876. }
  877. void disableDebugInfo() { DisableDebugInfo = true; }
  878. void enableDebugInfo() { DisableDebugInfo = false; }
  879. bool shouldUseFusedARCCalls() {
  880. return CGM.getCodeGenOpts().OptimizationLevel == 0;
  881. }
  882. const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
  883. /// Returns a pointer to the function's exception object and selector slot,
  884. /// which is assigned in every landing pad.
  885. llvm::Value *getExceptionSlot();
  886. llvm::Value *getEHSelectorSlot();
  887. /// Returns the contents of the function's exception object and selector
  888. /// slots.
  889. llvm::Value *getExceptionFromSlot();
  890. llvm::Value *getSelectorFromSlot();
  891. llvm::Value *getNormalCleanupDestSlot();
  892. llvm::BasicBlock *getUnreachableBlock() {
  893. if (!UnreachableBlock) {
  894. UnreachableBlock = createBasicBlock("unreachable");
  895. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  896. }
  897. return UnreachableBlock;
  898. }
  899. llvm::BasicBlock *getInvokeDest() {
  900. if (!EHStack.requiresLandingPad()) return nullptr;
  901. return getInvokeDestImpl();
  902. }
  903. bool currentFunctionUsesSEHTry() const {
  904. const auto *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
  905. return FD && FD->usesSEHTry();
  906. }
  907. const TargetInfo &getTarget() const { return Target; }
  908. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  909. //===--------------------------------------------------------------------===//
  910. // Cleanups
  911. //===--------------------------------------------------------------------===//
  912. typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty);
  913. void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  914. llvm::Value *arrayEndPointer,
  915. QualType elementType,
  916. Destroyer *destroyer);
  917. void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  918. llvm::Value *arrayEnd,
  919. QualType elementType,
  920. Destroyer *destroyer);
  921. void pushDestroy(QualType::DestructionKind dtorKind,
  922. llvm::Value *addr, QualType type);
  923. void pushEHDestroy(QualType::DestructionKind dtorKind,
  924. llvm::Value *addr, QualType type);
  925. void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type,
  926. Destroyer *destroyer, bool useEHCleanupForArray);
  927. void pushLifetimeExtendedDestroy(CleanupKind kind, llvm::Value *addr,
  928. QualType type, Destroyer *destroyer,
  929. bool useEHCleanupForArray);
  930. void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
  931. llvm::Value *CompletePtr,
  932. QualType ElementType);
  933. void pushStackRestore(CleanupKind kind, llvm::Value *SPMem);
  934. void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer,
  935. bool useEHCleanupForArray);
  936. llvm::Function *generateDestroyHelper(llvm::Constant *addr, QualType type,
  937. Destroyer *destroyer,
  938. bool useEHCleanupForArray,
  939. const VarDecl *VD);
  940. void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
  941. QualType type, Destroyer *destroyer,
  942. bool checkZeroLength, bool useEHCleanup);
  943. Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
  944. /// Determines whether an EH cleanup is required to destroy a type
  945. /// with the given destruction kind.
  946. bool needsEHCleanup(QualType::DestructionKind kind) {
  947. switch (kind) {
  948. case QualType::DK_none:
  949. return false;
  950. case QualType::DK_cxx_destructor:
  951. case QualType::DK_objc_weak_lifetime:
  952. return getLangOpts().Exceptions;
  953. case QualType::DK_objc_strong_lifetime:
  954. return getLangOpts().Exceptions &&
  955. CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
  956. }
  957. llvm_unreachable("bad destruction kind");
  958. }
  959. CleanupKind getCleanupKind(QualType::DestructionKind kind) {
  960. return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
  961. }
  962. //===--------------------------------------------------------------------===//
  963. // Objective-C
  964. //===--------------------------------------------------------------------===//
  965. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  966. void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
  967. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  968. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  969. const ObjCPropertyImplDecl *PID);
  970. void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  971. const ObjCPropertyImplDecl *propImpl,
  972. const ObjCMethodDecl *GetterMothodDecl,
  973. llvm::Constant *AtomicHelperFn);
  974. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  975. ObjCMethodDecl *MD, bool ctor);
  976. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  977. /// for the given property.
  978. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  979. const ObjCPropertyImplDecl *PID);
  980. void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  981. const ObjCPropertyImplDecl *propImpl,
  982. llvm::Constant *AtomicHelperFn);
  983. bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
  984. bool IvarTypeWithAggrGCObjects(QualType Ty);
  985. //===--------------------------------------------------------------------===//
  986. // Block Bits
  987. //===--------------------------------------------------------------------===//
  988. llvm::Value *EmitBlockLiteral(const BlockExpr *);
  989. llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
  990. static void destroyBlockInfos(CGBlockInfo *info);
  991. llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
  992. const CGBlockInfo &Info,
  993. llvm::StructType *,
  994. llvm::Constant *BlockVarLayout);
  995. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  996. const CGBlockInfo &Info,
  997. const DeclMapTy &ldm,
  998. bool IsLambdaConversionToBlock);
  999. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  1000. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  1001. llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
  1002. const ObjCPropertyImplDecl *PID);
  1003. llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
  1004. const ObjCPropertyImplDecl *PID);
  1005. llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
  1006. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
  1007. class AutoVarEmission;
  1008. void emitByrefStructureInit(const AutoVarEmission &emission);
  1009. void enterByrefCleanup(const AutoVarEmission &emission);
  1010. llvm::Value *LoadBlockStruct() {
  1011. assert(BlockPointer && "no block pointer set!");
  1012. return BlockPointer;
  1013. }
  1014. void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
  1015. void AllocateBlockDecl(const DeclRefExpr *E);
  1016. llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
  1017. llvm::Type *BuildByRefType(const VarDecl *var);
  1018. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1019. const CGFunctionInfo &FnInfo);
  1020. /// \brief Emit code for the start of a function.
  1021. /// \param Loc The location to be associated with the function.
  1022. /// \param StartLoc The location of the function body.
  1023. void StartFunction(GlobalDecl GD,
  1024. QualType RetTy,
  1025. llvm::Function *Fn,
  1026. const CGFunctionInfo &FnInfo,
  1027. const FunctionArgList &Args,
  1028. SourceLocation Loc = SourceLocation(),
  1029. SourceLocation StartLoc = SourceLocation());
  1030. void EmitConstructorBody(FunctionArgList &Args);
  1031. void EmitDestructorBody(FunctionArgList &Args);
  1032. void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
  1033. void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
  1034. void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
  1035. void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
  1036. CallArgList &CallArgs);
  1037. void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
  1038. void EmitLambdaBlockInvokeBody();
  1039. void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
  1040. void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
  1041. void EmitAsanPrologueOrEpilogue(bool Prologue);
  1042. /// \brief Emit the unified return block, trying to avoid its emission when
  1043. /// possible.
  1044. /// \return The debug location of the user written return statement if the
  1045. /// return block is is avoided.
  1046. llvm::DebugLoc EmitReturnBlock();
  1047. /// FinishFunction - Complete IR generation of the current function. It is
  1048. /// legal to call this function even if there is no current insertion point.
  1049. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  1050. void StartThunk(llvm::Function *Fn, GlobalDecl GD,
  1051. const CGFunctionInfo &FnInfo);
  1052. void EmitCallAndReturnForThunk(llvm::Value *Callee, const ThunkInfo *Thunk);
  1053. /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
  1054. void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
  1055. llvm::Value *Callee);
  1056. /// GenerateThunk - Generate a thunk for the given method.
  1057. void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1058. GlobalDecl GD, const ThunkInfo &Thunk);
  1059. void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1060. GlobalDecl GD, const ThunkInfo &Thunk);
  1061. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  1062. FunctionArgList &Args);
  1063. void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
  1064. ArrayRef<VarDecl *> ArrayIndexes);
  1065. /// InitializeVTablePointer - Initialize the vtable pointer of the given
  1066. /// subobject.
  1067. ///
  1068. void InitializeVTablePointer(BaseSubobject Base,
  1069. const CXXRecordDecl *NearestVBase,
  1070. CharUnits OffsetFromNearestVBase,
  1071. const CXXRecordDecl *VTableClass);
  1072. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  1073. void InitializeVTablePointers(BaseSubobject Base,
  1074. const CXXRecordDecl *NearestVBase,
  1075. CharUnits OffsetFromNearestVBase,
  1076. bool BaseIsNonVirtualPrimaryBase,
  1077. const CXXRecordDecl *VTableClass,
  1078. VisitedVirtualBasesSetTy& VBases);
  1079. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  1080. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  1081. /// to by This.
  1082. llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty);
  1083. /// \brief Derived is the presumed address of an object of type T after a
  1084. /// cast. If T is a polymorphic class type, emit a check that the virtual
  1085. /// table for Derived belongs to a class derived from T.
  1086. void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
  1087. bool MayBeNull);
  1088. /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
  1089. /// If vptr CFI is enabled, emit a check that VTable is valid.
  1090. void EmitVTablePtrCheckForCall(const CXXMethodDecl *MD, llvm::Value *VTable);
  1091. /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
  1092. /// RD using llvm.bitset.test.
  1093. void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable);
  1094. /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
  1095. /// expr can be devirtualized.
  1096. bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
  1097. const CXXMethodDecl *MD);
  1098. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  1099. /// given phase of destruction for a destructor. The end result
  1100. /// should call destructors on members and base classes in reverse
  1101. /// order of their construction.
  1102. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  1103. /// ShouldInstrumentFunction - Return true if the current function should be
  1104. /// instrumented with __cyg_profile_func_* calls
  1105. bool ShouldInstrumentFunction();
  1106. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  1107. /// instrumentation function with the current function and the call site, if
  1108. /// function instrumentation is enabled.
  1109. void EmitFunctionInstrumentation(const char *Fn);
  1110. /// EmitMCountInstrumentation - Emit call to .mcount.
  1111. void EmitMCountInstrumentation();
  1112. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  1113. /// arguments for the given function. This is also responsible for naming the
  1114. /// LLVM function arguments.
  1115. void EmitFunctionProlog(const CGFunctionInfo &FI,
  1116. llvm::Function *Fn,
  1117. const FunctionArgList &Args);
  1118. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  1119. /// given temporary.
  1120. void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
  1121. SourceLocation EndLoc);
  1122. /// EmitStartEHSpec - Emit the start of the exception spec.
  1123. void EmitStartEHSpec(const Decl *D);
  1124. /// EmitEndEHSpec - Emit the end of the exception spec.
  1125. void EmitEndEHSpec(const Decl *D);
  1126. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  1127. llvm::BasicBlock *getTerminateLandingPad();
  1128. /// getTerminateHandler - Return a handler (not a landing pad, just
  1129. /// a catch handler) that just calls terminate. This is used when
  1130. /// a terminate scope encloses a try.
  1131. llvm::BasicBlock *getTerminateHandler();
  1132. llvm::Type *ConvertTypeForMem(QualType T);
  1133. llvm::Type *ConvertType(QualType T);
  1134. llvm::Type *ConvertType(const TypeDecl *T) {
  1135. return ConvertType(getContext().getTypeDeclType(T));
  1136. }
  1137. /// LoadObjCSelf - Load the value of self. This function is only valid while
  1138. /// generating code for an Objective-C method.
  1139. llvm::Value *LoadObjCSelf();
  1140. /// TypeOfSelfObject - Return type of object that this self represents.
  1141. QualType TypeOfSelfObject();
  1142. /// hasAggregateLLVMType - Return true if the specified AST type will map into
  1143. /// an aggregate LLVM type or is void.
  1144. static TypeEvaluationKind getEvaluationKind(QualType T);
  1145. static bool hasScalarEvaluationKind(QualType T) {
  1146. return getEvaluationKind(T) == TEK_Scalar;
  1147. }
  1148. static bool hasAggregateEvaluationKind(QualType T) {
  1149. return getEvaluationKind(T) == TEK_Aggregate;
  1150. }
  1151. /// createBasicBlock - Create an LLVM basic block.
  1152. llvm::BasicBlock *createBasicBlock(const Twine &name = "",
  1153. llvm::Function *parent = nullptr,
  1154. llvm::BasicBlock *before = nullptr) {
  1155. #ifdef NDEBUG
  1156. return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
  1157. #else
  1158. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  1159. #endif
  1160. }
  1161. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  1162. /// label maps to.
  1163. JumpDest getJumpDestForLabel(const LabelDecl *S);
  1164. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  1165. /// another basic block, simplify it. This assumes that no other code could
  1166. /// potentially reference the basic block.
  1167. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  1168. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  1169. /// adding a fall-through branch from the current insert block if
  1170. /// necessary. It is legal to call this function even if there is no current
  1171. /// insertion point.
  1172. ///
  1173. /// IsFinished - If true, indicates that the caller has finished emitting
  1174. /// branches to the given block and does not expect to emit code into it. This
  1175. /// means the block can be ignored if it is unreachable.
  1176. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  1177. /// EmitBlockAfterUses - Emit the given block somewhere hopefully
  1178. /// near its uses, and leave the insertion point in it.
  1179. void EmitBlockAfterUses(llvm::BasicBlock *BB);
  1180. /// EmitBranch - Emit a branch to the specified basic block from the current
  1181. /// insert block, taking care to avoid creation of branches from dummy
  1182. /// blocks. It is legal to call this function even if there is no current
  1183. /// insertion point.
  1184. ///
  1185. /// This function clears the current insertion point. The caller should follow
  1186. /// calls to this function with calls to Emit*Block prior to generation new
  1187. /// code.
  1188. void EmitBranch(llvm::BasicBlock *Block);
  1189. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  1190. /// indicates that the current code being emitted is unreachable.
  1191. bool HaveInsertPoint() const {
  1192. return Builder.GetInsertBlock() != nullptr;
  1193. }
  1194. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  1195. /// emitted IR has a place to go. Note that by definition, if this function
  1196. /// creates a block then that block is unreachable; callers may do better to
  1197. /// detect when no insertion point is defined and simply skip IR generation.
  1198. void EnsureInsertPoint() {
  1199. if (!HaveInsertPoint())
  1200. EmitBlock(createBasicBlock());
  1201. }
  1202. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1203. /// specified stmt yet.
  1204. void ErrorUnsupported(const Stmt *S, const char *Type);
  1205. //===--------------------------------------------------------------------===//
  1206. // Helpers
  1207. //===--------------------------------------------------------------------===//
  1208. LValue MakeAddrLValue(llvm::Value *V, QualType T,
  1209. CharUnits Alignment = CharUnits()) {
  1210. return LValue::MakeAddr(V, T, Alignment, getContext(),
  1211. CGM.getTBAAInfo(T));
  1212. }
  1213. LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
  1214. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  1215. /// block. The caller is responsible for setting an appropriate alignment on
  1216. /// the alloca.
  1217. llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
  1218. const Twine &Name = "tmp");
  1219. /// InitTempAlloca - Provide an initial value for the given alloca.
  1220. void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
  1221. /// CreateIRTemp - Create a temporary IR object of the given type, with
  1222. /// appropriate alignment. This routine should only be used when an temporary
  1223. /// value needs to be stored into an alloca (for example, to avoid explicit
  1224. /// PHI construction), but the type is the IR type, not the type appropriate
  1225. /// for storing in memory.
  1226. llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp");
  1227. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1228. /// appropriate alignment.
  1229. llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp");
  1230. /// CreateAggTemp - Create a temporary memory object for the given
  1231. /// aggregate type.
  1232. AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
  1233. CharUnits Alignment = getContext().getTypeAlignInChars(T);
  1234. return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment,
  1235. T.getQualifiers(),
  1236. AggValueSlot::IsNotDestructed,
  1237. AggValueSlot::DoesNotNeedGCBarriers,
  1238. AggValueSlot::IsNotAliased);
  1239. }
  1240. /// CreateInAllocaTmp - Create a temporary memory object for the given
  1241. /// aggregate type.
  1242. AggValueSlot CreateInAllocaTmp(QualType T, const Twine &Name = "inalloca");
  1243. /// Emit a cast to void* in the appropriate address space.
  1244. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  1245. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  1246. /// expression and compare the result against zero, returning an Int1Ty value.
  1247. llvm::Value *EvaluateExprAsBool(const Expr *E);
  1248. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  1249. void EmitIgnoredExpr(const Expr *E);
  1250. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  1251. /// any type. The result is returned as an RValue struct. If this is an
  1252. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  1253. /// the result should be returned.
  1254. ///
  1255. /// \param ignoreResult True if the resulting value isn't used.
  1256. RValue EmitAnyExpr(const Expr *E,
  1257. AggValueSlot aggSlot = AggValueSlot::ignored(),
  1258. bool ignoreResult = false);
  1259. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  1260. // or the value of the expression, depending on how va_list is defined.
  1261. llvm::Value *EmitVAListRef(const Expr *E);
  1262. /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
  1263. /// always be accessible even if no aggregate location is provided.
  1264. RValue EmitAnyExprToTemp(const Expr *E);
  1265. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  1266. /// arbitrary expression into the given memory location.
  1267. void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
  1268. Qualifiers Quals, bool IsInitializer);
  1269. void EmitAnyExprToExn(const Expr *E, llvm::Value *Addr);
  1270. /// EmitExprAsInit - Emits the code necessary to initialize a
  1271. /// location in memory with the given initializer.
  1272. void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  1273. bool capturedByInit);
  1274. /// hasVolatileMember - returns true if aggregate type has a volatile
  1275. /// member.
  1276. bool hasVolatileMember(QualType T) {
  1277. if (const RecordType *RT = T->getAs<RecordType>()) {
  1278. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  1279. return RD->hasVolatileMember();
  1280. }
  1281. return false;
  1282. }
  1283. /// EmitAggregateCopy - Emit an aggregate assignment.
  1284. ///
  1285. /// The difference to EmitAggregateCopy is that tail padding is not copied.
  1286. /// This is required for correctness when assigning non-POD structures in C++.
  1287. void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1288. QualType EltTy) {
  1289. bool IsVolatile = hasVolatileMember(EltTy);
  1290. EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, CharUnits::Zero(),
  1291. true);
  1292. }
  1293. void EmitAggregateCopyCtor(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1294. QualType DestTy, QualType SrcTy) {
  1295. CharUnits DestTypeAlign = getContext().getTypeAlignInChars(DestTy);
  1296. CharUnits SrcTypeAlign = getContext().getTypeAlignInChars(SrcTy);
  1297. EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
  1298. std::min(DestTypeAlign, SrcTypeAlign),
  1299. /*IsAssignment=*/false);
  1300. }
  1301. /// EmitAggregateCopy - Emit an aggregate copy.
  1302. ///
  1303. /// \param isVolatile - True iff either the source or the destination is
  1304. /// volatile.
  1305. /// \param isAssignment - If false, allow padding to be copied. This often
  1306. /// yields more efficient.
  1307. void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1308. QualType EltTy, bool isVolatile=false,
  1309. CharUnits Alignment = CharUnits::Zero(),
  1310. bool isAssignment = false);
  1311. /// StartBlock - Start new block named N. If insert block is a dummy block
  1312. /// then reuse it.
  1313. void StartBlock(const char *N);
  1314. /// GetAddrOfLocalVar - Return the address of a local variable.
  1315. llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
  1316. llvm::Value *Res = LocalDeclMap[VD];
  1317. assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
  1318. return Res;
  1319. }
  1320. /// getOpaqueLValueMapping - Given an opaque value expression (which
  1321. /// must be mapped to an l-value), return its mapping.
  1322. const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
  1323. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  1324. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  1325. it = OpaqueLValues.find(e);
  1326. assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
  1327. return it->second;
  1328. }
  1329. /// getOpaqueRValueMapping - Given an opaque value expression (which
  1330. /// must be mapped to an r-value), return its mapping.
  1331. const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
  1332. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  1333. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  1334. it = OpaqueRValues.find(e);
  1335. assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
  1336. return it->second;
  1337. }
  1338. /// getAccessedFieldNo - Given an encoded value and a result number, return
  1339. /// the input field number being accessed.
  1340. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  1341. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  1342. llvm::BasicBlock *GetIndirectGotoBlock();
  1343. /// EmitNullInitialization - Generate code to set a value of the given type to
  1344. /// null, If the type contains data member pointers, they will be initialized
  1345. /// to -1 in accordance with the Itanium C++ ABI.
  1346. void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
  1347. // EmitVAArg - Generate code to get an argument from the passed in pointer
  1348. // and update it accordingly. The return value is a pointer to the argument.
  1349. // FIXME: We should be able to get rid of this method and use the va_arg
  1350. // instruction in LLVM instead once it works well enough.
  1351. llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
  1352. /// emitArrayLength - Compute the length of an array, even if it's a
  1353. /// VLA, and drill down to the base element type.
  1354. llvm::Value *emitArrayLength(const ArrayType *arrayType,
  1355. QualType &baseType,
  1356. llvm::Value *&addr);
  1357. /// EmitVLASize - Capture all the sizes for the VLA expressions in
  1358. /// the given variably-modified type and store them in the VLASizeMap.
  1359. ///
  1360. /// This function can be called with a null (unreachable) insert point.
  1361. void EmitVariablyModifiedType(QualType Ty);
  1362. /// getVLASize - Returns an LLVM value that corresponds to the size,
  1363. /// in non-variably-sized elements, of a variable length array type,
  1364. /// plus that largest non-variably-sized element type. Assumes that
  1365. /// the type has already been emitted with EmitVariablyModifiedType.
  1366. std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
  1367. std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
  1368. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  1369. /// generating code for an C++ member function.
  1370. llvm::Value *LoadCXXThis() {
  1371. assert(CXXThisValue && "no 'this' value for this function");
  1372. return CXXThisValue;
  1373. }
  1374. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  1375. /// virtual bases.
  1376. // FIXME: Every place that calls LoadCXXVTT is something
  1377. // that needs to be abstracted properly.
  1378. llvm::Value *LoadCXXVTT() {
  1379. assert(CXXStructorImplicitParamValue && "no VTT value for this function");
  1380. return CXXStructorImplicitParamValue;
  1381. }
  1382. /// LoadCXXStructorImplicitParam - Load the implicit parameter
  1383. /// for a constructor/destructor.
  1384. llvm::Value *LoadCXXStructorImplicitParam() {
  1385. assert(CXXStructorImplicitParamValue &&
  1386. "no implicit argument value for this function");
  1387. return CXXStructorImplicitParamValue;
  1388. }
  1389. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  1390. /// complete class to the given direct base.
  1391. llvm::Value *
  1392. GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
  1393. const CXXRecordDecl *Derived,
  1394. const CXXRecordDecl *Base,
  1395. bool BaseIsVirtual);
  1396. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  1397. /// load of 'this' and returns address of the base class.
  1398. llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
  1399. const CXXRecordDecl *Derived,
  1400. CastExpr::path_const_iterator PathBegin,
  1401. CastExpr::path_const_iterator PathEnd,
  1402. bool NullCheckValue, SourceLocation Loc);
  1403. llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
  1404. const CXXRecordDecl *Derived,
  1405. CastExpr::path_const_iterator PathBegin,
  1406. CastExpr::path_const_iterator PathEnd,
  1407. bool NullCheckValue);
  1408. /// GetVTTParameter - Return the VTT parameter that should be passed to a
  1409. /// base constructor/destructor with virtual bases.
  1410. /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
  1411. /// to ItaniumCXXABI.cpp together with all the references to VTT.
  1412. llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
  1413. bool Delegating);
  1414. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1415. CXXCtorType CtorType,
  1416. const FunctionArgList &Args,
  1417. SourceLocation Loc);
  1418. // It's important not to confuse this and the previous function. Delegating
  1419. // constructors are the C++0x feature. The constructor delegate optimization
  1420. // is used to reduce duplication in the base and complete consturctors where
  1421. // they are substantially the same.
  1422. void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1423. const FunctionArgList &Args);
  1424. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  1425. bool ForVirtualBase, bool Delegating,
  1426. llvm::Value *This, const CXXConstructExpr *E);
  1427. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1428. llvm::Value *This, llvm::Value *Src,
  1429. const CXXConstructExpr *E);
  1430. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1431. const ConstantArrayType *ArrayTy,
  1432. llvm::Value *ArrayPtr,
  1433. const CXXConstructExpr *E,
  1434. bool ZeroInitialization = false);
  1435. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1436. llvm::Value *NumElements,
  1437. llvm::Value *ArrayPtr,
  1438. const CXXConstructExpr *E,
  1439. bool ZeroInitialization = false);
  1440. static Destroyer destroyCXXObject;
  1441. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  1442. bool ForVirtualBase, bool Delegating,
  1443. llvm::Value *This);
  1444. void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
  1445. llvm::Type *ElementTy, llvm::Value *NewPtr,
  1446. llvm::Value *NumElements,
  1447. llvm::Value *AllocSizeWithoutCookie);
  1448. void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
  1449. llvm::Value *Ptr);
  1450. llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
  1451. void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
  1452. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  1453. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  1454. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  1455. QualType DeleteTy);
  1456. RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
  1457. const Expr *Arg, bool IsDelete);
  1458. llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  1459. llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
  1460. llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E);
  1461. /// \brief Situations in which we might emit a check for the suitability of a
  1462. /// pointer or glvalue.
  1463. enum TypeCheckKind {
  1464. /// Checking the operand of a load. Must be suitably sized and aligned.
  1465. TCK_Load,
  1466. /// Checking the destination of a store. Must be suitably sized and aligned.
  1467. TCK_Store,
  1468. /// Checking the bound value in a reference binding. Must be suitably sized
  1469. /// and aligned, but is not required to refer to an object (until the
  1470. /// reference is used), per core issue 453.
  1471. TCK_ReferenceBinding,
  1472. /// Checking the object expression in a non-static data member access. Must
  1473. /// be an object within its lifetime.
  1474. TCK_MemberAccess,
  1475. /// Checking the 'this' pointer for a call to a non-static member function.
  1476. /// Must be an object within its lifetime.
  1477. TCK_MemberCall,
  1478. /// Checking the 'this' pointer for a constructor call.
  1479. TCK_ConstructorCall,
  1480. /// Checking the operand of a static_cast to a derived pointer type. Must be
  1481. /// null or an object within its lifetime.
  1482. TCK_DowncastPointer,
  1483. /// Checking the operand of a static_cast to a derived reference type. Must
  1484. /// be an object within its lifetime.
  1485. TCK_DowncastReference,
  1486. /// Checking the operand of a cast to a base object. Must be suitably sized
  1487. /// and aligned.
  1488. TCK_Upcast,
  1489. /// Checking the operand of a cast to a virtual base object. Must be an
  1490. /// object within its lifetime.
  1491. TCK_UpcastToVirtualBase
  1492. };
  1493. /// \brief Whether any type-checking sanitizers are enabled. If \c false,
  1494. /// calls to EmitTypeCheck can be skipped.
  1495. bool sanitizePerformTypeCheck() const;
  1496. /// \brief Emit a check that \p V is the address of storage of the
  1497. /// appropriate size and alignment for an object of type \p Type.
  1498. void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
  1499. QualType Type, CharUnits Alignment = CharUnits::Zero(),
  1500. bool SkipNullCheck = false);
  1501. /// \brief Emit a check that \p Base points into an array object, which
  1502. /// we can access at index \p Index. \p Accessed should be \c false if we
  1503. /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
  1504. void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
  1505. QualType IndexType, bool Accessed);
  1506. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  1507. bool isInc, bool isPre);
  1508. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  1509. bool isInc, bool isPre);
  1510. void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
  1511. llvm::Value *OffsetValue = nullptr) {
  1512. Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
  1513. OffsetValue);
  1514. }
  1515. //===--------------------------------------------------------------------===//
  1516. // Declaration Emission
  1517. //===--------------------------------------------------------------------===//
  1518. /// EmitDecl - Emit a declaration.
  1519. ///
  1520. /// This function can be called with a null (unreachable) insert point.
  1521. void EmitDecl(const Decl &D);
  1522. /// EmitVarDecl - Emit a local variable declaration.
  1523. ///
  1524. /// This function can be called with a null (unreachable) insert point.
  1525. void EmitVarDecl(const VarDecl &D);
  1526. void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  1527. bool capturedByInit);
  1528. void EmitScalarInit(llvm::Value *init, LValue lvalue);
  1529. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  1530. llvm::Value *Address);
  1531. /// \brief Determine whether the given initializer is trivial in the sense
  1532. /// that it requires no code to be generated.
  1533. bool isTrivialInitializer(const Expr *Init);
  1534. /// EmitAutoVarDecl - Emit an auto variable declaration.
  1535. ///
  1536. /// This function can be called with a null (unreachable) insert point.
  1537. void EmitAutoVarDecl(const VarDecl &D);
  1538. class AutoVarEmission {
  1539. friend class CodeGenFunction;
  1540. const VarDecl *Variable;
  1541. /// The alignment of the variable.
  1542. CharUnits Alignment;
  1543. /// The address of the alloca. Null if the variable was emitted
  1544. /// as a global constant.
  1545. llvm::Value *Address;
  1546. llvm::Value *NRVOFlag;
  1547. /// True if the variable is a __block variable.
  1548. bool IsByRef;
  1549. /// True if the variable is of aggregate type and has a constant
  1550. /// initializer.
  1551. bool IsConstantAggregate;
  1552. /// Non-null if we should use lifetime annotations.
  1553. llvm::Value *SizeForLifetimeMarkers;
  1554. struct Invalid {};
  1555. AutoVarEmission(Invalid) : Variable(nullptr) {}
  1556. AutoVarEmission(const VarDecl &variable)
  1557. : Variable(&variable), Address(nullptr), NRVOFlag(nullptr),
  1558. IsByRef(false), IsConstantAggregate(false),
  1559. SizeForLifetimeMarkers(nullptr) {}
  1560. bool wasEmittedAsGlobal() const { return Address == nullptr; }
  1561. public:
  1562. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  1563. bool useLifetimeMarkers() const {
  1564. return SizeForLifetimeMarkers != nullptr;
  1565. }
  1566. llvm::Value *getSizeForLifetimeMarkers() const {
  1567. assert(useLifetimeMarkers());
  1568. return SizeForLifetimeMarkers;
  1569. }
  1570. /// Returns the raw, allocated address, which is not necessarily
  1571. /// the address of the object itself.
  1572. llvm::Value *getAllocatedAddress() const {
  1573. return Address;
  1574. }
  1575. /// Returns the address of the object within this declaration.
  1576. /// Note that this does not chase the forwarding pointer for
  1577. /// __block decls.
  1578. llvm::Value *getObjectAddress(CodeGenFunction &CGF) const {
  1579. if (!IsByRef) return Address;
  1580. auto F = CGF.getByRefValueLLVMField(Variable);
  1581. return CGF.Builder.CreateStructGEP(F.first, Address, F.second,
  1582. Variable->getNameAsString());
  1583. }
  1584. };
  1585. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  1586. void EmitAutoVarInit(const AutoVarEmission &emission);
  1587. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  1588. void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
  1589. QualType::DestructionKind dtorKind);
  1590. void EmitStaticVarDecl(const VarDecl &D,
  1591. llvm::GlobalValue::LinkageTypes Linkage);
  1592. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  1593. void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, bool ArgIsPointer,
  1594. unsigned ArgNo);
  1595. /// protectFromPeepholes - Protect a value that we're intending to
  1596. /// store to the side, but which will probably be used later, from
  1597. /// aggressive peepholing optimizations that might delete it.
  1598. ///
  1599. /// Pass the result to unprotectFromPeepholes to declare that
  1600. /// protection is no longer required.
  1601. ///
  1602. /// There's no particular reason why this shouldn't apply to
  1603. /// l-values, it's just that no existing peepholes work on pointers.
  1604. PeepholeProtection protectFromPeepholes(RValue rvalue);
  1605. void unprotectFromPeepholes(PeepholeProtection protection);
  1606. //===--------------------------------------------------------------------===//
  1607. // Statement Emission
  1608. //===--------------------------------------------------------------------===//
  1609. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  1610. void EmitStopPoint(const Stmt *S);
  1611. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  1612. /// this function even if there is no current insertion point.
  1613. ///
  1614. /// This function may clear the current insertion point; callers should use
  1615. /// EnsureInsertPoint if they wish to subsequently generate code without first
  1616. /// calling EmitBlock, EmitBranch, or EmitStmt.
  1617. void EmitStmt(const Stmt *S);
  1618. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  1619. /// necessarily require an insertion point or debug information; typically
  1620. /// because the statement amounts to a jump or a container of other
  1621. /// statements.
  1622. ///
  1623. /// \return True if the statement was handled.
  1624. bool EmitSimpleStmt(const Stmt *S);
  1625. llvm::Value *EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  1626. AggValueSlot AVS = AggValueSlot::ignored());
  1627. llvm::Value *EmitCompoundStmtWithoutScope(const CompoundStmt &S,
  1628. bool GetLast = false,
  1629. AggValueSlot AVS =
  1630. AggValueSlot::ignored());
  1631. /// EmitLabel - Emit the block for the given label. It is legal to call this
  1632. /// function even if there is no current insertion point.
  1633. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  1634. void EmitLabelStmt(const LabelStmt &S);
  1635. void EmitAttributedStmt(const AttributedStmt &S);
  1636. void EmitGotoStmt(const GotoStmt &S);
  1637. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  1638. void EmitIfStmt(const IfStmt &S);
  1639. void EmitCondBrHints(llvm::LLVMContext &Context, llvm::BranchInst *CondBr,
  1640. ArrayRef<const Attr *> Attrs);
  1641. void EmitWhileStmt(const WhileStmt &S,
  1642. ArrayRef<const Attr *> Attrs = None);
  1643. void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
  1644. void EmitForStmt(const ForStmt &S,
  1645. ArrayRef<const Attr *> Attrs = None);
  1646. void EmitReturnStmt(const ReturnStmt &S);
  1647. void EmitDeclStmt(const DeclStmt &S);
  1648. void EmitBreakStmt(const BreakStmt &S);
  1649. void EmitContinueStmt(const ContinueStmt &S);
  1650. void EmitSwitchStmt(const SwitchStmt &S);
  1651. void EmitDefaultStmt(const DefaultStmt &S);
  1652. void EmitCaseStmt(const CaseStmt &S);
  1653. void EmitCaseStmtRange(const CaseStmt &S);
  1654. void EmitAsmStmt(const AsmStmt &S);
  1655. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  1656. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  1657. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  1658. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  1659. void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
  1660. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1661. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1662. void EmitCXXTryStmt(const CXXTryStmt &S);
  1663. void EmitSEHTryStmt(const SEHTryStmt &S);
  1664. void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
  1665. void EnterSEHTryStmt(const SEHTryStmt &S);
  1666. void ExitSEHTryStmt(const SEHTryStmt &S);
  1667. void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, StringRef Name,
  1668. QualType RetTy, FunctionArgList &Args,
  1669. const Stmt *OutlinedStmt);
  1670. llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
  1671. const SEHExceptStmt &Except);
  1672. llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
  1673. const SEHFinallyStmt &Finally);
  1674. void EmitSEHExceptionCodeSave();
  1675. llvm::Value *EmitSEHExceptionCode();
  1676. llvm::Value *EmitSEHExceptionInfo();
  1677. llvm::Value *EmitSEHAbnormalTermination();
  1678. /// Scan the outlined statement for captures from the parent function. For
  1679. /// each capture, mark the capture as escaped and emit a call to
  1680. /// llvm.framerecover. Insert the framerecover result into the LocalDeclMap.
  1681. void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt);
  1682. /// Recovers the address of a local in a parent function. ParentVar is the
  1683. /// address of the variable used in the immediate parent function. It can
  1684. /// either be an alloca or a call to llvm.framerecover if there are nested
  1685. /// outlined functions. ParentFP is the frame pointer of the outermost parent
  1686. /// frame.
  1687. llvm::Value *recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
  1688. llvm::Value *ParentVar,
  1689. llvm::Value *ParentFP);
  1690. void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
  1691. ArrayRef<const Attr *> Attrs = None);
  1692. LValue InitCapturedStruct(const CapturedStmt &S);
  1693. llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
  1694. void GenerateCapturedStmtFunctionProlog(const CapturedStmt &S);
  1695. llvm::Function *GenerateCapturedStmtFunctionEpilog(const CapturedStmt &S);
  1696. llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
  1697. llvm::Value *GenerateCapturedStmtArgument(const CapturedStmt &S);
  1698. /// \brief Perform element by element copying of arrays with type \a
  1699. /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
  1700. /// generated by \a CopyGen.
  1701. ///
  1702. /// \param DestAddr Address of the destination array.
  1703. /// \param SrcAddr Address of the source array.
  1704. /// \param OriginalType Type of destination and source arrays.
  1705. /// \param CopyGen Copying procedure that copies value of single array element
  1706. /// to another single array element.
  1707. void EmitOMPAggregateAssign(
  1708. llvm::Value *DestAddr, llvm::Value *SrcAddr, QualType OriginalType,
  1709. const llvm::function_ref<void(llvm::Value *, llvm::Value *)> &CopyGen);
  1710. /// \brief Emit proper copying of data from one variable to another.
  1711. ///
  1712. /// \param OriginalType Original type of the copied variables.
  1713. /// \param DestAddr Destination address.
  1714. /// \param SrcAddr Source address.
  1715. /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
  1716. /// type of the base array element).
  1717. /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
  1718. /// the base array element).
  1719. /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
  1720. /// DestVD.
  1721. void EmitOMPCopy(CodeGenFunction &CGF, QualType OriginalType,
  1722. llvm::Value *DestAddr, llvm::Value *SrcAddr,
  1723. const VarDecl *DestVD, const VarDecl *SrcVD,
  1724. const Expr *Copy);
  1725. /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
  1726. /// \a X = \a E \a BO \a E.
  1727. ///
  1728. /// \param X Value to be updated.
  1729. /// \param E Update value.
  1730. /// \param BO Binary operation for update operation.
  1731. /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
  1732. /// expression, false otherwise.
  1733. /// \param AO Atomic ordering of the generated atomic instructions.
  1734. /// \param CommonGen Code generator for complex expressions that cannot be
  1735. /// expressed through atomicrmw instruction.
  1736. /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
  1737. /// generated, <false, RValue::get(nullptr)> otherwise.
  1738. std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
  1739. LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
  1740. llvm::AtomicOrdering AO, SourceLocation Loc,
  1741. const llvm::function_ref<RValue(RValue)> &CommonGen);
  1742. bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
  1743. OMPPrivateScope &PrivateScope);
  1744. void EmitOMPPrivateClause(const OMPExecutableDirective &D,
  1745. OMPPrivateScope &PrivateScope);
  1746. /// \brief Emit code for copyin clause in \a D directive. The next code is
  1747. /// generated at the start of outlined functions for directives:
  1748. /// \code
  1749. /// threadprivate_var1 = master_threadprivate_var1;
  1750. /// operator=(threadprivate_var2, master_threadprivate_var2);
  1751. /// ...
  1752. /// __kmpc_barrier(&loc, global_tid);
  1753. /// \endcode
  1754. ///
  1755. /// \param D OpenMP directive possibly with 'copyin' clause(s).
  1756. /// \returns true if at least one copyin variable is found, false otherwise.
  1757. bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
  1758. /// \brief Emit initial code for lastprivate variables. If some variable is
  1759. /// not also firstprivate, then the default initialization is used. Otherwise
  1760. /// initialization of this variable is performed by EmitOMPFirstprivateClause
  1761. /// method.
  1762. ///
  1763. /// \param D Directive that may have 'lastprivate' directives.
  1764. /// \param PrivateScope Private scope for capturing lastprivate variables for
  1765. /// proper codegen in internal captured statement.
  1766. ///
  1767. /// \returns true if there is at least one lastprivate variable, false
  1768. /// otherwise.
  1769. bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
  1770. OMPPrivateScope &PrivateScope);
  1771. /// \brief Emit final copying of lastprivate values to original variables at
  1772. /// the end of the worksharing or simd directive.
  1773. ///
  1774. /// \param D Directive that has at least one 'lastprivate' directives.
  1775. /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
  1776. /// it is the last iteration of the loop code in associated directive, or to
  1777. /// 'i1 false' otherwise.
  1778. void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
  1779. llvm::Value *IsLastIterCond);
  1780. /// \brief Emit initial code for reduction variables. Creates reduction copies
  1781. /// and initializes them with the values according to OpenMP standard.
  1782. ///
  1783. /// \param D Directive (possibly) with the 'reduction' clause.
  1784. /// \param PrivateScope Private scope for capturing reduction variables for
  1785. /// proper codegen in internal captured statement.
  1786. ///
  1787. void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
  1788. OMPPrivateScope &PrivateScope);
  1789. /// \brief Emit final update of reduction values to original variables at
  1790. /// the end of the directive.
  1791. ///
  1792. /// \param D Directive that has at least one 'reduction' directives.
  1793. void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D);
  1794. void EmitOMPParallelDirective(const OMPParallelDirective &S);
  1795. void EmitOMPSimdDirective(const OMPSimdDirective &S);
  1796. void EmitOMPForDirective(const OMPForDirective &S);
  1797. void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
  1798. void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
  1799. void EmitOMPSectionDirective(const OMPSectionDirective &S);
  1800. void EmitOMPSingleDirective(const OMPSingleDirective &S);
  1801. void EmitOMPMasterDirective(const OMPMasterDirective &S);
  1802. void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
  1803. void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
  1804. void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
  1805. void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
  1806. void EmitOMPTaskDirective(const OMPTaskDirective &S);
  1807. void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
  1808. void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
  1809. void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
  1810. void EmitOMPFlushDirective(const OMPFlushDirective &S);
  1811. void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
  1812. void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
  1813. void EmitOMPTargetDirective(const OMPTargetDirective &S);
  1814. void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
  1815. /// \brief Emit inner loop of the worksharing/simd construct.
  1816. ///
  1817. /// \param S Directive, for which the inner loop must be emitted.
  1818. /// \param RequiresCleanup true, if directive has some associated private
  1819. /// variables.
  1820. /// \param LoopCond Bollean condition for loop continuation.
  1821. /// \param IncExpr Increment expression for loop control variable.
  1822. /// \param BodyGen Generator for the inner body of the inner loop.
  1823. /// \param PostIncGen Genrator for post-increment code (required for ordered
  1824. /// loop directvies).
  1825. void EmitOMPInnerLoop(
  1826. const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
  1827. const Expr *IncExpr,
  1828. const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
  1829. const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
  1830. private:
  1831. /// Helpers for the OpenMP loop directives.
  1832. void EmitOMPLoopBody(const OMPLoopDirective &Directive,
  1833. bool SeparateIter = false);
  1834. void EmitOMPSimdFinal(const OMPLoopDirective &S);
  1835. /// \brief Emit code for the worksharing loop-based directive.
  1836. /// \return true, if this construct has any lastprivate clause, false -
  1837. /// otherwise.
  1838. bool EmitOMPWorksharingLoop(const OMPLoopDirective &S);
  1839. void EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
  1840. const OMPLoopDirective &S,
  1841. OMPPrivateScope &LoopScope, llvm::Value *LB,
  1842. llvm::Value *UB, llvm::Value *ST, llvm::Value *IL,
  1843. llvm::Value *Chunk);
  1844. public:
  1845. //===--------------------------------------------------------------------===//
  1846. // LValue Expression Emission
  1847. //===--------------------------------------------------------------------===//
  1848. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  1849. RValue GetUndefRValue(QualType Ty);
  1850. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  1851. /// and issue an ErrorUnsupported style diagnostic (using the
  1852. /// provided Name).
  1853. RValue EmitUnsupportedRValue(const Expr *E,
  1854. const char *Name);
  1855. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  1856. /// an ErrorUnsupported style diagnostic (using the provided Name).
  1857. LValue EmitUnsupportedLValue(const Expr *E,
  1858. const char *Name);
  1859. /// EmitLValue - Emit code to compute a designator that specifies the location
  1860. /// of the expression.
  1861. ///
  1862. /// This can return one of two things: a simple address or a bitfield
  1863. /// reference. In either case, the LLVM Value* in the LValue structure is
  1864. /// guaranteed to be an LLVM pointer type.
  1865. ///
  1866. /// If this returns a bitfield reference, nothing about the pointee type of
  1867. /// the LLVM value is known: For example, it may not be a pointer to an
  1868. /// integer.
  1869. ///
  1870. /// If this returns a normal address, and if the lvalue's C type is fixed
  1871. /// size, this method guarantees that the returned pointer type will point to
  1872. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  1873. /// variable length type, this is not possible.
  1874. ///
  1875. LValue EmitLValue(const Expr *E);
  1876. /// \brief Same as EmitLValue but additionally we generate checking code to
  1877. /// guard against undefined behavior. This is only suitable when we know
  1878. /// that the address will be used to access the object.
  1879. LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
  1880. RValue convertTempToRValue(llvm::Value *addr, QualType type,
  1881. SourceLocation Loc);
  1882. void EmitAtomicInit(Expr *E, LValue lvalue);
  1883. bool LValueIsSuitableForInlineAtomic(LValue Src);
  1884. bool typeIsSuitableForInlineAtomic(QualType Ty, bool IsVolatile) const;
  1885. RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
  1886. AggValueSlot Slot = AggValueSlot::ignored());
  1887. RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
  1888. llvm::AtomicOrdering AO, bool IsVolatile = false,
  1889. AggValueSlot slot = AggValueSlot::ignored());
  1890. void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
  1891. void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
  1892. bool IsVolatile, bool isInit);
  1893. std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
  1894. LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
  1895. llvm::AtomicOrdering Success = llvm::SequentiallyConsistent,
  1896. llvm::AtomicOrdering Failure = llvm::SequentiallyConsistent,
  1897. bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
  1898. void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
  1899. const std::function<RValue(RValue)> &UpdateOp,
  1900. bool IsVolatile);
  1901. /// EmitToMemory - Change a scalar value from its value
  1902. /// representation to its in-memory representation.
  1903. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  1904. /// EmitFromMemory - Change a scalar value from its memory
  1905. /// representation to its value representation.
  1906. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  1907. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  1908. /// care to appropriately convert from the memory representation to
  1909. /// the LLVM value representation.
  1910. llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
  1911. unsigned Alignment, QualType Ty,
  1912. SourceLocation Loc,
  1913. llvm::MDNode *TBAAInfo = nullptr,
  1914. QualType TBAABaseTy = QualType(),
  1915. uint64_t TBAAOffset = 0);
  1916. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  1917. /// care to appropriately convert from the memory representation to
  1918. /// the LLVM value representation. The l-value must be a simple
  1919. /// l-value.
  1920. llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
  1921. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  1922. /// care to appropriately convert from the memory representation to
  1923. /// the LLVM value representation.
  1924. void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
  1925. bool Volatile, unsigned Alignment, QualType Ty,
  1926. llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
  1927. QualType TBAABaseTy = QualType(),
  1928. uint64_t TBAAOffset = 0);
  1929. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  1930. /// care to appropriately convert from the memory representation to
  1931. /// the LLVM value representation. The l-value must be a simple
  1932. /// l-value. The isInit flag indicates whether this is an initialization.
  1933. /// If so, atomic qualifiers are ignored and the store is always non-atomic.
  1934. void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
  1935. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  1936. /// this method emits the address of the lvalue, then loads the result as an
  1937. /// rvalue, returning the rvalue.
  1938. RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
  1939. RValue EmitLoadOfExtVectorElementLValue(LValue V);
  1940. RValue EmitLoadOfBitfieldLValue(LValue LV);
  1941. RValue EmitLoadOfGlobalRegLValue(LValue LV);
  1942. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  1943. /// lvalue, where both are guaranteed to the have the same type, and that type
  1944. /// is 'Ty'.
  1945. void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
  1946. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
  1947. void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
  1948. /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
  1949. /// as EmitStoreThroughLValue.
  1950. ///
  1951. /// \param Result [out] - If non-null, this will be set to a Value* for the
  1952. /// bit-field contents after the store, appropriate for use as the result of
  1953. /// an assignment to the bit-field.
  1954. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  1955. llvm::Value **Result=nullptr);
  1956. /// Emit an l-value for an assignment (simple or compound) of complex type.
  1957. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  1958. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  1959. LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
  1960. llvm::Value *&Result);
  1961. // Note: only available for agg return types
  1962. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  1963. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  1964. // Note: only available for agg return types
  1965. LValue EmitCallExprLValue(const CallExpr *E);
  1966. // Note: only available for agg return types
  1967. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  1968. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  1969. LValue EmitReadRegister(const VarDecl *VD);
  1970. LValue EmitStringLiteralLValue(const StringLiteral *E);
  1971. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  1972. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  1973. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  1974. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  1975. bool Accessed = false);
  1976. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  1977. LValue EmitMemberExpr(const MemberExpr *E);
  1978. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  1979. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  1980. LValue EmitInitListLValue(const InitListExpr *E);
  1981. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  1982. LValue EmitCastLValue(const CastExpr *E);
  1983. LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  1984. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  1985. llvm::Value *EmitExtVectorElementLValue(LValue V);
  1986. RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
  1987. class ConstantEmission {
  1988. llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
  1989. ConstantEmission(llvm::Constant *C, bool isReference)
  1990. : ValueAndIsReference(C, isReference) {}
  1991. public:
  1992. ConstantEmission() {}
  1993. static ConstantEmission forReference(llvm::Constant *C) {
  1994. return ConstantEmission(C, true);
  1995. }
  1996. static ConstantEmission forValue(llvm::Constant *C) {
  1997. return ConstantEmission(C, false);
  1998. }
  1999. explicit operator bool() const {
  2000. return ValueAndIsReference.getOpaqueValue() != nullptr;
  2001. }
  2002. bool isReference() const { return ValueAndIsReference.getInt(); }
  2003. LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
  2004. assert(isReference());
  2005. return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
  2006. refExpr->getType());
  2007. }
  2008. llvm::Constant *getValue() const {
  2009. assert(!isReference());
  2010. return ValueAndIsReference.getPointer();
  2011. }
  2012. };
  2013. ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
  2014. RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
  2015. AggValueSlot slot = AggValueSlot::ignored());
  2016. LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
  2017. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  2018. const ObjCIvarDecl *Ivar);
  2019. LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
  2020. LValue EmitLValueForLambdaField(const FieldDecl *Field);
  2021. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  2022. /// if the Field is a reference, this will return the address of the reference
  2023. /// and not the address of the value stored in the reference.
  2024. LValue EmitLValueForFieldInitialization(LValue Base,
  2025. const FieldDecl* Field);
  2026. LValue EmitLValueForIvar(QualType ObjectTy,
  2027. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  2028. unsigned CVRQualifiers);
  2029. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  2030. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  2031. LValue EmitLambdaLValue(const LambdaExpr *E);
  2032. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  2033. LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
  2034. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  2035. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  2036. LValue EmitStmtExprLValue(const StmtExpr *E);
  2037. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  2038. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  2039. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
  2040. //===--------------------------------------------------------------------===//
  2041. // Scalar Expression Emission
  2042. //===--------------------------------------------------------------------===//
  2043. /// EmitCall - Generate a call of the given function, expecting the given
  2044. /// result type, and using the given argument list which specifies both the
  2045. /// LLVM arguments and the types they were derived from.
  2046. ///
  2047. /// \param TargetDecl - If given, the decl of the function in a direct call;
  2048. /// used to set attributes on the call (noreturn, etc.).
  2049. RValue EmitCall(const CGFunctionInfo &FnInfo,
  2050. llvm::Value *Callee,
  2051. ReturnValueSlot ReturnValue,
  2052. const CallArgList &Args,
  2053. const Decl *TargetDecl = nullptr,
  2054. llvm::Instruction **callOrInvoke = nullptr);
  2055. RValue EmitCall(QualType FnType, llvm::Value *Callee, const CallExpr *E,
  2056. ReturnValueSlot ReturnValue,
  2057. const Decl *TargetDecl = nullptr,
  2058. llvm::Value *Chain = nullptr);
  2059. RValue EmitCallExpr(const CallExpr *E,
  2060. ReturnValueSlot ReturnValue = ReturnValueSlot());
  2061. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  2062. const Twine &name = "");
  2063. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  2064. ArrayRef<llvm::Value*> args,
  2065. const Twine &name = "");
  2066. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  2067. const Twine &name = "");
  2068. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  2069. ArrayRef<llvm::Value*> args,
  2070. const Twine &name = "");
  2071. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  2072. ArrayRef<llvm::Value *> Args,
  2073. const Twine &Name = "");
  2074. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  2075. const Twine &Name = "");
  2076. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2077. ArrayRef<llvm::Value*> args,
  2078. const Twine &name = "");
  2079. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2080. const Twine &name = "");
  2081. void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
  2082. ArrayRef<llvm::Value*> args);
  2083. llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  2084. NestedNameSpecifier *Qual,
  2085. llvm::Type *Ty);
  2086. llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  2087. CXXDtorType Type,
  2088. const CXXRecordDecl *RD);
  2089. RValue
  2090. EmitCXXMemberOrOperatorCall(const CXXMethodDecl *MD, llvm::Value *Callee,
  2091. ReturnValueSlot ReturnValue, llvm::Value *This,
  2092. llvm::Value *ImplicitParam,
  2093. QualType ImplicitParamTy, const CallExpr *E);
  2094. RValue EmitCXXStructorCall(const CXXMethodDecl *MD, llvm::Value *Callee,
  2095. ReturnValueSlot ReturnValue, llvm::Value *This,
  2096. llvm::Value *ImplicitParam,
  2097. QualType ImplicitParamTy, const CallExpr *E,
  2098. StructorType Type);
  2099. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  2100. ReturnValueSlot ReturnValue);
  2101. RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
  2102. const CXXMethodDecl *MD,
  2103. ReturnValueSlot ReturnValue,
  2104. bool HasQualifier,
  2105. NestedNameSpecifier *Qualifier,
  2106. bool IsArrow, const Expr *Base);
  2107. // Compute the object pointer.
  2108. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  2109. ReturnValueSlot ReturnValue);
  2110. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  2111. const CXXMethodDecl *MD,
  2112. ReturnValueSlot ReturnValue);
  2113. RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
  2114. ReturnValueSlot ReturnValue);
  2115. RValue EmitBuiltinExpr(const FunctionDecl *FD,
  2116. unsigned BuiltinID, const CallExpr *E,
  2117. ReturnValueSlot ReturnValue);
  2118. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  2119. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  2120. /// is unhandled by the current target.
  2121. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2122. llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
  2123. const llvm::CmpInst::Predicate Fp,
  2124. const llvm::CmpInst::Predicate Ip,
  2125. const llvm::Twine &Name = "");
  2126. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2127. llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
  2128. unsigned LLVMIntrinsic,
  2129. unsigned AltLLVMIntrinsic,
  2130. const char *NameHint,
  2131. unsigned Modifier,
  2132. const CallExpr *E,
  2133. SmallVectorImpl<llvm::Value *> &Ops,
  2134. llvm::Value *Align = nullptr);
  2135. llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
  2136. unsigned Modifier, llvm::Type *ArgTy,
  2137. const CallExpr *E);
  2138. llvm::Value *EmitNeonCall(llvm::Function *F,
  2139. SmallVectorImpl<llvm::Value*> &O,
  2140. const char *name,
  2141. unsigned shift = 0, bool rightshift = false);
  2142. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  2143. llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
  2144. bool negateForRightShift);
  2145. llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
  2146. llvm::Type *Ty, bool usgn, const char *name);
  2147. // Helper functions for EmitAArch64BuiltinExpr.
  2148. llvm::Value *vectorWrapScalar8(llvm::Value *Op);
  2149. llvm::Value *vectorWrapScalar16(llvm::Value *Op);
  2150. llvm::Value *emitVectorWrappedScalar8Intrinsic(
  2151. unsigned Int, SmallVectorImpl<llvm::Value *> &Ops, const char *Name);
  2152. llvm::Value *emitVectorWrappedScalar16Intrinsic(
  2153. unsigned Int, SmallVectorImpl<llvm::Value *> &Ops, const char *Name);
  2154. llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2155. llvm::Value *EmitNeon64Call(llvm::Function *F,
  2156. llvm::SmallVectorImpl<llvm::Value *> &O,
  2157. const char *name);
  2158. llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
  2159. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2160. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2161. llvm::Value *EmitR600BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2162. llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2163. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  2164. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  2165. llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
  2166. llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
  2167. llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
  2168. llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
  2169. const ObjCMethodDecl *MethodWithObjects);
  2170. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  2171. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  2172. ReturnValueSlot Return = ReturnValueSlot());
  2173. /// Retrieves the default cleanup kind for an ARC cleanup.
  2174. /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
  2175. CleanupKind getARCCleanupKind() {
  2176. return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
  2177. ? NormalAndEHCleanup : NormalCleanup;
  2178. }
  2179. // ARC primitives.
  2180. void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr);
  2181. void EmitARCDestroyWeak(llvm::Value *addr);
  2182. llvm::Value *EmitARCLoadWeak(llvm::Value *addr);
  2183. llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr);
  2184. llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr,
  2185. bool ignored);
  2186. void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src);
  2187. void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src);
  2188. llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
  2189. llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
  2190. llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
  2191. bool resultIgnored);
  2192. llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value,
  2193. bool resultIgnored);
  2194. llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
  2195. llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
  2196. llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
  2197. void EmitARCDestroyStrong(llvm::Value *addr, ARCPreciseLifetime_t precise);
  2198. void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
  2199. llvm::Value *EmitARCAutorelease(llvm::Value *value);
  2200. llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
  2201. llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
  2202. llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
  2203. std::pair<LValue,llvm::Value*>
  2204. EmitARCStoreAutoreleasing(const BinaryOperator *e);
  2205. std::pair<LValue,llvm::Value*>
  2206. EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
  2207. llvm::Value *EmitObjCThrowOperand(const Expr *expr);
  2208. llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr);
  2209. llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
  2210. llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
  2211. llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
  2212. llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
  2213. llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
  2214. void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
  2215. static Destroyer destroyARCStrongImprecise;
  2216. static Destroyer destroyARCStrongPrecise;
  2217. static Destroyer destroyARCWeak;
  2218. void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
  2219. llvm::Value *EmitObjCAutoreleasePoolPush();
  2220. llvm::Value *EmitObjCMRRAutoreleasePoolPush();
  2221. void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
  2222. void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
  2223. /// \brief Emits a reference binding to the passed in expression.
  2224. RValue EmitReferenceBindingToExpr(const Expr *E);
  2225. //===--------------------------------------------------------------------===//
  2226. // Expression Emission
  2227. //===--------------------------------------------------------------------===//
  2228. // Expressions are broken into three classes: scalar, complex, aggregate.
  2229. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  2230. /// scalar type, returning the result.
  2231. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  2232. /// EmitScalarConversion - Emit a conversion from the specified type to the
  2233. /// specified destination type, both of which are LLVM scalar types.
  2234. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  2235. QualType DstTy);
  2236. /// EmitComplexToScalarConversion - Emit a conversion from the specified
  2237. /// complex type to the specified destination type, where the destination type
  2238. /// is an LLVM scalar type.
  2239. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  2240. QualType DstTy);
  2241. /// EmitAggExpr - Emit the computation of the specified expression
  2242. /// of aggregate type. The result is computed into the given slot,
  2243. /// which may be null to indicate that the value is not needed.
  2244. void EmitAggExpr(const Expr *E, AggValueSlot AS);
  2245. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  2246. /// aggregate type into a temporary LValue.
  2247. LValue EmitAggExprToLValue(const Expr *E);
  2248. /// EmitGCMemmoveCollectable - Emit special API for structs with object
  2249. /// pointers.
  2250. void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  2251. QualType Ty);
  2252. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  2253. /// make sure it survives garbage collection until this point.
  2254. void EmitExtendGCLifetime(llvm::Value *object);
  2255. /// EmitComplexExpr - Emit the computation of the specified expression of
  2256. /// complex type, returning the result.
  2257. ComplexPairTy EmitComplexExpr(const Expr *E,
  2258. bool IgnoreReal = false,
  2259. bool IgnoreImag = false);
  2260. /// EmitComplexExprIntoLValue - Emit the given expression of complex
  2261. /// type and place its result into the specified l-value.
  2262. void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
  2263. /// EmitStoreOfComplex - Store a complex number into the specified l-value.
  2264. void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
  2265. /// EmitLoadOfComplex - Load a complex number from the specified l-value.
  2266. ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
  2267. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  2268. /// global variable that has already been created for it. If the initializer
  2269. /// has a different type than GV does, this may free GV and return a different
  2270. /// one. Otherwise it just returns GV.
  2271. llvm::GlobalVariable *
  2272. AddInitializerToStaticVarDecl(const VarDecl &D,
  2273. llvm::GlobalVariable *GV);
  2274. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  2275. /// variable with global storage.
  2276. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
  2277. bool PerformInit);
  2278. llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
  2279. llvm::Constant *Addr);
  2280. /// Call atexit() with a function that passes the given argument to
  2281. /// the given function.
  2282. void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
  2283. llvm::Constant *addr);
  2284. /// Emit code in this function to perform a guarded variable
  2285. /// initialization. Guarded initializations are used when it's not
  2286. /// possible to prove that an initialization will be done exactly
  2287. /// once, e.g. with a static local variable or a static data member
  2288. /// of a class template.
  2289. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
  2290. bool PerformInit);
  2291. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  2292. /// variables.
  2293. void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  2294. ArrayRef<llvm::Function *> CXXThreadLocals,
  2295. llvm::GlobalVariable *Guard = nullptr);
  2296. /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
  2297. /// variables.
  2298. void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
  2299. const std::vector<std::pair<llvm::WeakVH,
  2300. llvm::Constant*> > &DtorsAndObjects);
  2301. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  2302. const VarDecl *D,
  2303. llvm::GlobalVariable *Addr,
  2304. bool PerformInit);
  2305. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  2306. void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
  2307. const Expr *Exp);
  2308. void enterFullExpression(const ExprWithCleanups *E) {
  2309. if (E->getNumObjects() == 0) return;
  2310. enterNonTrivialFullExpression(E);
  2311. }
  2312. void enterNonTrivialFullExpression(const ExprWithCleanups *E);
  2313. void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
  2314. void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
  2315. RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = nullptr);
  2316. //===--------------------------------------------------------------------===//
  2317. // Annotations Emission
  2318. //===--------------------------------------------------------------------===//
  2319. /// Emit an annotation call (intrinsic or builtin).
  2320. llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
  2321. llvm::Value *AnnotatedVal,
  2322. StringRef AnnotationStr,
  2323. SourceLocation Location);
  2324. /// Emit local annotations for the local variable V, declared by D.
  2325. void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
  2326. /// Emit field annotations for the given field & value. Returns the
  2327. /// annotation result.
  2328. llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V);
  2329. //===--------------------------------------------------------------------===//
  2330. // Internal Helpers
  2331. //===--------------------------------------------------------------------===//
  2332. /// ContainsLabel - Return true if the statement contains a label in it. If
  2333. /// this statement is not executed normally, it not containing a label means
  2334. /// that we can just remove the code.
  2335. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  2336. /// containsBreak - Return true if the statement contains a break out of it.
  2337. /// If the statement (recursively) contains a switch or loop with a break
  2338. /// inside of it, this is fine.
  2339. static bool containsBreak(const Stmt *S);
  2340. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2341. /// to a constant, or if it does but contains a label, return false. If it
  2342. /// constant folds return true and set the boolean result in Result.
  2343. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
  2344. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2345. /// to a constant, or if it does but contains a label, return false. If it
  2346. /// constant folds return true and set the folded value.
  2347. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result);
  2348. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  2349. /// if statement) to the specified blocks. Based on the condition, this might
  2350. /// try to simplify the codegen of the conditional based on the branch.
  2351. /// TrueCount should be the number of times we expect the condition to
  2352. /// evaluate to true based on PGO data.
  2353. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  2354. llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
  2355. /// \brief Emit a description of a type in a format suitable for passing to
  2356. /// a runtime sanitizer handler.
  2357. llvm::Constant *EmitCheckTypeDescriptor(QualType T);
  2358. /// \brief Convert a value into a format suitable for passing to a runtime
  2359. /// sanitizer handler.
  2360. llvm::Value *EmitCheckValue(llvm::Value *V);
  2361. /// \brief Emit a description of a source location in a format suitable for
  2362. /// passing to a runtime sanitizer handler.
  2363. llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
  2364. /// \brief Create a basic block that will call a handler function in a
  2365. /// sanitizer runtime with the provided arguments, and create a conditional
  2366. /// branch to it.
  2367. void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerKind>> Checked,
  2368. StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
  2369. ArrayRef<llvm::Value *> DynamicArgs);
  2370. /// \brief Create a basic block that will call the trap intrinsic, and emit a
  2371. /// conditional branch to it, for the -ftrapv checks.
  2372. void EmitTrapCheck(llvm::Value *Checked);
  2373. /// EmitCallArg - Emit a single call argument.
  2374. void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
  2375. /// EmitDelegateCallArg - We are performing a delegate call; that
  2376. /// is, the current function is delegating to another one. Produce
  2377. /// a r-value suitable for passing the given parameter.
  2378. void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
  2379. SourceLocation loc);
  2380. /// SetFPAccuracy - Set the minimum required accuracy of the given floating
  2381. /// point operation, expressed as the maximum relative error in ulp.
  2382. void SetFPAccuracy(llvm::Value *Val, float Accuracy);
  2383. private:
  2384. llvm::MDNode *getRangeForLoadFromType(QualType Ty);
  2385. void EmitReturnOfRValue(RValue RV, QualType Ty);
  2386. void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
  2387. llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
  2388. DeferredReplacements;
  2389. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  2390. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  2391. ///
  2392. /// \param AI - The first function argument of the expansion.
  2393. void ExpandTypeFromArgs(QualType Ty, LValue Dst,
  2394. SmallVectorImpl<llvm::Argument *>::iterator &AI);
  2395. /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
  2396. /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
  2397. /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
  2398. void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
  2399. SmallVectorImpl<llvm::Value *> &IRCallArgs,
  2400. unsigned &IRCallArgPos);
  2401. llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
  2402. const Expr *InputExpr, std::string &ConstraintStr);
  2403. llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
  2404. LValue InputValue, QualType InputType,
  2405. std::string &ConstraintStr,
  2406. SourceLocation Loc);
  2407. public:
  2408. /// EmitCallArgs - Emit call arguments for a function.
  2409. template <typename T>
  2410. void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
  2411. CallExpr::const_arg_iterator ArgBeg,
  2412. CallExpr::const_arg_iterator ArgEnd,
  2413. const FunctionDecl *CalleeDecl = nullptr,
  2414. unsigned ParamsToSkip = 0) {
  2415. SmallVector<QualType, 16> ArgTypes;
  2416. CallExpr::const_arg_iterator Arg = ArgBeg;
  2417. assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
  2418. "Can't skip parameters if type info is not provided");
  2419. if (CallArgTypeInfo) {
  2420. // First, use the argument types that the type info knows about
  2421. for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
  2422. E = CallArgTypeInfo->param_type_end();
  2423. I != E; ++I, ++Arg) {
  2424. assert(Arg != ArgEnd && "Running over edge of argument list!");
  2425. assert(
  2426. ((*I)->isVariablyModifiedType() ||
  2427. getContext()
  2428. .getCanonicalType((*I).getNonReferenceType())
  2429. .getTypePtr() ==
  2430. getContext().getCanonicalType(Arg->getType()).getTypePtr()) &&
  2431. "type mismatch in call argument!");
  2432. ArgTypes.push_back(*I);
  2433. }
  2434. }
  2435. // Either we've emitted all the call args, or we have a call to variadic
  2436. // function.
  2437. assert(
  2438. (Arg == ArgEnd || !CallArgTypeInfo || CallArgTypeInfo->isVariadic()) &&
  2439. "Extra arguments in non-variadic function!");
  2440. // If we still have any arguments, emit them using the type of the argument.
  2441. for (; Arg != ArgEnd; ++Arg)
  2442. ArgTypes.push_back(getVarArgType(*Arg));
  2443. EmitCallArgs(Args, ArgTypes, ArgBeg, ArgEnd, CalleeDecl, ParamsToSkip);
  2444. }
  2445. void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
  2446. CallExpr::const_arg_iterator ArgBeg,
  2447. CallExpr::const_arg_iterator ArgEnd,
  2448. const FunctionDecl *CalleeDecl = nullptr,
  2449. unsigned ParamsToSkip = 0);
  2450. private:
  2451. QualType getVarArgType(const Expr *Arg);
  2452. const TargetCodeGenInfo &getTargetHooks() const {
  2453. return CGM.getTargetCodeGenInfo();
  2454. }
  2455. void EmitDeclMetadata();
  2456. CodeGenModule::ByrefHelpers *
  2457. buildByrefHelpers(llvm::StructType &byrefType,
  2458. const AutoVarEmission &emission);
  2459. void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
  2460. /// GetPointeeAlignment - Given an expression with a pointer type, emit the
  2461. /// value and compute our best estimate of the alignment of the pointee.
  2462. std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr);
  2463. llvm::Value *GetValueForARMHint(unsigned BuiltinID);
  2464. };
  2465. /// Helper class with most of the code for saving a value for a
  2466. /// conditional expression cleanup.
  2467. struct DominatingLLVMValue {
  2468. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  2469. /// Answer whether the given value needs extra work to be saved.
  2470. static bool needsSaving(llvm::Value *value) {
  2471. // If it's not an instruction, we don't need to save.
  2472. if (!isa<llvm::Instruction>(value)) return false;
  2473. // If it's an instruction in the entry block, we don't need to save.
  2474. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  2475. return (block != &block->getParent()->getEntryBlock());
  2476. }
  2477. /// Try to save the given value.
  2478. static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
  2479. if (!needsSaving(value)) return saved_type(value, false);
  2480. // Otherwise we need an alloca.
  2481. llvm::Value *alloca =
  2482. CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save");
  2483. CGF.Builder.CreateStore(value, alloca);
  2484. return saved_type(alloca, true);
  2485. }
  2486. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
  2487. if (!value.getInt()) return value.getPointer();
  2488. return CGF.Builder.CreateLoad(value.getPointer());
  2489. }
  2490. };
  2491. /// A partial specialization of DominatingValue for llvm::Values that
  2492. /// might be llvm::Instructions.
  2493. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  2494. typedef T *type;
  2495. static type restore(CodeGenFunction &CGF, saved_type value) {
  2496. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  2497. }
  2498. };
  2499. /// A specialization of DominatingValue for RValue.
  2500. template <> struct DominatingValue<RValue> {
  2501. typedef RValue type;
  2502. class saved_type {
  2503. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  2504. AggregateAddress, ComplexAddress };
  2505. llvm::Value *Value;
  2506. Kind K;
  2507. saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {}
  2508. public:
  2509. static bool needsSaving(RValue value);
  2510. static saved_type save(CodeGenFunction &CGF, RValue value);
  2511. RValue restore(CodeGenFunction &CGF);
  2512. // implementations in CGExprCXX.cpp
  2513. };
  2514. static bool needsSaving(type value) {
  2515. return saved_type::needsSaving(value);
  2516. }
  2517. static saved_type save(CodeGenFunction &CGF, type value) {
  2518. return saved_type::save(CGF, value);
  2519. }
  2520. static type restore(CodeGenFunction &CGF, saved_type value) {
  2521. return value.restore(CGF);
  2522. }
  2523. };
  2524. } // end namespace CodeGen
  2525. } // end namespace clang
  2526. #endif