CodeGenFunction.h 119 KB

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