CodeGenFunction.h 127 KB

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