CodeGenFunction.h 114 KB

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