CodeGenFunction.h 110 KB

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