CodeGenFunction.h 108 KB

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