CGBlocks.cpp 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027
  1. //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code to emit blocks.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGBlocks.h"
  13. #include "CGCXXABI.h"
  14. #include "CGDebugInfo.h"
  15. #include "CGObjCRuntime.h"
  16. #include "CGOpenCLRuntime.h"
  17. #include "CodeGenFunction.h"
  18. #include "CodeGenModule.h"
  19. #include "ConstantEmitter.h"
  20. #include "TargetInfo.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/CodeGen/ConstantInitBuilder.h"
  23. #include "llvm/ADT/SmallSet.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/Support/ScopedPrinter.h"
  27. #include <algorithm>
  28. #include <cstdio>
  29. using namespace clang;
  30. using namespace CodeGen;
  31. CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
  32. : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
  33. HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
  34. CapturesNonExternalType(false), LocalAddress(Address::invalid()),
  35. StructureType(nullptr), Block(block), DominatingIP(nullptr) {
  36. // Skip asm prefix, if any. 'name' is usually taken directly from
  37. // the mangled name of the enclosing function.
  38. if (!name.empty() && name[0] == '\01')
  39. name = name.substr(1);
  40. }
  41. // Anchor the vtable to this translation unit.
  42. BlockByrefHelpers::~BlockByrefHelpers() {}
  43. /// Build the given block as a global block.
  44. static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
  45. const CGBlockInfo &blockInfo,
  46. llvm::Constant *blockFn);
  47. /// Build the helper function to copy a block.
  48. static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
  49. const CGBlockInfo &blockInfo) {
  50. return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
  51. }
  52. /// Build the helper function to dispose of a block.
  53. static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
  54. const CGBlockInfo &blockInfo) {
  55. return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
  56. }
  57. namespace {
  58. /// Represents a type of copy/destroy operation that should be performed for an
  59. /// entity that's captured by a block.
  60. enum class BlockCaptureEntityKind {
  61. CXXRecord, // Copy or destroy
  62. ARCWeak,
  63. ARCStrong,
  64. NonTrivialCStruct,
  65. BlockObject, // Assign or release
  66. None
  67. };
  68. /// Represents a captured entity that requires extra operations in order for
  69. /// this entity to be copied or destroyed correctly.
  70. struct BlockCaptureManagedEntity {
  71. BlockCaptureEntityKind CopyKind, DisposeKind;
  72. BlockFieldFlags CopyFlags, DisposeFlags;
  73. const BlockDecl::Capture *CI;
  74. const CGBlockInfo::Capture *Capture;
  75. BlockCaptureManagedEntity(BlockCaptureEntityKind CopyType,
  76. BlockCaptureEntityKind DisposeType,
  77. BlockFieldFlags CopyFlags,
  78. BlockFieldFlags DisposeFlags,
  79. const BlockDecl::Capture &CI,
  80. const CGBlockInfo::Capture &Capture)
  81. : CopyKind(CopyType), DisposeKind(DisposeType), CopyFlags(CopyFlags),
  82. DisposeFlags(DisposeFlags), CI(&CI), Capture(&Capture) {}
  83. bool operator<(const BlockCaptureManagedEntity &Other) const {
  84. return Capture->getOffset() < Other.Capture->getOffset();
  85. }
  86. };
  87. enum class CaptureStrKind {
  88. // String for the copy helper.
  89. CopyHelper,
  90. // String for the dispose helper.
  91. DisposeHelper,
  92. // Merge the strings for the copy helper and dispose helper.
  93. Merged
  94. };
  95. } // end anonymous namespace
  96. static void findBlockCapturedManagedEntities(
  97. const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
  98. SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures);
  99. static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
  100. CaptureStrKind StrKind,
  101. CharUnits BlockAlignment,
  102. CodeGenModule &CGM);
  103. static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
  104. CodeGenModule &CGM) {
  105. std::string Name = "__block_descriptor_";
  106. Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
  107. if (BlockInfo.needsCopyDisposeHelpers()) {
  108. if (CGM.getLangOpts().Exceptions)
  109. Name += "e";
  110. if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
  111. Name += "a";
  112. Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
  113. SmallVector<BlockCaptureManagedEntity, 4> ManagedCaptures;
  114. findBlockCapturedManagedEntities(BlockInfo, CGM.getContext().getLangOpts(),
  115. ManagedCaptures);
  116. for (const BlockCaptureManagedEntity &E : ManagedCaptures) {
  117. Name += llvm::to_string(E.Capture->getOffset().getQuantity());
  118. if (E.CopyKind == E.DisposeKind) {
  119. // If CopyKind and DisposeKind are the same, merge the capture
  120. // information.
  121. assert(E.CopyKind != BlockCaptureEntityKind::None &&
  122. "shouldn't see BlockCaptureManagedEntity that is None");
  123. Name += getBlockCaptureStr(E, CaptureStrKind::Merged,
  124. BlockInfo.BlockAlign, CGM);
  125. } else {
  126. // If CopyKind and DisposeKind are not the same, which can happen when
  127. // either Kind is None or the captured object is a __strong block,
  128. // concatenate the copy and dispose strings.
  129. Name += getBlockCaptureStr(E, CaptureStrKind::CopyHelper,
  130. BlockInfo.BlockAlign, CGM);
  131. Name += getBlockCaptureStr(E, CaptureStrKind::DisposeHelper,
  132. BlockInfo.BlockAlign, CGM);
  133. }
  134. }
  135. Name += "_";
  136. }
  137. std::string TypeAtEncoding =
  138. CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
  139. /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as
  140. /// a separator between symbol name and symbol version.
  141. std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1');
  142. Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
  143. Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
  144. return Name;
  145. }
  146. /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
  147. /// buildBlockDescriptor is accessed from 5th field of the Block_literal
  148. /// meta-data and contains stationary information about the block literal.
  149. /// Its definition will have 4 (or optionally 6) words.
  150. /// \code
  151. /// struct Block_descriptor {
  152. /// unsigned long reserved;
  153. /// unsigned long size; // size of Block_literal metadata in bytes.
  154. /// void *copy_func_helper_decl; // optional copy helper.
  155. /// void *destroy_func_decl; // optional destructor helper.
  156. /// void *block_method_encoding_address; // @encode for block literal signature.
  157. /// void *block_layout_info; // encoding of captured block variables.
  158. /// };
  159. /// \endcode
  160. static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
  161. const CGBlockInfo &blockInfo) {
  162. ASTContext &C = CGM.getContext();
  163. llvm::IntegerType *ulong =
  164. cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
  165. llvm::PointerType *i8p = nullptr;
  166. if (CGM.getLangOpts().OpenCL)
  167. i8p =
  168. llvm::Type::getInt8PtrTy(
  169. CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
  170. else
  171. i8p = CGM.VoidPtrTy;
  172. std::string descName;
  173. // If an equivalent block descriptor global variable exists, return it.
  174. if (C.getLangOpts().ObjC &&
  175. CGM.getLangOpts().getGC() == LangOptions::NonGC) {
  176. descName = getBlockDescriptorName(blockInfo, CGM);
  177. if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
  178. return llvm::ConstantExpr::getBitCast(desc,
  179. CGM.getBlockDescriptorType());
  180. }
  181. // If there isn't an equivalent block descriptor global variable, create a new
  182. // one.
  183. ConstantInitBuilder builder(CGM);
  184. auto elements = builder.beginStruct();
  185. // reserved
  186. elements.addInt(ulong, 0);
  187. // Size
  188. // FIXME: What is the right way to say this doesn't fit? We should give
  189. // a user diagnostic in that case. Better fix would be to change the
  190. // API to size_t.
  191. elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
  192. // Optional copy/dispose helpers.
  193. bool hasInternalHelper = false;
  194. if (blockInfo.needsCopyDisposeHelpers()) {
  195. // copy_func_helper_decl
  196. llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
  197. elements.add(copyHelper);
  198. // destroy_func_decl
  199. llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
  200. elements.add(disposeHelper);
  201. if (cast<llvm::Function>(copyHelper->getOperand(0))->hasInternalLinkage() ||
  202. cast<llvm::Function>(disposeHelper->getOperand(0))
  203. ->hasInternalLinkage())
  204. hasInternalHelper = true;
  205. }
  206. // Signature. Mandatory ObjC-style method descriptor @encode sequence.
  207. std::string typeAtEncoding =
  208. CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
  209. elements.add(llvm::ConstantExpr::getBitCast(
  210. CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
  211. // GC layout.
  212. if (C.getLangOpts().ObjC) {
  213. if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
  214. elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
  215. else
  216. elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
  217. }
  218. else
  219. elements.addNullPointer(i8p);
  220. unsigned AddrSpace = 0;
  221. if (C.getLangOpts().OpenCL)
  222. AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
  223. llvm::GlobalValue::LinkageTypes linkage;
  224. if (descName.empty()) {
  225. linkage = llvm::GlobalValue::InternalLinkage;
  226. descName = "__block_descriptor_tmp";
  227. } else if (hasInternalHelper) {
  228. // If either the copy helper or the dispose helper has internal linkage,
  229. // the block descriptor must have internal linkage too.
  230. linkage = llvm::GlobalValue::InternalLinkage;
  231. } else {
  232. linkage = llvm::GlobalValue::LinkOnceODRLinkage;
  233. }
  234. llvm::GlobalVariable *global =
  235. elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
  236. /*constant*/ true, linkage, AddrSpace);
  237. if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
  238. if (CGM.supportsCOMDAT())
  239. global->setComdat(CGM.getModule().getOrInsertComdat(descName));
  240. global->setVisibility(llvm::GlobalValue::HiddenVisibility);
  241. global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  242. }
  243. return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
  244. }
  245. /*
  246. Purely notional variadic template describing the layout of a block.
  247. template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
  248. struct Block_literal {
  249. /// Initialized to one of:
  250. /// extern void *_NSConcreteStackBlock[];
  251. /// extern void *_NSConcreteGlobalBlock[];
  252. ///
  253. /// In theory, we could start one off malloc'ed by setting
  254. /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
  255. /// this isa:
  256. /// extern void *_NSConcreteMallocBlock[];
  257. struct objc_class *isa;
  258. /// These are the flags (with corresponding bit number) that the
  259. /// compiler is actually supposed to know about.
  260. /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
  261. /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
  262. /// descriptor provides copy and dispose helper functions
  263. /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
  264. /// object with a nontrivial destructor or copy constructor
  265. /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
  266. /// as global memory
  267. /// 29. BLOCK_USE_STRET - indicates that the block function
  268. /// uses stret, which objc_msgSend needs to know about
  269. /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
  270. /// @encoded signature string
  271. /// And we're not supposed to manipulate these:
  272. /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
  273. /// to malloc'ed memory
  274. /// 27. BLOCK_IS_GC - indicates that the block has been moved to
  275. /// to GC-allocated memory
  276. /// Additionally, the bottom 16 bits are a reference count which
  277. /// should be zero on the stack.
  278. int flags;
  279. /// Reserved; should be zero-initialized.
  280. int reserved;
  281. /// Function pointer generated from block literal.
  282. _ResultType (*invoke)(Block_literal *, _ParamTypes...);
  283. /// Block description metadata generated from block literal.
  284. struct Block_descriptor *block_descriptor;
  285. /// Captured values follow.
  286. _CapturesTypes captures...;
  287. };
  288. */
  289. namespace {
  290. /// A chunk of data that we actually have to capture in the block.
  291. struct BlockLayoutChunk {
  292. CharUnits Alignment;
  293. CharUnits Size;
  294. Qualifiers::ObjCLifetime Lifetime;
  295. const BlockDecl::Capture *Capture; // null for 'this'
  296. llvm::Type *Type;
  297. QualType FieldType;
  298. BlockLayoutChunk(CharUnits align, CharUnits size,
  299. Qualifiers::ObjCLifetime lifetime,
  300. const BlockDecl::Capture *capture,
  301. llvm::Type *type, QualType fieldType)
  302. : Alignment(align), Size(size), Lifetime(lifetime),
  303. Capture(capture), Type(type), FieldType(fieldType) {}
  304. /// Tell the block info that this chunk has the given field index.
  305. void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
  306. if (!Capture) {
  307. info.CXXThisIndex = index;
  308. info.CXXThisOffset = offset;
  309. } else {
  310. auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
  311. info.Captures.insert({Capture->getVariable(), C});
  312. }
  313. }
  314. };
  315. /// Order by 1) all __strong together 2) next, all byfref together 3) next,
  316. /// all __weak together. Preserve descending alignment in all situations.
  317. bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
  318. if (left.Alignment != right.Alignment)
  319. return left.Alignment > right.Alignment;
  320. auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
  321. if (chunk.Capture && chunk.Capture->isByRef())
  322. return 1;
  323. if (chunk.Lifetime == Qualifiers::OCL_Strong)
  324. return 0;
  325. if (chunk.Lifetime == Qualifiers::OCL_Weak)
  326. return 2;
  327. return 3;
  328. };
  329. return getPrefOrder(left) < getPrefOrder(right);
  330. }
  331. } // end anonymous namespace
  332. /// Determines if the given type is safe for constant capture in C++.
  333. static bool isSafeForCXXConstantCapture(QualType type) {
  334. const RecordType *recordType =
  335. type->getBaseElementTypeUnsafe()->getAs<RecordType>();
  336. // Only records can be unsafe.
  337. if (!recordType) return true;
  338. const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
  339. // Maintain semantics for classes with non-trivial dtors or copy ctors.
  340. if (!record->hasTrivialDestructor()) return false;
  341. if (record->hasNonTrivialCopyConstructor()) return false;
  342. // Otherwise, we just have to make sure there aren't any mutable
  343. // fields that might have changed since initialization.
  344. return !record->hasMutableFields();
  345. }
  346. /// It is illegal to modify a const object after initialization.
  347. /// Therefore, if a const object has a constant initializer, we don't
  348. /// actually need to keep storage for it in the block; we'll just
  349. /// rematerialize it at the start of the block function. This is
  350. /// acceptable because we make no promises about address stability of
  351. /// captured variables.
  352. static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
  353. CodeGenFunction *CGF,
  354. const VarDecl *var) {
  355. // Return if this is a function parameter. We shouldn't try to
  356. // rematerialize default arguments of function parameters.
  357. if (isa<ParmVarDecl>(var))
  358. return nullptr;
  359. QualType type = var->getType();
  360. // We can only do this if the variable is const.
  361. if (!type.isConstQualified()) return nullptr;
  362. // Furthermore, in C++ we have to worry about mutable fields:
  363. // C++ [dcl.type.cv]p4:
  364. // Except that any class member declared mutable can be
  365. // modified, any attempt to modify a const object during its
  366. // lifetime results in undefined behavior.
  367. if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
  368. return nullptr;
  369. // If the variable doesn't have any initializer (shouldn't this be
  370. // invalid?), it's not clear what we should do. Maybe capture as
  371. // zero?
  372. const Expr *init = var->getInit();
  373. if (!init) return nullptr;
  374. return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
  375. }
  376. /// Get the low bit of a nonzero character count. This is the
  377. /// alignment of the nth byte if the 0th byte is universally aligned.
  378. static CharUnits getLowBit(CharUnits v) {
  379. return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
  380. }
  381. static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
  382. SmallVectorImpl<llvm::Type*> &elementTypes) {
  383. assert(elementTypes.empty());
  384. if (CGM.getLangOpts().OpenCL) {
  385. // The header is basically 'struct { int; int; generic void *;
  386. // custom_fields; }'. Assert that struct is packed.
  387. auto GenericAS =
  388. CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
  389. auto GenPtrAlign =
  390. CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 8);
  391. auto GenPtrSize =
  392. CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 8);
  393. assert(CGM.getIntSize() <= GenPtrSize);
  394. assert(CGM.getIntAlign() <= GenPtrAlign);
  395. assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
  396. elementTypes.push_back(CGM.IntTy); /* total size */
  397. elementTypes.push_back(CGM.IntTy); /* align */
  398. elementTypes.push_back(
  399. CGM.getOpenCLRuntime()
  400. .getGenericVoidPointerType()); /* invoke function */
  401. unsigned Offset =
  402. 2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
  403. unsigned BlockAlign = GenPtrAlign.getQuantity();
  404. if (auto *Helper =
  405. CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
  406. for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
  407. // TargetOpenCLBlockHelp needs to make sure the struct is packed.
  408. // If necessary, add padding fields to the custom fields.
  409. unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
  410. if (BlockAlign < Align)
  411. BlockAlign = Align;
  412. assert(Offset % Align == 0);
  413. Offset += CGM.getDataLayout().getTypeAllocSize(I);
  414. elementTypes.push_back(I);
  415. }
  416. }
  417. info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
  418. info.BlockSize = CharUnits::fromQuantity(Offset);
  419. } else {
  420. // The header is basically 'struct { void *; int; int; void *; void *; }'.
  421. // Assert that the struct is packed.
  422. assert(CGM.getIntSize() <= CGM.getPointerSize());
  423. assert(CGM.getIntAlign() <= CGM.getPointerAlign());
  424. assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
  425. info.BlockAlign = CGM.getPointerAlign();
  426. info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
  427. elementTypes.push_back(CGM.VoidPtrTy);
  428. elementTypes.push_back(CGM.IntTy);
  429. elementTypes.push_back(CGM.IntTy);
  430. elementTypes.push_back(CGM.VoidPtrTy);
  431. elementTypes.push_back(CGM.getBlockDescriptorType());
  432. }
  433. }
  434. static QualType getCaptureFieldType(const CodeGenFunction &CGF,
  435. const BlockDecl::Capture &CI) {
  436. const VarDecl *VD = CI.getVariable();
  437. // If the variable is captured by an enclosing block or lambda expression,
  438. // use the type of the capture field.
  439. if (CGF.BlockInfo && CI.isNested())
  440. return CGF.BlockInfo->getCapture(VD).fieldType();
  441. if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
  442. return FD->getType();
  443. // If the captured variable is a non-escaping __block variable, the field
  444. // type is the reference type. If the variable is a __block variable that
  445. // already has a reference type, the field type is the variable's type.
  446. return VD->isNonEscapingByref() ?
  447. CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType();
  448. }
  449. /// Compute the layout of the given block. Attempts to lay the block
  450. /// out with minimal space requirements.
  451. static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
  452. CGBlockInfo &info) {
  453. ASTContext &C = CGM.getContext();
  454. const BlockDecl *block = info.getBlockDecl();
  455. SmallVector<llvm::Type*, 8> elementTypes;
  456. initializeForBlockHeader(CGM, info, elementTypes);
  457. bool hasNonConstantCustomFields = false;
  458. if (auto *OpenCLHelper =
  459. CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
  460. hasNonConstantCustomFields =
  461. !OpenCLHelper->areAllCustomFieldValuesConstant(info);
  462. if (!block->hasCaptures() && !hasNonConstantCustomFields) {
  463. info.StructureType =
  464. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  465. info.CanBeGlobal = true;
  466. return;
  467. }
  468. else if (C.getLangOpts().ObjC &&
  469. CGM.getLangOpts().getGC() == LangOptions::NonGC)
  470. info.HasCapturedVariableLayout = true;
  471. // Collect the layout chunks.
  472. SmallVector<BlockLayoutChunk, 16> layout;
  473. layout.reserve(block->capturesCXXThis() +
  474. (block->capture_end() - block->capture_begin()));
  475. CharUnits maxFieldAlign;
  476. // First, 'this'.
  477. if (block->capturesCXXThis()) {
  478. assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
  479. "Can't capture 'this' outside a method");
  480. QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType();
  481. // Theoretically, this could be in a different address space, so
  482. // don't assume standard pointer size/align.
  483. llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
  484. std::pair<CharUnits,CharUnits> tinfo
  485. = CGM.getContext().getTypeInfoInChars(thisType);
  486. maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
  487. layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
  488. Qualifiers::OCL_None,
  489. nullptr, llvmType, thisType));
  490. }
  491. // Next, all the block captures.
  492. for (const auto &CI : block->captures()) {
  493. const VarDecl *variable = CI.getVariable();
  494. if (CI.isEscapingByref()) {
  495. // We have to copy/dispose of the __block reference.
  496. info.NeedsCopyDispose = true;
  497. // Just use void* instead of a pointer to the byref type.
  498. CharUnits align = CGM.getPointerAlign();
  499. maxFieldAlign = std::max(maxFieldAlign, align);
  500. // Since a __block variable cannot be captured by lambdas, its type and
  501. // the capture field type should always match.
  502. assert(getCaptureFieldType(*CGF, CI) == variable->getType() &&
  503. "capture type differs from the variable type");
  504. layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
  505. Qualifiers::OCL_None, &CI,
  506. CGM.VoidPtrTy, variable->getType()));
  507. continue;
  508. }
  509. // Otherwise, build a layout chunk with the size and alignment of
  510. // the declaration.
  511. if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
  512. info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
  513. continue;
  514. }
  515. QualType VT = getCaptureFieldType(*CGF, CI);
  516. // If we have a lifetime qualifier, honor it for capture purposes.
  517. // That includes *not* copying it if it's __unsafe_unretained.
  518. Qualifiers::ObjCLifetime lifetime = VT.getObjCLifetime();
  519. if (lifetime) {
  520. switch (lifetime) {
  521. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  522. case Qualifiers::OCL_ExplicitNone:
  523. case Qualifiers::OCL_Autoreleasing:
  524. break;
  525. case Qualifiers::OCL_Strong:
  526. case Qualifiers::OCL_Weak:
  527. info.NeedsCopyDispose = true;
  528. }
  529. // Block pointers require copy/dispose. So do Objective-C pointers.
  530. } else if (VT->isObjCRetainableType()) {
  531. // But honor the inert __unsafe_unretained qualifier, which doesn't
  532. // actually make it into the type system.
  533. if (VT->isObjCInertUnsafeUnretainedType()) {
  534. lifetime = Qualifiers::OCL_ExplicitNone;
  535. } else {
  536. info.NeedsCopyDispose = true;
  537. // used for mrr below.
  538. lifetime = Qualifiers::OCL_Strong;
  539. }
  540. // So do types that require non-trivial copy construction.
  541. } else if (CI.hasCopyExpr()) {
  542. info.NeedsCopyDispose = true;
  543. info.HasCXXObject = true;
  544. if (!VT->getAsCXXRecordDecl()->isExternallyVisible())
  545. info.CapturesNonExternalType = true;
  546. // So do C structs that require non-trivial copy construction or
  547. // destruction.
  548. } else if (VT.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct ||
  549. VT.isDestructedType() == QualType::DK_nontrivial_c_struct) {
  550. info.NeedsCopyDispose = true;
  551. // And so do types with destructors.
  552. } else if (CGM.getLangOpts().CPlusPlus) {
  553. if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl()) {
  554. if (!record->hasTrivialDestructor()) {
  555. info.HasCXXObject = true;
  556. info.NeedsCopyDispose = true;
  557. if (!record->isExternallyVisible())
  558. info.CapturesNonExternalType = true;
  559. }
  560. }
  561. }
  562. CharUnits size = C.getTypeSizeInChars(VT);
  563. CharUnits align = C.getDeclAlign(variable);
  564. maxFieldAlign = std::max(maxFieldAlign, align);
  565. llvm::Type *llvmType =
  566. CGM.getTypes().ConvertTypeForMem(VT);
  567. layout.push_back(
  568. BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
  569. }
  570. // If that was everything, we're done here.
  571. if (layout.empty()) {
  572. info.StructureType =
  573. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  574. info.CanBeGlobal = true;
  575. return;
  576. }
  577. // Sort the layout by alignment. We have to use a stable sort here
  578. // to get reproducible results. There should probably be an
  579. // llvm::array_pod_stable_sort.
  580. llvm::stable_sort(layout);
  581. // Needed for blocks layout info.
  582. info.BlockHeaderForcedGapOffset = info.BlockSize;
  583. info.BlockHeaderForcedGapSize = CharUnits::Zero();
  584. CharUnits &blockSize = info.BlockSize;
  585. info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
  586. // Assuming that the first byte in the header is maximally aligned,
  587. // get the alignment of the first byte following the header.
  588. CharUnits endAlign = getLowBit(blockSize);
  589. // If the end of the header isn't satisfactorily aligned for the
  590. // maximum thing, look for things that are okay with the header-end
  591. // alignment, and keep appending them until we get something that's
  592. // aligned right. This algorithm is only guaranteed optimal if
  593. // that condition is satisfied at some point; otherwise we can get
  594. // things like:
  595. // header // next byte has alignment 4
  596. // something_with_size_5; // next byte has alignment 1
  597. // something_with_alignment_8;
  598. // which has 7 bytes of padding, as opposed to the naive solution
  599. // which might have less (?).
  600. if (endAlign < maxFieldAlign) {
  601. SmallVectorImpl<BlockLayoutChunk>::iterator
  602. li = layout.begin() + 1, le = layout.end();
  603. // Look for something that the header end is already
  604. // satisfactorily aligned for.
  605. for (; li != le && endAlign < li->Alignment; ++li)
  606. ;
  607. // If we found something that's naturally aligned for the end of
  608. // the header, keep adding things...
  609. if (li != le) {
  610. SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
  611. for (; li != le; ++li) {
  612. assert(endAlign >= li->Alignment);
  613. li->setIndex(info, elementTypes.size(), blockSize);
  614. elementTypes.push_back(li->Type);
  615. blockSize += li->Size;
  616. endAlign = getLowBit(blockSize);
  617. // ...until we get to the alignment of the maximum field.
  618. if (endAlign >= maxFieldAlign) {
  619. break;
  620. }
  621. }
  622. // Don't re-append everything we just appended.
  623. layout.erase(first, li);
  624. }
  625. }
  626. assert(endAlign == getLowBit(blockSize));
  627. // At this point, we just have to add padding if the end align still
  628. // isn't aligned right.
  629. if (endAlign < maxFieldAlign) {
  630. CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
  631. CharUnits padding = newBlockSize - blockSize;
  632. // If we haven't yet added any fields, remember that there was an
  633. // initial gap; this need to go into the block layout bit map.
  634. if (blockSize == info.BlockHeaderForcedGapOffset) {
  635. info.BlockHeaderForcedGapSize = padding;
  636. }
  637. elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
  638. padding.getQuantity()));
  639. blockSize = newBlockSize;
  640. endAlign = getLowBit(blockSize); // might be > maxFieldAlign
  641. }
  642. assert(endAlign >= maxFieldAlign);
  643. assert(endAlign == getLowBit(blockSize));
  644. // Slam everything else on now. This works because they have
  645. // strictly decreasing alignment and we expect that size is always a
  646. // multiple of alignment.
  647. for (SmallVectorImpl<BlockLayoutChunk>::iterator
  648. li = layout.begin(), le = layout.end(); li != le; ++li) {
  649. if (endAlign < li->Alignment) {
  650. // size may not be multiple of alignment. This can only happen with
  651. // an over-aligned variable. We will be adding a padding field to
  652. // make the size be multiple of alignment.
  653. CharUnits padding = li->Alignment - endAlign;
  654. elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
  655. padding.getQuantity()));
  656. blockSize += padding;
  657. endAlign = getLowBit(blockSize);
  658. }
  659. assert(endAlign >= li->Alignment);
  660. li->setIndex(info, elementTypes.size(), blockSize);
  661. elementTypes.push_back(li->Type);
  662. blockSize += li->Size;
  663. endAlign = getLowBit(blockSize);
  664. }
  665. info.StructureType =
  666. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  667. }
  668. /// Enter the scope of a block. This should be run at the entrance to
  669. /// a full-expression so that the block's cleanups are pushed at the
  670. /// right place in the stack.
  671. static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
  672. assert(CGF.HaveInsertPoint());
  673. // Allocate the block info and place it at the head of the list.
  674. CGBlockInfo &blockInfo =
  675. *new CGBlockInfo(block, CGF.CurFn->getName());
  676. blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
  677. CGF.FirstBlockInfo = &blockInfo;
  678. // Compute information about the layout, etc., of this block,
  679. // pushing cleanups as necessary.
  680. computeBlockInfo(CGF.CGM, &CGF, blockInfo);
  681. // Nothing else to do if it can be global.
  682. if (blockInfo.CanBeGlobal) return;
  683. // Make the allocation for the block.
  684. blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
  685. blockInfo.BlockAlign, "block");
  686. // If there are cleanups to emit, enter them (but inactive).
  687. if (!blockInfo.NeedsCopyDispose) return;
  688. // Walk through the captures (in order) and find the ones not
  689. // captured by constant.
  690. for (const auto &CI : block->captures()) {
  691. // Ignore __block captures; there's nothing special in the
  692. // on-stack block that we need to do for them.
  693. if (CI.isByRef()) continue;
  694. // Ignore variables that are constant-captured.
  695. const VarDecl *variable = CI.getVariable();
  696. CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  697. if (capture.isConstant()) continue;
  698. // Ignore objects that aren't destructed.
  699. QualType VT = getCaptureFieldType(CGF, CI);
  700. QualType::DestructionKind dtorKind = VT.isDestructedType();
  701. if (dtorKind == QualType::DK_none) continue;
  702. CodeGenFunction::Destroyer *destroyer;
  703. // Block captures count as local values and have imprecise semantics.
  704. // They also can't be arrays, so need to worry about that.
  705. //
  706. // For const-qualified captures, emit clang.arc.use to ensure the captured
  707. // object doesn't get released while we are still depending on its validity
  708. // within the block.
  709. if (VT.isConstQualified() &&
  710. VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
  711. CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
  712. assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
  713. "expected ObjC ARC to be enabled");
  714. destroyer = CodeGenFunction::emitARCIntrinsicUse;
  715. } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
  716. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  717. } else {
  718. destroyer = CGF.getDestroyer(dtorKind);
  719. }
  720. // GEP down to the address.
  721. Address addr =
  722. CGF.Builder.CreateStructGEP(blockInfo.LocalAddress, capture.getIndex());
  723. // We can use that GEP as the dominating IP.
  724. if (!blockInfo.DominatingIP)
  725. blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
  726. CleanupKind cleanupKind = InactiveNormalCleanup;
  727. bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
  728. if (useArrayEHCleanup)
  729. cleanupKind = InactiveNormalAndEHCleanup;
  730. CGF.pushDestroy(cleanupKind, addr, VT,
  731. destroyer, useArrayEHCleanup);
  732. // Remember where that cleanup was.
  733. capture.setCleanup(CGF.EHStack.stable_begin());
  734. }
  735. }
  736. /// Enter a full-expression with a non-trivial number of objects to
  737. /// clean up. This is in this file because, at the moment, the only
  738. /// kind of cleanup object is a BlockDecl*.
  739. void CodeGenFunction::enterNonTrivialFullExpression(const FullExpr *E) {
  740. if (const auto EWC = dyn_cast<ExprWithCleanups>(E)) {
  741. assert(EWC->getNumObjects() != 0);
  742. for (const ExprWithCleanups::CleanupObject &C : EWC->getObjects())
  743. enterBlockScope(*this, C);
  744. }
  745. }
  746. /// Find the layout for the given block in a linked list and remove it.
  747. static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
  748. const BlockDecl *block) {
  749. while (true) {
  750. assert(head && *head);
  751. CGBlockInfo *cur = *head;
  752. // If this is the block we're looking for, splice it out of the list.
  753. if (cur->getBlockDecl() == block) {
  754. *head = cur->NextBlockInfo;
  755. return cur;
  756. }
  757. head = &cur->NextBlockInfo;
  758. }
  759. }
  760. /// Destroy a chain of block layouts.
  761. void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
  762. assert(head && "destroying an empty chain");
  763. do {
  764. CGBlockInfo *cur = head;
  765. head = cur->NextBlockInfo;
  766. delete cur;
  767. } while (head != nullptr);
  768. }
  769. /// Emit a block literal expression in the current function.
  770. llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
  771. // If the block has no captures, we won't have a pre-computed
  772. // layout for it.
  773. if (!blockExpr->getBlockDecl()->hasCaptures()) {
  774. // The block literal is emitted as a global variable, and the block invoke
  775. // function has to be extracted from its initializer.
  776. if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) {
  777. return Block;
  778. }
  779. CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
  780. computeBlockInfo(CGM, this, blockInfo);
  781. blockInfo.BlockExpression = blockExpr;
  782. return EmitBlockLiteral(blockInfo);
  783. }
  784. // Find the block info for this block and take ownership of it.
  785. std::unique_ptr<CGBlockInfo> blockInfo;
  786. blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
  787. blockExpr->getBlockDecl()));
  788. blockInfo->BlockExpression = blockExpr;
  789. return EmitBlockLiteral(*blockInfo);
  790. }
  791. llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
  792. bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
  793. auto GenVoidPtrTy =
  794. IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
  795. LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
  796. auto GenVoidPtrSize = CharUnits::fromQuantity(
  797. CGM.getTarget().getPointerWidth(
  798. CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
  799. 8);
  800. // Using the computed layout, generate the actual block function.
  801. bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
  802. CodeGenFunction BlockCGF{CGM, true};
  803. BlockCGF.SanOpts = SanOpts;
  804. auto *InvokeFn = BlockCGF.GenerateBlockFunction(
  805. CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
  806. auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
  807. // If there is nothing to capture, we can emit this as a global block.
  808. if (blockInfo.CanBeGlobal)
  809. return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
  810. // Otherwise, we have to emit this as a local block.
  811. Address blockAddr = blockInfo.LocalAddress;
  812. assert(blockAddr.isValid() && "block has no address!");
  813. llvm::Constant *isa;
  814. llvm::Constant *descriptor;
  815. BlockFlags flags;
  816. if (!IsOpenCL) {
  817. // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
  818. // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
  819. // block just returns the original block and releasing it is a no-op.
  820. llvm::Constant *blockISA = blockInfo.getBlockDecl()->doesNotEscape()
  821. ? CGM.getNSConcreteGlobalBlock()
  822. : CGM.getNSConcreteStackBlock();
  823. isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
  824. // Build the block descriptor.
  825. descriptor = buildBlockDescriptor(CGM, blockInfo);
  826. // Compute the initial on-stack block flags.
  827. flags = BLOCK_HAS_SIGNATURE;
  828. if (blockInfo.HasCapturedVariableLayout)
  829. flags |= BLOCK_HAS_EXTENDED_LAYOUT;
  830. if (blockInfo.needsCopyDisposeHelpers())
  831. flags |= BLOCK_HAS_COPY_DISPOSE;
  832. if (blockInfo.HasCXXObject)
  833. flags |= BLOCK_HAS_CXX_OBJ;
  834. if (blockInfo.UsesStret)
  835. flags |= BLOCK_USE_STRET;
  836. if (blockInfo.getBlockDecl()->doesNotEscape())
  837. flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
  838. }
  839. auto projectField = [&](unsigned index, const Twine &name) -> Address {
  840. return Builder.CreateStructGEP(blockAddr, index, name);
  841. };
  842. auto storeField = [&](llvm::Value *value, unsigned index, const Twine &name) {
  843. Builder.CreateStore(value, projectField(index, name));
  844. };
  845. // Initialize the block header.
  846. {
  847. // We assume all the header fields are densely packed.
  848. unsigned index = 0;
  849. CharUnits offset;
  850. auto addHeaderField = [&](llvm::Value *value, CharUnits size,
  851. const Twine &name) {
  852. storeField(value, index, name);
  853. offset += size;
  854. index++;
  855. };
  856. if (!IsOpenCL) {
  857. addHeaderField(isa, getPointerSize(), "block.isa");
  858. addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
  859. getIntSize(), "block.flags");
  860. addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
  861. "block.reserved");
  862. } else {
  863. addHeaderField(
  864. llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
  865. getIntSize(), "block.size");
  866. addHeaderField(
  867. llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
  868. getIntSize(), "block.align");
  869. }
  870. addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
  871. if (!IsOpenCL)
  872. addHeaderField(descriptor, getPointerSize(), "block.descriptor");
  873. else if (auto *Helper =
  874. CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
  875. for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
  876. addHeaderField(
  877. I.first,
  878. CharUnits::fromQuantity(
  879. CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
  880. I.second);
  881. }
  882. }
  883. }
  884. // Finally, capture all the values into the block.
  885. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  886. // First, 'this'.
  887. if (blockDecl->capturesCXXThis()) {
  888. Address addr =
  889. projectField(blockInfo.CXXThisIndex, "block.captured-this.addr");
  890. Builder.CreateStore(LoadCXXThis(), addr);
  891. }
  892. // Next, captured variables.
  893. for (const auto &CI : blockDecl->captures()) {
  894. const VarDecl *variable = CI.getVariable();
  895. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  896. // Ignore constant captures.
  897. if (capture.isConstant()) continue;
  898. QualType type = capture.fieldType();
  899. // This will be a [[type]]*, except that a byref entry will just be
  900. // an i8**.
  901. Address blockField = projectField(capture.getIndex(), "block.captured");
  902. // Compute the address of the thing we're going to move into the
  903. // block literal.
  904. Address src = Address::invalid();
  905. if (blockDecl->isConversionFromLambda()) {
  906. // The lambda capture in a lambda's conversion-to-block-pointer is
  907. // special; we'll simply emit it directly.
  908. src = Address::invalid();
  909. } else if (CI.isEscapingByref()) {
  910. if (BlockInfo && CI.isNested()) {
  911. // We need to use the capture from the enclosing block.
  912. const CGBlockInfo::Capture &enclosingCapture =
  913. BlockInfo->getCapture(variable);
  914. // This is a [[type]]*, except that a byref entry will just be an i8**.
  915. src = Builder.CreateStructGEP(LoadBlockStruct(),
  916. enclosingCapture.getIndex(),
  917. "block.capture.addr");
  918. } else {
  919. auto I = LocalDeclMap.find(variable);
  920. assert(I != LocalDeclMap.end());
  921. src = I->second;
  922. }
  923. } else {
  924. DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
  925. /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
  926. type.getNonReferenceType(), VK_LValue,
  927. SourceLocation());
  928. src = EmitDeclRefLValue(&declRef).getAddress();
  929. };
  930. // For byrefs, we just write the pointer to the byref struct into
  931. // the block field. There's no need to chase the forwarding
  932. // pointer at this point, since we're building something that will
  933. // live a shorter life than the stack byref anyway.
  934. if (CI.isEscapingByref()) {
  935. // Get a void* that points to the byref struct.
  936. llvm::Value *byrefPointer;
  937. if (CI.isNested())
  938. byrefPointer = Builder.CreateLoad(src, "byref.capture");
  939. else
  940. byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
  941. // Write that void* into the capture field.
  942. Builder.CreateStore(byrefPointer, blockField);
  943. // If we have a copy constructor, evaluate that into the block field.
  944. } else if (const Expr *copyExpr = CI.getCopyExpr()) {
  945. if (blockDecl->isConversionFromLambda()) {
  946. // If we have a lambda conversion, emit the expression
  947. // directly into the block instead.
  948. AggValueSlot Slot =
  949. AggValueSlot::forAddr(blockField, Qualifiers(),
  950. AggValueSlot::IsDestructed,
  951. AggValueSlot::DoesNotNeedGCBarriers,
  952. AggValueSlot::IsNotAliased,
  953. AggValueSlot::DoesNotOverlap);
  954. EmitAggExpr(copyExpr, Slot);
  955. } else {
  956. EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
  957. }
  958. // If it's a reference variable, copy the reference into the block field.
  959. } else if (type->isReferenceType()) {
  960. Builder.CreateStore(src.getPointer(), blockField);
  961. // If type is const-qualified, copy the value into the block field.
  962. } else if (type.isConstQualified() &&
  963. type.getObjCLifetime() == Qualifiers::OCL_Strong &&
  964. CGM.getCodeGenOpts().OptimizationLevel != 0) {
  965. llvm::Value *value = Builder.CreateLoad(src, "captured");
  966. Builder.CreateStore(value, blockField);
  967. // If this is an ARC __strong block-pointer variable, don't do a
  968. // block copy.
  969. //
  970. // TODO: this can be generalized into the normal initialization logic:
  971. // we should never need to do a block-copy when initializing a local
  972. // variable, because the local variable's lifetime should be strictly
  973. // contained within the stack block's.
  974. } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
  975. type->isBlockPointerType()) {
  976. // Load the block and do a simple retain.
  977. llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
  978. value = EmitARCRetainNonBlock(value);
  979. // Do a primitive store to the block field.
  980. Builder.CreateStore(value, blockField);
  981. // Otherwise, fake up a POD copy into the block field.
  982. } else {
  983. // Fake up a new variable so that EmitScalarInit doesn't think
  984. // we're referring to the variable in its own initializer.
  985. ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
  986. ImplicitParamDecl::Other);
  987. // We use one of these or the other depending on whether the
  988. // reference is nested.
  989. DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
  990. /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
  991. type, VK_LValue, SourceLocation());
  992. ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
  993. &declRef, VK_RValue);
  994. // FIXME: Pass a specific location for the expr init so that the store is
  995. // attributed to a reasonable location - otherwise it may be attributed to
  996. // locations of subexpressions in the initialization.
  997. EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
  998. MakeAddrLValue(blockField, type, AlignmentSource::Decl),
  999. /*captured by init*/ false);
  1000. }
  1001. // Activate the cleanup if layout pushed one.
  1002. if (!CI.isByRef()) {
  1003. EHScopeStack::stable_iterator cleanup = capture.getCleanup();
  1004. if (cleanup.isValid())
  1005. ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
  1006. }
  1007. }
  1008. // Cast to the converted block-pointer type, which happens (somewhat
  1009. // unfortunately) to be a pointer to function type.
  1010. llvm::Value *result = Builder.CreatePointerCast(
  1011. blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
  1012. if (IsOpenCL) {
  1013. CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
  1014. result);
  1015. }
  1016. return result;
  1017. }
  1018. llvm::Type *CodeGenModule::getBlockDescriptorType() {
  1019. if (BlockDescriptorType)
  1020. return BlockDescriptorType;
  1021. llvm::Type *UnsignedLongTy =
  1022. getTypes().ConvertType(getContext().UnsignedLongTy);
  1023. // struct __block_descriptor {
  1024. // unsigned long reserved;
  1025. // unsigned long block_size;
  1026. //
  1027. // // later, the following will be added
  1028. //
  1029. // struct {
  1030. // void (*copyHelper)();
  1031. // void (*copyHelper)();
  1032. // } helpers; // !!! optional
  1033. //
  1034. // const char *signature; // the block signature
  1035. // const char *layout; // reserved
  1036. // };
  1037. BlockDescriptorType = llvm::StructType::create(
  1038. "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
  1039. // Now form a pointer to that.
  1040. unsigned AddrSpace = 0;
  1041. if (getLangOpts().OpenCL)
  1042. AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
  1043. BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
  1044. return BlockDescriptorType;
  1045. }
  1046. llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
  1047. if (GenericBlockLiteralType)
  1048. return GenericBlockLiteralType;
  1049. llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
  1050. if (getLangOpts().OpenCL) {
  1051. // struct __opencl_block_literal_generic {
  1052. // int __size;
  1053. // int __align;
  1054. // __generic void *__invoke;
  1055. // /* custom fields */
  1056. // };
  1057. SmallVector<llvm::Type *, 8> StructFields(
  1058. {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
  1059. if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
  1060. for (auto I : Helper->getCustomFieldTypes())
  1061. StructFields.push_back(I);
  1062. }
  1063. GenericBlockLiteralType = llvm::StructType::create(
  1064. StructFields, "struct.__opencl_block_literal_generic");
  1065. } else {
  1066. // struct __block_literal_generic {
  1067. // void *__isa;
  1068. // int __flags;
  1069. // int __reserved;
  1070. // void (*__invoke)(void *);
  1071. // struct __block_descriptor *__descriptor;
  1072. // };
  1073. GenericBlockLiteralType =
  1074. llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
  1075. IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
  1076. }
  1077. return GenericBlockLiteralType;
  1078. }
  1079. RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
  1080. ReturnValueSlot ReturnValue) {
  1081. const BlockPointerType *BPT =
  1082. E->getCallee()->getType()->getAs<BlockPointerType>();
  1083. llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
  1084. llvm::Type *GenBlockTy = CGM.getGenericBlockLiteralType();
  1085. llvm::Value *Func = nullptr;
  1086. QualType FnType = BPT->getPointeeType();
  1087. ASTContext &Ctx = getContext();
  1088. CallArgList Args;
  1089. if (getLangOpts().OpenCL) {
  1090. // For OpenCL, BlockPtr is already casted to generic block literal.
  1091. // First argument of a block call is a generic block literal casted to
  1092. // generic void pointer, i.e. i8 addrspace(4)*
  1093. llvm::Value *BlockDescriptor = Builder.CreatePointerCast(
  1094. BlockPtr, CGM.getOpenCLRuntime().getGenericVoidPointerType());
  1095. QualType VoidPtrQualTy = Ctx.getPointerType(
  1096. Ctx.getAddrSpaceQualType(Ctx.VoidTy, LangAS::opencl_generic));
  1097. Args.add(RValue::get(BlockDescriptor), VoidPtrQualTy);
  1098. // And the rest of the arguments.
  1099. EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
  1100. // We *can* call the block directly unless it is a function argument.
  1101. if (!isa<ParmVarDecl>(E->getCalleeDecl()))
  1102. Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
  1103. else {
  1104. llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
  1105. Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
  1106. }
  1107. } else {
  1108. // Bitcast the block literal to a generic block literal.
  1109. BlockPtr = Builder.CreatePointerCast(
  1110. BlockPtr, llvm::PointerType::get(GenBlockTy, 0), "block.literal");
  1111. // Get pointer to the block invoke function
  1112. llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
  1113. // First argument is a block literal casted to a void pointer
  1114. BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy);
  1115. Args.add(RValue::get(BlockPtr), Ctx.VoidPtrTy);
  1116. // And the rest of the arguments.
  1117. EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
  1118. // Load the function.
  1119. Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
  1120. }
  1121. const FunctionType *FuncTy = FnType->castAs<FunctionType>();
  1122. const CGFunctionInfo &FnInfo =
  1123. CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
  1124. // Cast the function pointer to the right type.
  1125. llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
  1126. llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
  1127. Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
  1128. // Prepare the callee.
  1129. CGCallee Callee(CGCalleeInfo(), Func);
  1130. // And call the block.
  1131. return EmitCall(FnInfo, Callee, ReturnValue, Args);
  1132. }
  1133. Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
  1134. assert(BlockInfo && "evaluating block ref without block information?");
  1135. const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
  1136. // Handle constant captures.
  1137. if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
  1138. Address addr = Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
  1139. "block.capture.addr");
  1140. if (variable->isEscapingByref()) {
  1141. // addr should be a void** right now. Load, then cast the result
  1142. // to byref*.
  1143. auto &byrefInfo = getBlockByrefInfo(variable);
  1144. addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
  1145. auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
  1146. addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
  1147. addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
  1148. variable->getName());
  1149. }
  1150. assert((!variable->isNonEscapingByref() ||
  1151. capture.fieldType()->isReferenceType()) &&
  1152. "the capture field of a non-escaping variable should have a "
  1153. "reference type");
  1154. if (capture.fieldType()->isReferenceType())
  1155. addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
  1156. return addr;
  1157. }
  1158. void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
  1159. llvm::Constant *Addr) {
  1160. bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
  1161. (void)Ok;
  1162. assert(Ok && "Trying to replace an already-existing global block!");
  1163. }
  1164. llvm::Constant *
  1165. CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
  1166. StringRef Name) {
  1167. if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
  1168. return Block;
  1169. CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
  1170. blockInfo.BlockExpression = BE;
  1171. // Compute information about the layout, etc., of this block.
  1172. computeBlockInfo(*this, nullptr, blockInfo);
  1173. // Using that metadata, generate the actual block function.
  1174. {
  1175. CodeGenFunction::DeclMapTy LocalDeclMap;
  1176. CodeGenFunction(*this).GenerateBlockFunction(
  1177. GlobalDecl(), blockInfo, LocalDeclMap,
  1178. /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
  1179. }
  1180. return getAddrOfGlobalBlockIfEmitted(BE);
  1181. }
  1182. static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
  1183. const CGBlockInfo &blockInfo,
  1184. llvm::Constant *blockFn) {
  1185. assert(blockInfo.CanBeGlobal);
  1186. // Callers should detect this case on their own: calling this function
  1187. // generally requires computing layout information, which is a waste of time
  1188. // if we've already emitted this block.
  1189. assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
  1190. "Refusing to re-emit a global block.");
  1191. // Generate the constants for the block literal initializer.
  1192. ConstantInitBuilder builder(CGM);
  1193. auto fields = builder.beginStruct();
  1194. bool IsOpenCL = CGM.getLangOpts().OpenCL;
  1195. bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
  1196. if (!IsOpenCL) {
  1197. // isa
  1198. if (IsWindows)
  1199. fields.addNullPointer(CGM.Int8PtrPtrTy);
  1200. else
  1201. fields.add(CGM.getNSConcreteGlobalBlock());
  1202. // __flags
  1203. BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
  1204. if (blockInfo.UsesStret)
  1205. flags |= BLOCK_USE_STRET;
  1206. fields.addInt(CGM.IntTy, flags.getBitMask());
  1207. // Reserved
  1208. fields.addInt(CGM.IntTy, 0);
  1209. } else {
  1210. fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
  1211. fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
  1212. }
  1213. // Function
  1214. fields.add(blockFn);
  1215. if (!IsOpenCL) {
  1216. // Descriptor
  1217. fields.add(buildBlockDescriptor(CGM, blockInfo));
  1218. } else if (auto *Helper =
  1219. CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
  1220. for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
  1221. fields.add(I);
  1222. }
  1223. }
  1224. unsigned AddrSpace = 0;
  1225. if (CGM.getContext().getLangOpts().OpenCL)
  1226. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
  1227. llvm::Constant *literal = fields.finishAndCreateGlobal(
  1228. "__block_literal_global", blockInfo.BlockAlign,
  1229. /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
  1230. // Windows does not allow globals to be initialised to point to globals in
  1231. // different DLLs. Any such variables must run code to initialise them.
  1232. if (IsWindows) {
  1233. auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
  1234. {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
  1235. &CGM.getModule());
  1236. llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
  1237. Init));
  1238. b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
  1239. b.CreateStructGEP(literal, 0), CGM.getPointerAlign().getQuantity());
  1240. b.CreateRetVoid();
  1241. // We can't use the normal LLVM global initialisation array, because we
  1242. // need to specify that this runs early in library initialisation.
  1243. auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  1244. /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
  1245. Init, ".block_isa_init_ptr");
  1246. InitVar->setSection(".CRT$XCLa");
  1247. CGM.addUsedGlobal(InitVar);
  1248. }
  1249. // Return a constant of the appropriately-casted type.
  1250. llvm::Type *RequiredType =
  1251. CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
  1252. llvm::Constant *Result =
  1253. llvm::ConstantExpr::getPointerCast(literal, RequiredType);
  1254. CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
  1255. if (CGM.getContext().getLangOpts().OpenCL)
  1256. CGM.getOpenCLRuntime().recordBlockInfo(
  1257. blockInfo.BlockExpression,
  1258. cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
  1259. return Result;
  1260. }
  1261. void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
  1262. unsigned argNum,
  1263. llvm::Value *arg) {
  1264. assert(BlockInfo && "not emitting prologue of block invocation function?!");
  1265. // Allocate a stack slot like for any local variable to guarantee optimal
  1266. // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
  1267. Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
  1268. Builder.CreateStore(arg, alloc);
  1269. if (CGDebugInfo *DI = getDebugInfo()) {
  1270. if (CGM.getCodeGenOpts().getDebugInfo() >=
  1271. codegenoptions::LimitedDebugInfo) {
  1272. DI->setLocation(D->getLocation());
  1273. DI->EmitDeclareOfBlockLiteralArgVariable(
  1274. *BlockInfo, D->getName(), argNum,
  1275. cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
  1276. }
  1277. }
  1278. SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
  1279. ApplyDebugLocation Scope(*this, StartLoc);
  1280. // Instead of messing around with LocalDeclMap, just set the value
  1281. // directly as BlockPointer.
  1282. BlockPointer = Builder.CreatePointerCast(
  1283. arg,
  1284. BlockInfo->StructureType->getPointerTo(
  1285. getContext().getLangOpts().OpenCL
  1286. ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
  1287. : 0),
  1288. "block");
  1289. }
  1290. Address CodeGenFunction::LoadBlockStruct() {
  1291. assert(BlockInfo && "not in a block invocation function!");
  1292. assert(BlockPointer && "no block pointer set!");
  1293. return Address(BlockPointer, BlockInfo->BlockAlign);
  1294. }
  1295. llvm::Function *
  1296. CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
  1297. const CGBlockInfo &blockInfo,
  1298. const DeclMapTy &ldm,
  1299. bool IsLambdaConversionToBlock,
  1300. bool BuildGlobalBlock) {
  1301. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  1302. CurGD = GD;
  1303. CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
  1304. BlockInfo = &blockInfo;
  1305. // Arrange for local static and local extern declarations to appear
  1306. // to be local to this function as well, in case they're directly
  1307. // referenced in a block.
  1308. for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
  1309. const auto *var = dyn_cast<VarDecl>(i->first);
  1310. if (var && !var->hasLocalStorage())
  1311. setAddrOfLocalVar(var, i->second);
  1312. }
  1313. // Begin building the function declaration.
  1314. // Build the argument list.
  1315. FunctionArgList args;
  1316. // The first argument is the block pointer. Just take it as a void*
  1317. // and cast it later.
  1318. QualType selfTy = getContext().VoidPtrTy;
  1319. // For OpenCL passed block pointer can be private AS local variable or
  1320. // global AS program scope variable (for the case with and without captures).
  1321. // Generic AS is used therefore to be able to accommodate both private and
  1322. // generic AS in one implementation.
  1323. if (getLangOpts().OpenCL)
  1324. selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
  1325. getContext().VoidTy, LangAS::opencl_generic));
  1326. IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
  1327. ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
  1328. SourceLocation(), II, selfTy,
  1329. ImplicitParamDecl::ObjCSelf);
  1330. args.push_back(&SelfDecl);
  1331. // Now add the rest of the parameters.
  1332. args.append(blockDecl->param_begin(), blockDecl->param_end());
  1333. // Create the function declaration.
  1334. const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
  1335. const CGFunctionInfo &fnInfo =
  1336. CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
  1337. if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
  1338. blockInfo.UsesStret = true;
  1339. llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
  1340. StringRef name = CGM.getBlockMangledName(GD, blockDecl);
  1341. llvm::Function *fn = llvm::Function::Create(
  1342. fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
  1343. CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
  1344. if (BuildGlobalBlock) {
  1345. auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
  1346. ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
  1347. : VoidPtrTy;
  1348. buildGlobalBlock(CGM, blockInfo,
  1349. llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
  1350. }
  1351. // Begin generating the function.
  1352. StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
  1353. blockDecl->getLocation(),
  1354. blockInfo.getBlockExpr()->getBody()->getBeginLoc());
  1355. // Okay. Undo some of what StartFunction did.
  1356. // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
  1357. // won't delete the dbg.declare intrinsics for captured variables.
  1358. llvm::Value *BlockPointerDbgLoc = BlockPointer;
  1359. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1360. // Allocate a stack slot for it, so we can point the debugger to it
  1361. Address Alloca = CreateTempAlloca(BlockPointer->getType(),
  1362. getPointerAlign(),
  1363. "block.addr");
  1364. // Set the DebugLocation to empty, so the store is recognized as a
  1365. // frame setup instruction by llvm::DwarfDebug::beginFunction().
  1366. auto NL = ApplyDebugLocation::CreateEmpty(*this);
  1367. Builder.CreateStore(BlockPointer, Alloca);
  1368. BlockPointerDbgLoc = Alloca.getPointer();
  1369. }
  1370. // If we have a C++ 'this' reference, go ahead and force it into
  1371. // existence now.
  1372. if (blockDecl->capturesCXXThis()) {
  1373. Address addr = Builder.CreateStructGEP(
  1374. LoadBlockStruct(), blockInfo.CXXThisIndex, "block.captured-this");
  1375. CXXThisValue = Builder.CreateLoad(addr, "this");
  1376. }
  1377. // Also force all the constant captures.
  1378. for (const auto &CI : blockDecl->captures()) {
  1379. const VarDecl *variable = CI.getVariable();
  1380. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1381. if (!capture.isConstant()) continue;
  1382. CharUnits align = getContext().getDeclAlign(variable);
  1383. Address alloca =
  1384. CreateMemTemp(variable->getType(), align, "block.captured-const");
  1385. Builder.CreateStore(capture.getConstant(), alloca);
  1386. setAddrOfLocalVar(variable, alloca);
  1387. }
  1388. // Save a spot to insert the debug information for all the DeclRefExprs.
  1389. llvm::BasicBlock *entry = Builder.GetInsertBlock();
  1390. llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
  1391. --entry_ptr;
  1392. if (IsLambdaConversionToBlock)
  1393. EmitLambdaBlockInvokeBody();
  1394. else {
  1395. PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
  1396. incrementProfileCounter(blockDecl->getBody());
  1397. EmitStmt(blockDecl->getBody());
  1398. }
  1399. // Remember where we were...
  1400. llvm::BasicBlock *resume = Builder.GetInsertBlock();
  1401. // Go back to the entry.
  1402. ++entry_ptr;
  1403. Builder.SetInsertPoint(entry, entry_ptr);
  1404. // Emit debug information for all the DeclRefExprs.
  1405. // FIXME: also for 'this'
  1406. if (CGDebugInfo *DI = getDebugInfo()) {
  1407. for (const auto &CI : blockDecl->captures()) {
  1408. const VarDecl *variable = CI.getVariable();
  1409. DI->EmitLocation(Builder, variable->getLocation());
  1410. if (CGM.getCodeGenOpts().getDebugInfo() >=
  1411. codegenoptions::LimitedDebugInfo) {
  1412. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1413. if (capture.isConstant()) {
  1414. auto addr = LocalDeclMap.find(variable)->second;
  1415. (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
  1416. Builder);
  1417. continue;
  1418. }
  1419. DI->EmitDeclareOfBlockDeclRefVariable(
  1420. variable, BlockPointerDbgLoc, Builder, blockInfo,
  1421. entry_ptr == entry->end() ? nullptr : &*entry_ptr);
  1422. }
  1423. }
  1424. // Recover location if it was changed in the above loop.
  1425. DI->EmitLocation(Builder,
  1426. cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
  1427. }
  1428. // And resume where we left off.
  1429. if (resume == nullptr)
  1430. Builder.ClearInsertionPoint();
  1431. else
  1432. Builder.SetInsertPoint(resume);
  1433. FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
  1434. return fn;
  1435. }
  1436. static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
  1437. computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
  1438. const LangOptions &LangOpts) {
  1439. if (CI.getCopyExpr()) {
  1440. assert(!CI.isByRef());
  1441. // don't bother computing flags
  1442. return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
  1443. }
  1444. BlockFieldFlags Flags;
  1445. if (CI.isEscapingByref()) {
  1446. Flags = BLOCK_FIELD_IS_BYREF;
  1447. if (T.isObjCGCWeak())
  1448. Flags |= BLOCK_FIELD_IS_WEAK;
  1449. return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
  1450. }
  1451. Flags = BLOCK_FIELD_IS_OBJECT;
  1452. bool isBlockPointer = T->isBlockPointerType();
  1453. if (isBlockPointer)
  1454. Flags = BLOCK_FIELD_IS_BLOCK;
  1455. switch (T.isNonTrivialToPrimitiveCopy()) {
  1456. case QualType::PCK_Struct:
  1457. return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
  1458. BlockFieldFlags());
  1459. case QualType::PCK_ARCWeak:
  1460. // We need to register __weak direct captures with the runtime.
  1461. return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
  1462. case QualType::PCK_ARCStrong:
  1463. // We need to retain the copied value for __strong direct captures.
  1464. // If it's a block pointer, we have to copy the block and assign that to
  1465. // the destination pointer, so we might as well use _Block_object_assign.
  1466. // Otherwise we can avoid that.
  1467. return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
  1468. : BlockCaptureEntityKind::BlockObject,
  1469. Flags);
  1470. case QualType::PCK_Trivial:
  1471. case QualType::PCK_VolatileTrivial: {
  1472. if (!T->isObjCRetainableType())
  1473. // For all other types, the memcpy is fine.
  1474. return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
  1475. // Special rules for ARC captures:
  1476. Qualifiers QS = T.getQualifiers();
  1477. // Non-ARC captures of retainable pointers are strong and
  1478. // therefore require a call to _Block_object_assign.
  1479. if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
  1480. return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
  1481. // Otherwise the memcpy is fine.
  1482. return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
  1483. }
  1484. }
  1485. llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
  1486. }
  1487. static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
  1488. computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
  1489. const LangOptions &LangOpts);
  1490. /// Find the set of block captures that need to be explicitly copied or destroy.
  1491. static void findBlockCapturedManagedEntities(
  1492. const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
  1493. SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures) {
  1494. for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
  1495. const VarDecl *Variable = CI.getVariable();
  1496. const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
  1497. if (Capture.isConstant())
  1498. continue;
  1499. QualType VT = Capture.fieldType();
  1500. auto CopyInfo = computeCopyInfoForBlockCapture(CI, VT, LangOpts);
  1501. auto DisposeInfo = computeDestroyInfoForBlockCapture(CI, VT, LangOpts);
  1502. if (CopyInfo.first != BlockCaptureEntityKind::None ||
  1503. DisposeInfo.first != BlockCaptureEntityKind::None)
  1504. ManagedCaptures.emplace_back(CopyInfo.first, DisposeInfo.first,
  1505. CopyInfo.second, DisposeInfo.second, CI,
  1506. Capture);
  1507. }
  1508. // Sort the captures by offset.
  1509. llvm::sort(ManagedCaptures);
  1510. }
  1511. namespace {
  1512. /// Release a __block variable.
  1513. struct CallBlockRelease final : EHScopeStack::Cleanup {
  1514. Address Addr;
  1515. BlockFieldFlags FieldFlags;
  1516. bool LoadBlockVarAddr, CanThrow;
  1517. CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
  1518. bool CT)
  1519. : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
  1520. CanThrow(CT) {}
  1521. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1522. llvm::Value *BlockVarAddr;
  1523. if (LoadBlockVarAddr) {
  1524. BlockVarAddr = CGF.Builder.CreateLoad(Addr);
  1525. BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
  1526. } else {
  1527. BlockVarAddr = Addr.getPointer();
  1528. }
  1529. CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
  1530. }
  1531. };
  1532. } // end anonymous namespace
  1533. /// Check if \p T is a C++ class that has a destructor that can throw.
  1534. bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
  1535. if (const auto *RD = T->getAsCXXRecordDecl())
  1536. if (const CXXDestructorDecl *DD = RD->getDestructor())
  1537. return DD->getType()->getAs<FunctionProtoType>()->canThrow();
  1538. return false;
  1539. }
  1540. // Return a string that has the information about a capture.
  1541. static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
  1542. CaptureStrKind StrKind,
  1543. CharUnits BlockAlignment,
  1544. CodeGenModule &CGM) {
  1545. std::string Str;
  1546. ASTContext &Ctx = CGM.getContext();
  1547. const BlockDecl::Capture &CI = *E.CI;
  1548. QualType CaptureTy = CI.getVariable()->getType();
  1549. BlockCaptureEntityKind Kind;
  1550. BlockFieldFlags Flags;
  1551. // CaptureStrKind::Merged should be passed only when the operations and the
  1552. // flags are the same for copy and dispose.
  1553. assert((StrKind != CaptureStrKind::Merged ||
  1554. (E.CopyKind == E.DisposeKind && E.CopyFlags == E.DisposeFlags)) &&
  1555. "different operations and flags");
  1556. if (StrKind == CaptureStrKind::DisposeHelper) {
  1557. Kind = E.DisposeKind;
  1558. Flags = E.DisposeFlags;
  1559. } else {
  1560. Kind = E.CopyKind;
  1561. Flags = E.CopyFlags;
  1562. }
  1563. switch (Kind) {
  1564. case BlockCaptureEntityKind::CXXRecord: {
  1565. Str += "c";
  1566. SmallString<256> TyStr;
  1567. llvm::raw_svector_ostream Out(TyStr);
  1568. CGM.getCXXABI().getMangleContext().mangleTypeName(CaptureTy, Out);
  1569. Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
  1570. break;
  1571. }
  1572. case BlockCaptureEntityKind::ARCWeak:
  1573. Str += "w";
  1574. break;
  1575. case BlockCaptureEntityKind::ARCStrong:
  1576. Str += "s";
  1577. break;
  1578. case BlockCaptureEntityKind::BlockObject: {
  1579. const VarDecl *Var = CI.getVariable();
  1580. unsigned F = Flags.getBitMask();
  1581. if (F & BLOCK_FIELD_IS_BYREF) {
  1582. Str += "r";
  1583. if (F & BLOCK_FIELD_IS_WEAK)
  1584. Str += "w";
  1585. else {
  1586. // If CaptureStrKind::Merged is passed, check both the copy expression
  1587. // and the destructor.
  1588. if (StrKind != CaptureStrKind::DisposeHelper) {
  1589. if (Ctx.getBlockVarCopyInit(Var).canThrow())
  1590. Str += "c";
  1591. }
  1592. if (StrKind != CaptureStrKind::CopyHelper) {
  1593. if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
  1594. Str += "d";
  1595. }
  1596. }
  1597. } else {
  1598. assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
  1599. if (F == BLOCK_FIELD_IS_BLOCK)
  1600. Str += "b";
  1601. else
  1602. Str += "o";
  1603. }
  1604. break;
  1605. }
  1606. case BlockCaptureEntityKind::NonTrivialCStruct: {
  1607. bool IsVolatile = CaptureTy.isVolatileQualified();
  1608. CharUnits Alignment =
  1609. BlockAlignment.alignmentAtOffset(E.Capture->getOffset());
  1610. Str += "n";
  1611. std::string FuncStr;
  1612. if (StrKind == CaptureStrKind::DisposeHelper)
  1613. FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
  1614. CaptureTy, Alignment, IsVolatile, Ctx);
  1615. else
  1616. // If CaptureStrKind::Merged is passed, use the copy constructor string.
  1617. // It has all the information that the destructor string has.
  1618. FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
  1619. CaptureTy, Alignment, IsVolatile, Ctx);
  1620. // The underscore is necessary here because non-trivial copy constructor
  1621. // and destructor strings can start with a number.
  1622. Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
  1623. break;
  1624. }
  1625. case BlockCaptureEntityKind::None:
  1626. break;
  1627. }
  1628. return Str;
  1629. }
  1630. static std::string getCopyDestroyHelperFuncName(
  1631. const SmallVectorImpl<BlockCaptureManagedEntity> &Captures,
  1632. CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
  1633. assert((StrKind == CaptureStrKind::CopyHelper ||
  1634. StrKind == CaptureStrKind::DisposeHelper) &&
  1635. "unexpected CaptureStrKind");
  1636. std::string Name = StrKind == CaptureStrKind::CopyHelper
  1637. ? "__copy_helper_block_"
  1638. : "__destroy_helper_block_";
  1639. if (CGM.getLangOpts().Exceptions)
  1640. Name += "e";
  1641. if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
  1642. Name += "a";
  1643. Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
  1644. for (const BlockCaptureManagedEntity &E : Captures) {
  1645. Name += llvm::to_string(E.Capture->getOffset().getQuantity());
  1646. Name += getBlockCaptureStr(E, StrKind, BlockAlignment, CGM);
  1647. }
  1648. return Name;
  1649. }
  1650. static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
  1651. Address Field, QualType CaptureType,
  1652. BlockFieldFlags Flags, bool ForCopyHelper,
  1653. VarDecl *Var, CodeGenFunction &CGF) {
  1654. bool EHOnly = ForCopyHelper;
  1655. switch (CaptureKind) {
  1656. case BlockCaptureEntityKind::CXXRecord:
  1657. case BlockCaptureEntityKind::ARCWeak:
  1658. case BlockCaptureEntityKind::NonTrivialCStruct:
  1659. case BlockCaptureEntityKind::ARCStrong: {
  1660. if (CaptureType.isDestructedType() &&
  1661. (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
  1662. CodeGenFunction::Destroyer *Destroyer =
  1663. CaptureKind == BlockCaptureEntityKind::ARCStrong
  1664. ? CodeGenFunction::destroyARCStrongImprecise
  1665. : CGF.getDestroyer(CaptureType.isDestructedType());
  1666. CleanupKind Kind =
  1667. EHOnly ? EHCleanup
  1668. : CGF.getCleanupKind(CaptureType.isDestructedType());
  1669. CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
  1670. }
  1671. break;
  1672. }
  1673. case BlockCaptureEntityKind::BlockObject: {
  1674. if (!EHOnly || CGF.getLangOpts().Exceptions) {
  1675. CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
  1676. // Calls to _Block_object_dispose along the EH path in the copy helper
  1677. // function don't throw as newly-copied __block variables always have a
  1678. // reference count of 2.
  1679. bool CanThrow =
  1680. !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
  1681. CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
  1682. CanThrow);
  1683. }
  1684. break;
  1685. }
  1686. case BlockCaptureEntityKind::None:
  1687. break;
  1688. }
  1689. }
  1690. static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
  1691. llvm::Function *Fn,
  1692. const CGFunctionInfo &FI,
  1693. CodeGenModule &CGM) {
  1694. if (CapturesNonExternalType) {
  1695. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
  1696. } else {
  1697. Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1698. Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1699. CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn);
  1700. CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
  1701. }
  1702. }
  1703. /// Generate the copy-helper function for a block closure object:
  1704. /// static void block_copy_helper(block_t *dst, block_t *src);
  1705. /// The runtime will have previously initialized 'dst' by doing a
  1706. /// bit-copy of 'src'.
  1707. ///
  1708. /// Note that this copies an entire block closure object to the heap;
  1709. /// it should not be confused with a 'byref copy helper', which moves
  1710. /// the contents of an individual __block variable to the heap.
  1711. llvm::Constant *
  1712. CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
  1713. SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
  1714. findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures);
  1715. std::string FuncName =
  1716. getCopyDestroyHelperFuncName(CopiedCaptures, blockInfo.BlockAlign,
  1717. CaptureStrKind::CopyHelper, CGM);
  1718. if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
  1719. return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
  1720. ASTContext &C = getContext();
  1721. QualType ReturnTy = C.VoidTy;
  1722. FunctionArgList args;
  1723. ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
  1724. args.push_back(&DstDecl);
  1725. ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
  1726. args.push_back(&SrcDecl);
  1727. const CGFunctionInfo &FI =
  1728. CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
  1729. // FIXME: it would be nice if these were mergeable with things with
  1730. // identical semantics.
  1731. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  1732. llvm::Function *Fn =
  1733. llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
  1734. FuncName, &CGM.getModule());
  1735. if (CGM.supportsCOMDAT())
  1736. Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
  1737. IdentifierInfo *II = &C.Idents.get(FuncName);
  1738. SmallVector<QualType, 2> ArgTys;
  1739. ArgTys.push_back(C.VoidPtrTy);
  1740. ArgTys.push_back(C.VoidPtrTy);
  1741. QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
  1742. FunctionDecl *FD = FunctionDecl::Create(
  1743. C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
  1744. FunctionTy, nullptr, SC_Static, false, false);
  1745. setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
  1746. CGM);
  1747. StartFunction(FD, ReturnTy, Fn, FI, args);
  1748. ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
  1749. llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
  1750. Address src = GetAddrOfLocalVar(&SrcDecl);
  1751. src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
  1752. src = Builder.CreateBitCast(src, structPtrTy, "block.source");
  1753. Address dst = GetAddrOfLocalVar(&DstDecl);
  1754. dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
  1755. dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
  1756. for (const auto &CopiedCapture : CopiedCaptures) {
  1757. const BlockDecl::Capture &CI = *CopiedCapture.CI;
  1758. const CGBlockInfo::Capture &capture = *CopiedCapture.Capture;
  1759. QualType captureType = CI.getVariable()->getType();
  1760. BlockFieldFlags flags = CopiedCapture.CopyFlags;
  1761. unsigned index = capture.getIndex();
  1762. Address srcField = Builder.CreateStructGEP(src, index);
  1763. Address dstField = Builder.CreateStructGEP(dst, index);
  1764. switch (CopiedCapture.CopyKind) {
  1765. case BlockCaptureEntityKind::CXXRecord:
  1766. // If there's an explicit copy expression, we do that.
  1767. assert(CI.getCopyExpr() && "copy expression for variable is missing");
  1768. EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
  1769. break;
  1770. case BlockCaptureEntityKind::ARCWeak:
  1771. EmitARCCopyWeak(dstField, srcField);
  1772. break;
  1773. case BlockCaptureEntityKind::NonTrivialCStruct: {
  1774. // If this is a C struct that requires non-trivial copy construction,
  1775. // emit a call to its copy constructor.
  1776. QualType varType = CI.getVariable()->getType();
  1777. callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
  1778. MakeAddrLValue(srcField, varType));
  1779. break;
  1780. }
  1781. case BlockCaptureEntityKind::ARCStrong: {
  1782. llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
  1783. // At -O0, store null into the destination field (so that the
  1784. // storeStrong doesn't over-release) and then call storeStrong.
  1785. // This is a workaround to not having an initStrong call.
  1786. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1787. auto *ty = cast<llvm::PointerType>(srcValue->getType());
  1788. llvm::Value *null = llvm::ConstantPointerNull::get(ty);
  1789. Builder.CreateStore(null, dstField);
  1790. EmitARCStoreStrongCall(dstField, srcValue, true);
  1791. // With optimization enabled, take advantage of the fact that
  1792. // the blocks runtime guarantees a memcpy of the block data, and
  1793. // just emit a retain of the src field.
  1794. } else {
  1795. EmitARCRetainNonBlock(srcValue);
  1796. // Unless EH cleanup is required, we don't need this anymore, so kill
  1797. // it. It's not quite worth the annoyance to avoid creating it in the
  1798. // first place.
  1799. if (!needsEHCleanup(captureType.isDestructedType()))
  1800. cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
  1801. }
  1802. break;
  1803. }
  1804. case BlockCaptureEntityKind::BlockObject: {
  1805. llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
  1806. srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
  1807. llvm::Value *dstAddr =
  1808. Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
  1809. llvm::Value *args[] = {
  1810. dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
  1811. };
  1812. if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
  1813. EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
  1814. else
  1815. EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
  1816. break;
  1817. }
  1818. case BlockCaptureEntityKind::None:
  1819. continue;
  1820. }
  1821. // Ensure that we destroy the copied object if an exception is thrown later
  1822. // in the helper function.
  1823. pushCaptureCleanup(CopiedCapture.CopyKind, dstField, captureType, flags,
  1824. /*ForCopyHelper*/ true, CI.getVariable(), *this);
  1825. }
  1826. FinishFunction();
  1827. return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  1828. }
  1829. static BlockFieldFlags
  1830. getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
  1831. QualType T) {
  1832. BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
  1833. if (T->isBlockPointerType())
  1834. Flags = BLOCK_FIELD_IS_BLOCK;
  1835. return Flags;
  1836. }
  1837. static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
  1838. computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
  1839. const LangOptions &LangOpts) {
  1840. if (CI.isEscapingByref()) {
  1841. BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
  1842. if (T.isObjCGCWeak())
  1843. Flags |= BLOCK_FIELD_IS_WEAK;
  1844. return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
  1845. }
  1846. switch (T.isDestructedType()) {
  1847. case QualType::DK_cxx_destructor:
  1848. return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
  1849. case QualType::DK_objc_strong_lifetime:
  1850. // Use objc_storeStrong for __strong direct captures; the
  1851. // dynamic tools really like it when we do this.
  1852. return std::make_pair(BlockCaptureEntityKind::ARCStrong,
  1853. getBlockFieldFlagsForObjCObjectPointer(CI, T));
  1854. case QualType::DK_objc_weak_lifetime:
  1855. // Support __weak direct captures.
  1856. return std::make_pair(BlockCaptureEntityKind::ARCWeak,
  1857. getBlockFieldFlagsForObjCObjectPointer(CI, T));
  1858. case QualType::DK_nontrivial_c_struct:
  1859. return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
  1860. BlockFieldFlags());
  1861. case QualType::DK_none: {
  1862. // Non-ARC captures are strong, and we need to use _Block_object_dispose.
  1863. if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
  1864. !LangOpts.ObjCAutoRefCount)
  1865. return std::make_pair(BlockCaptureEntityKind::BlockObject,
  1866. getBlockFieldFlagsForObjCObjectPointer(CI, T));
  1867. // Otherwise, we have nothing to do.
  1868. return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
  1869. }
  1870. }
  1871. llvm_unreachable("after exhaustive DestructionKind switch");
  1872. }
  1873. /// Generate the destroy-helper function for a block closure object:
  1874. /// static void block_destroy_helper(block_t *theBlock);
  1875. ///
  1876. /// Note that this destroys a heap-allocated block closure object;
  1877. /// it should not be confused with a 'byref destroy helper', which
  1878. /// destroys the heap-allocated contents of an individual __block
  1879. /// variable.
  1880. llvm::Constant *
  1881. CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
  1882. SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
  1883. findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures);
  1884. std::string FuncName =
  1885. getCopyDestroyHelperFuncName(DestroyedCaptures, blockInfo.BlockAlign,
  1886. CaptureStrKind::DisposeHelper, CGM);
  1887. if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
  1888. return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
  1889. ASTContext &C = getContext();
  1890. QualType ReturnTy = C.VoidTy;
  1891. FunctionArgList args;
  1892. ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
  1893. args.push_back(&SrcDecl);
  1894. const CGFunctionInfo &FI =
  1895. CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
  1896. // FIXME: We'd like to put these into a mergable by content, with
  1897. // internal linkage.
  1898. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  1899. llvm::Function *Fn =
  1900. llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
  1901. FuncName, &CGM.getModule());
  1902. if (CGM.supportsCOMDAT())
  1903. Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
  1904. IdentifierInfo *II = &C.Idents.get(FuncName);
  1905. SmallVector<QualType, 1> ArgTys;
  1906. ArgTys.push_back(C.VoidPtrTy);
  1907. QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
  1908. FunctionDecl *FD = FunctionDecl::Create(
  1909. C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
  1910. FunctionTy, nullptr, SC_Static, false, false);
  1911. setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
  1912. CGM);
  1913. StartFunction(FD, ReturnTy, Fn, FI, args);
  1914. markAsIgnoreThreadCheckingAtRuntime(Fn);
  1915. ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
  1916. llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
  1917. Address src = GetAddrOfLocalVar(&SrcDecl);
  1918. src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
  1919. src = Builder.CreateBitCast(src, structPtrTy, "block");
  1920. CodeGenFunction::RunCleanupsScope cleanups(*this);
  1921. for (const auto &DestroyedCapture : DestroyedCaptures) {
  1922. const BlockDecl::Capture &CI = *DestroyedCapture.CI;
  1923. const CGBlockInfo::Capture &capture = *DestroyedCapture.Capture;
  1924. BlockFieldFlags flags = DestroyedCapture.DisposeFlags;
  1925. Address srcField = Builder.CreateStructGEP(src, capture.getIndex());
  1926. pushCaptureCleanup(DestroyedCapture.DisposeKind, srcField,
  1927. CI.getVariable()->getType(), flags,
  1928. /*ForCopyHelper*/ false, CI.getVariable(), *this);
  1929. }
  1930. cleanups.ForceCleanup();
  1931. FinishFunction();
  1932. return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  1933. }
  1934. namespace {
  1935. /// Emits the copy/dispose helper functions for a __block object of id type.
  1936. class ObjectByrefHelpers final : public BlockByrefHelpers {
  1937. BlockFieldFlags Flags;
  1938. public:
  1939. ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
  1940. : BlockByrefHelpers(alignment), Flags(flags) {}
  1941. void emitCopy(CodeGenFunction &CGF, Address destField,
  1942. Address srcField) override {
  1943. destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
  1944. srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
  1945. llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
  1946. unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
  1947. llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
  1948. llvm::FunctionCallee fn = CGF.CGM.getBlockObjectAssign();
  1949. llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
  1950. CGF.EmitNounwindRuntimeCall(fn, args);
  1951. }
  1952. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1953. field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
  1954. llvm::Value *value = CGF.Builder.CreateLoad(field);
  1955. CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
  1956. }
  1957. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1958. id.AddInteger(Flags.getBitMask());
  1959. }
  1960. };
  1961. /// Emits the copy/dispose helpers for an ARC __block __weak variable.
  1962. class ARCWeakByrefHelpers final : public BlockByrefHelpers {
  1963. public:
  1964. ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
  1965. void emitCopy(CodeGenFunction &CGF, Address destField,
  1966. Address srcField) override {
  1967. CGF.EmitARCMoveWeak(destField, srcField);
  1968. }
  1969. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1970. CGF.EmitARCDestroyWeak(field);
  1971. }
  1972. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1973. // 0 is distinguishable from all pointers and byref flags
  1974. id.AddInteger(0);
  1975. }
  1976. };
  1977. /// Emits the copy/dispose helpers for an ARC __block __strong variable
  1978. /// that's not of block-pointer type.
  1979. class ARCStrongByrefHelpers final : public BlockByrefHelpers {
  1980. public:
  1981. ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
  1982. void emitCopy(CodeGenFunction &CGF, Address destField,
  1983. Address srcField) override {
  1984. // Do a "move" by copying the value and then zeroing out the old
  1985. // variable.
  1986. llvm::Value *value = CGF.Builder.CreateLoad(srcField);
  1987. llvm::Value *null =
  1988. llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
  1989. if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1990. CGF.Builder.CreateStore(null, destField);
  1991. CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
  1992. CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
  1993. return;
  1994. }
  1995. CGF.Builder.CreateStore(value, destField);
  1996. CGF.Builder.CreateStore(null, srcField);
  1997. }
  1998. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1999. CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
  2000. }
  2001. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  2002. // 1 is distinguishable from all pointers and byref flags
  2003. id.AddInteger(1);
  2004. }
  2005. };
  2006. /// Emits the copy/dispose helpers for an ARC __block __strong
  2007. /// variable that's of block-pointer type.
  2008. class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
  2009. public:
  2010. ARCStrongBlockByrefHelpers(CharUnits alignment)
  2011. : BlockByrefHelpers(alignment) {}
  2012. void emitCopy(CodeGenFunction &CGF, Address destField,
  2013. Address srcField) override {
  2014. // Do the copy with objc_retainBlock; that's all that
  2015. // _Block_object_assign would do anyway, and we'd have to pass the
  2016. // right arguments to make sure it doesn't get no-op'ed.
  2017. llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
  2018. llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
  2019. CGF.Builder.CreateStore(copy, destField);
  2020. }
  2021. void emitDispose(CodeGenFunction &CGF, Address field) override {
  2022. CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
  2023. }
  2024. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  2025. // 2 is distinguishable from all pointers and byref flags
  2026. id.AddInteger(2);
  2027. }
  2028. };
  2029. /// Emits the copy/dispose helpers for a __block variable with a
  2030. /// nontrivial copy constructor or destructor.
  2031. class CXXByrefHelpers final : public BlockByrefHelpers {
  2032. QualType VarType;
  2033. const Expr *CopyExpr;
  2034. public:
  2035. CXXByrefHelpers(CharUnits alignment, QualType type,
  2036. const Expr *copyExpr)
  2037. : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
  2038. bool needsCopy() const override { return CopyExpr != nullptr; }
  2039. void emitCopy(CodeGenFunction &CGF, Address destField,
  2040. Address srcField) override {
  2041. if (!CopyExpr) return;
  2042. CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
  2043. }
  2044. void emitDispose(CodeGenFunction &CGF, Address field) override {
  2045. EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
  2046. CGF.PushDestructorCleanup(VarType, field);
  2047. CGF.PopCleanupBlocks(cleanupDepth);
  2048. }
  2049. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  2050. id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
  2051. }
  2052. };
  2053. /// Emits the copy/dispose helpers for a __block variable that is a non-trivial
  2054. /// C struct.
  2055. class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
  2056. QualType VarType;
  2057. public:
  2058. NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
  2059. : BlockByrefHelpers(alignment), VarType(type) {}
  2060. void emitCopy(CodeGenFunction &CGF, Address destField,
  2061. Address srcField) override {
  2062. CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
  2063. CGF.MakeAddrLValue(srcField, VarType));
  2064. }
  2065. bool needsDispose() const override {
  2066. return VarType.isDestructedType();
  2067. }
  2068. void emitDispose(CodeGenFunction &CGF, Address field) override {
  2069. EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
  2070. CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
  2071. CGF.PopCleanupBlocks(cleanupDepth);
  2072. }
  2073. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  2074. id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
  2075. }
  2076. };
  2077. } // end anonymous namespace
  2078. static llvm::Constant *
  2079. generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
  2080. BlockByrefHelpers &generator) {
  2081. ASTContext &Context = CGF.getContext();
  2082. QualType ReturnTy = Context.VoidTy;
  2083. FunctionArgList args;
  2084. ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
  2085. args.push_back(&Dst);
  2086. ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
  2087. args.push_back(&Src);
  2088. const CGFunctionInfo &FI =
  2089. CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
  2090. llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
  2091. // FIXME: We'd like to put these into a mergable by content, with
  2092. // internal linkage.
  2093. llvm::Function *Fn =
  2094. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  2095. "__Block_byref_object_copy_", &CGF.CGM.getModule());
  2096. IdentifierInfo *II
  2097. = &Context.Idents.get("__Block_byref_object_copy_");
  2098. SmallVector<QualType, 2> ArgTys;
  2099. ArgTys.push_back(Context.VoidPtrTy);
  2100. ArgTys.push_back(Context.VoidPtrTy);
  2101. QualType FunctionTy = Context.getFunctionType(ReturnTy, ArgTys, {});
  2102. FunctionDecl *FD = FunctionDecl::Create(
  2103. Context, Context.getTranslationUnitDecl(), SourceLocation(),
  2104. SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
  2105. CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
  2106. CGF.StartFunction(FD, ReturnTy, Fn, FI, args);
  2107. if (generator.needsCopy()) {
  2108. llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
  2109. // dst->x
  2110. Address destField = CGF.GetAddrOfLocalVar(&Dst);
  2111. destField = Address(CGF.Builder.CreateLoad(destField),
  2112. byrefInfo.ByrefAlignment);
  2113. destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
  2114. destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
  2115. "dest-object");
  2116. // src->x
  2117. Address srcField = CGF.GetAddrOfLocalVar(&Src);
  2118. srcField = Address(CGF.Builder.CreateLoad(srcField),
  2119. byrefInfo.ByrefAlignment);
  2120. srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
  2121. srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
  2122. "src-object");
  2123. generator.emitCopy(CGF, destField, srcField);
  2124. }
  2125. CGF.FinishFunction();
  2126. return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
  2127. }
  2128. /// Build the copy helper for a __block variable.
  2129. static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
  2130. const BlockByrefInfo &byrefInfo,
  2131. BlockByrefHelpers &generator) {
  2132. CodeGenFunction CGF(CGM);
  2133. return generateByrefCopyHelper(CGF, byrefInfo, generator);
  2134. }
  2135. /// Generate code for a __block variable's dispose helper.
  2136. static llvm::Constant *
  2137. generateByrefDisposeHelper(CodeGenFunction &CGF,
  2138. const BlockByrefInfo &byrefInfo,
  2139. BlockByrefHelpers &generator) {
  2140. ASTContext &Context = CGF.getContext();
  2141. QualType R = Context.VoidTy;
  2142. FunctionArgList args;
  2143. ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
  2144. ImplicitParamDecl::Other);
  2145. args.push_back(&Src);
  2146. const CGFunctionInfo &FI =
  2147. CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
  2148. llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
  2149. // FIXME: We'd like to put these into a mergable by content, with
  2150. // internal linkage.
  2151. llvm::Function *Fn =
  2152. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  2153. "__Block_byref_object_dispose_",
  2154. &CGF.CGM.getModule());
  2155. IdentifierInfo *II
  2156. = &Context.Idents.get("__Block_byref_object_dispose_");
  2157. SmallVector<QualType, 1> ArgTys;
  2158. ArgTys.push_back(Context.VoidPtrTy);
  2159. QualType FunctionTy = Context.getFunctionType(R, ArgTys, {});
  2160. FunctionDecl *FD = FunctionDecl::Create(
  2161. Context, Context.getTranslationUnitDecl(), SourceLocation(),
  2162. SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
  2163. CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
  2164. CGF.StartFunction(FD, R, Fn, FI, args);
  2165. if (generator.needsDispose()) {
  2166. Address addr = CGF.GetAddrOfLocalVar(&Src);
  2167. addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
  2168. auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
  2169. addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
  2170. addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
  2171. generator.emitDispose(CGF, addr);
  2172. }
  2173. CGF.FinishFunction();
  2174. return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
  2175. }
  2176. /// Build the dispose helper for a __block variable.
  2177. static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
  2178. const BlockByrefInfo &byrefInfo,
  2179. BlockByrefHelpers &generator) {
  2180. CodeGenFunction CGF(CGM);
  2181. return generateByrefDisposeHelper(CGF, byrefInfo, generator);
  2182. }
  2183. /// Lazily build the copy and dispose helpers for a __block variable
  2184. /// with the given information.
  2185. template <class T>
  2186. static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
  2187. T &&generator) {
  2188. llvm::FoldingSetNodeID id;
  2189. generator.Profile(id);
  2190. void *insertPos;
  2191. BlockByrefHelpers *node
  2192. = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
  2193. if (node) return static_cast<T*>(node);
  2194. generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
  2195. generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
  2196. T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
  2197. CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
  2198. return copy;
  2199. }
  2200. /// Build the copy and dispose helpers for the given __block variable
  2201. /// emission. Places the helpers in the global cache. Returns null
  2202. /// if no helpers are required.
  2203. BlockByrefHelpers *
  2204. CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
  2205. const AutoVarEmission &emission) {
  2206. const VarDecl &var = *emission.Variable;
  2207. assert(var.isEscapingByref() &&
  2208. "only escaping __block variables need byref helpers");
  2209. QualType type = var.getType();
  2210. auto &byrefInfo = getBlockByrefInfo(&var);
  2211. // The alignment we care about for the purposes of uniquing byref
  2212. // helpers is the alignment of the actual byref value field.
  2213. CharUnits valueAlignment =
  2214. byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
  2215. if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
  2216. const Expr *copyExpr =
  2217. CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
  2218. if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
  2219. return ::buildByrefHelpers(
  2220. CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
  2221. }
  2222. // If type is a non-trivial C struct type that is non-trivial to
  2223. // destructly move or destroy, build the copy and dispose helpers.
  2224. if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
  2225. type.isDestructedType() == QualType::DK_nontrivial_c_struct)
  2226. return ::buildByrefHelpers(
  2227. CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
  2228. // Otherwise, if we don't have a retainable type, there's nothing to do.
  2229. // that the runtime does extra copies.
  2230. if (!type->isObjCRetainableType()) return nullptr;
  2231. Qualifiers qs = type.getQualifiers();
  2232. // If we have lifetime, that dominates.
  2233. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
  2234. switch (lifetime) {
  2235. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  2236. // These are just bits as far as the runtime is concerned.
  2237. case Qualifiers::OCL_ExplicitNone:
  2238. case Qualifiers::OCL_Autoreleasing:
  2239. return nullptr;
  2240. // Tell the runtime that this is ARC __weak, called by the
  2241. // byref routines.
  2242. case Qualifiers::OCL_Weak:
  2243. return ::buildByrefHelpers(CGM, byrefInfo,
  2244. ARCWeakByrefHelpers(valueAlignment));
  2245. // ARC __strong __block variables need to be retained.
  2246. case Qualifiers::OCL_Strong:
  2247. // Block pointers need to be copied, and there's no direct
  2248. // transfer possible.
  2249. if (type->isBlockPointerType()) {
  2250. return ::buildByrefHelpers(CGM, byrefInfo,
  2251. ARCStrongBlockByrefHelpers(valueAlignment));
  2252. // Otherwise, we transfer ownership of the retain from the stack
  2253. // to the heap.
  2254. } else {
  2255. return ::buildByrefHelpers(CGM, byrefInfo,
  2256. ARCStrongByrefHelpers(valueAlignment));
  2257. }
  2258. }
  2259. llvm_unreachable("fell out of lifetime switch!");
  2260. }
  2261. BlockFieldFlags flags;
  2262. if (type->isBlockPointerType()) {
  2263. flags |= BLOCK_FIELD_IS_BLOCK;
  2264. } else if (CGM.getContext().isObjCNSObjectType(type) ||
  2265. type->isObjCObjectPointerType()) {
  2266. flags |= BLOCK_FIELD_IS_OBJECT;
  2267. } else {
  2268. return nullptr;
  2269. }
  2270. if (type.isObjCGCWeak())
  2271. flags |= BLOCK_FIELD_IS_WEAK;
  2272. return ::buildByrefHelpers(CGM, byrefInfo,
  2273. ObjectByrefHelpers(valueAlignment, flags));
  2274. }
  2275. Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
  2276. const VarDecl *var,
  2277. bool followForward) {
  2278. auto &info = getBlockByrefInfo(var);
  2279. return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
  2280. }
  2281. Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
  2282. const BlockByrefInfo &info,
  2283. bool followForward,
  2284. const llvm::Twine &name) {
  2285. // Chase the forwarding address if requested.
  2286. if (followForward) {
  2287. Address forwardingAddr = Builder.CreateStructGEP(baseAddr, 1, "forwarding");
  2288. baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
  2289. }
  2290. return Builder.CreateStructGEP(baseAddr, info.FieldIndex, name);
  2291. }
  2292. /// BuildByrefInfo - This routine changes a __block variable declared as T x
  2293. /// into:
  2294. ///
  2295. /// struct {
  2296. /// void *__isa;
  2297. /// void *__forwarding;
  2298. /// int32_t __flags;
  2299. /// int32_t __size;
  2300. /// void *__copy_helper; // only if needed
  2301. /// void *__destroy_helper; // only if needed
  2302. /// void *__byref_variable_layout;// only if needed
  2303. /// char padding[X]; // only if needed
  2304. /// T x;
  2305. /// } x
  2306. ///
  2307. const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
  2308. auto it = BlockByrefInfos.find(D);
  2309. if (it != BlockByrefInfos.end())
  2310. return it->second;
  2311. llvm::StructType *byrefType =
  2312. llvm::StructType::create(getLLVMContext(),
  2313. "struct.__block_byref_" + D->getNameAsString());
  2314. QualType Ty = D->getType();
  2315. CharUnits size;
  2316. SmallVector<llvm::Type *, 8> types;
  2317. // void *__isa;
  2318. types.push_back(Int8PtrTy);
  2319. size += getPointerSize();
  2320. // void *__forwarding;
  2321. types.push_back(llvm::PointerType::getUnqual(byrefType));
  2322. size += getPointerSize();
  2323. // int32_t __flags;
  2324. types.push_back(Int32Ty);
  2325. size += CharUnits::fromQuantity(4);
  2326. // int32_t __size;
  2327. types.push_back(Int32Ty);
  2328. size += CharUnits::fromQuantity(4);
  2329. // Note that this must match *exactly* the logic in buildByrefHelpers.
  2330. bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
  2331. if (hasCopyAndDispose) {
  2332. /// void *__copy_helper;
  2333. types.push_back(Int8PtrTy);
  2334. size += getPointerSize();
  2335. /// void *__destroy_helper;
  2336. types.push_back(Int8PtrTy);
  2337. size += getPointerSize();
  2338. }
  2339. bool HasByrefExtendedLayout = false;
  2340. Qualifiers::ObjCLifetime Lifetime;
  2341. if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
  2342. HasByrefExtendedLayout) {
  2343. /// void *__byref_variable_layout;
  2344. types.push_back(Int8PtrTy);
  2345. size += CharUnits::fromQuantity(PointerSizeInBytes);
  2346. }
  2347. // T x;
  2348. llvm::Type *varTy = ConvertTypeForMem(Ty);
  2349. bool packed = false;
  2350. CharUnits varAlign = getContext().getDeclAlign(D);
  2351. CharUnits varOffset = size.alignTo(varAlign);
  2352. // We may have to insert padding.
  2353. if (varOffset != size) {
  2354. llvm::Type *paddingTy =
  2355. llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
  2356. types.push_back(paddingTy);
  2357. size = varOffset;
  2358. // Conversely, we might have to prevent LLVM from inserting padding.
  2359. } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
  2360. > varAlign.getQuantity()) {
  2361. packed = true;
  2362. }
  2363. types.push_back(varTy);
  2364. byrefType->setBody(types, packed);
  2365. BlockByrefInfo info;
  2366. info.Type = byrefType;
  2367. info.FieldIndex = types.size() - 1;
  2368. info.FieldOffset = varOffset;
  2369. info.ByrefAlignment = std::max(varAlign, getPointerAlign());
  2370. auto pair = BlockByrefInfos.insert({D, info});
  2371. assert(pair.second && "info was inserted recursively?");
  2372. return pair.first->second;
  2373. }
  2374. /// Initialize the structural components of a __block variable, i.e.
  2375. /// everything but the actual object.
  2376. void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
  2377. // Find the address of the local.
  2378. Address addr = emission.Addr;
  2379. // That's an alloca of the byref structure type.
  2380. llvm::StructType *byrefType = cast<llvm::StructType>(
  2381. cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
  2382. unsigned nextHeaderIndex = 0;
  2383. CharUnits nextHeaderOffset;
  2384. auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
  2385. const Twine &name) {
  2386. auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name);
  2387. Builder.CreateStore(value, fieldAddr);
  2388. nextHeaderIndex++;
  2389. nextHeaderOffset += fieldSize;
  2390. };
  2391. // Build the byref helpers if necessary. This is null if we don't need any.
  2392. BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
  2393. const VarDecl &D = *emission.Variable;
  2394. QualType type = D.getType();
  2395. bool HasByrefExtendedLayout;
  2396. Qualifiers::ObjCLifetime ByrefLifetime;
  2397. bool ByRefHasLifetime =
  2398. getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
  2399. llvm::Value *V;
  2400. // Initialize the 'isa', which is just 0 or 1.
  2401. int isa = 0;
  2402. if (type.isObjCGCWeak())
  2403. isa = 1;
  2404. V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
  2405. storeHeaderField(V, getPointerSize(), "byref.isa");
  2406. // Store the address of the variable into its own forwarding pointer.
  2407. storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
  2408. // Blocks ABI:
  2409. // c) the flags field is set to either 0 if no helper functions are
  2410. // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
  2411. BlockFlags flags;
  2412. if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
  2413. if (ByRefHasLifetime) {
  2414. if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
  2415. else switch (ByrefLifetime) {
  2416. case Qualifiers::OCL_Strong:
  2417. flags |= BLOCK_BYREF_LAYOUT_STRONG;
  2418. break;
  2419. case Qualifiers::OCL_Weak:
  2420. flags |= BLOCK_BYREF_LAYOUT_WEAK;
  2421. break;
  2422. case Qualifiers::OCL_ExplicitNone:
  2423. flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
  2424. break;
  2425. case Qualifiers::OCL_None:
  2426. if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
  2427. flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
  2428. break;
  2429. default:
  2430. break;
  2431. }
  2432. if (CGM.getLangOpts().ObjCGCBitmapPrint) {
  2433. printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
  2434. if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
  2435. printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
  2436. if (flags & BLOCK_BYREF_LAYOUT_MASK) {
  2437. BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
  2438. if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
  2439. printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
  2440. if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
  2441. printf(" BLOCK_BYREF_LAYOUT_STRONG");
  2442. if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
  2443. printf(" BLOCK_BYREF_LAYOUT_WEAK");
  2444. if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
  2445. printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
  2446. if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
  2447. printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
  2448. }
  2449. printf("\n");
  2450. }
  2451. }
  2452. storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
  2453. getIntSize(), "byref.flags");
  2454. CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
  2455. V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
  2456. storeHeaderField(V, getIntSize(), "byref.size");
  2457. if (helpers) {
  2458. storeHeaderField(helpers->CopyHelper, getPointerSize(),
  2459. "byref.copyHelper");
  2460. storeHeaderField(helpers->DisposeHelper, getPointerSize(),
  2461. "byref.disposeHelper");
  2462. }
  2463. if (ByRefHasLifetime && HasByrefExtendedLayout) {
  2464. auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
  2465. storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
  2466. }
  2467. }
  2468. void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
  2469. bool CanThrow) {
  2470. llvm::FunctionCallee F = CGM.getBlockObjectDispose();
  2471. llvm::Value *args[] = {
  2472. Builder.CreateBitCast(V, Int8PtrTy),
  2473. llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
  2474. };
  2475. if (CanThrow)
  2476. EmitRuntimeCallOrInvoke(F, args);
  2477. else
  2478. EmitNounwindRuntimeCall(F, args);
  2479. }
  2480. void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
  2481. BlockFieldFlags Flags,
  2482. bool LoadBlockVarAddr, bool CanThrow) {
  2483. EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
  2484. CanThrow);
  2485. }
  2486. /// Adjust the declaration of something from the blocks API.
  2487. static void configureBlocksRuntimeObject(CodeGenModule &CGM,
  2488. llvm::Constant *C) {
  2489. auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
  2490. if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
  2491. IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
  2492. TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
  2493. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2494. assert((isa<llvm::Function>(C->stripPointerCasts()) ||
  2495. isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
  2496. "expected Function or GlobalVariable");
  2497. const NamedDecl *ND = nullptr;
  2498. for (const auto &Result : DC->lookup(&II))
  2499. if ((ND = dyn_cast<FunctionDecl>(Result)) ||
  2500. (ND = dyn_cast<VarDecl>(Result)))
  2501. break;
  2502. // TODO: support static blocks runtime
  2503. if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
  2504. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  2505. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2506. } else {
  2507. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  2508. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2509. }
  2510. }
  2511. if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
  2512. GV->hasExternalLinkage())
  2513. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  2514. CGM.setDSOLocal(GV);
  2515. }
  2516. llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() {
  2517. if (BlockObjectDispose)
  2518. return BlockObjectDispose;
  2519. llvm::Type *args[] = { Int8PtrTy, Int32Ty };
  2520. llvm::FunctionType *fty
  2521. = llvm::FunctionType::get(VoidTy, args, false);
  2522. BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
  2523. configureBlocksRuntimeObject(
  2524. *this, cast<llvm::Constant>(BlockObjectDispose.getCallee()));
  2525. return BlockObjectDispose;
  2526. }
  2527. llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() {
  2528. if (BlockObjectAssign)
  2529. return BlockObjectAssign;
  2530. llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
  2531. llvm::FunctionType *fty
  2532. = llvm::FunctionType::get(VoidTy, args, false);
  2533. BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
  2534. configureBlocksRuntimeObject(
  2535. *this, cast<llvm::Constant>(BlockObjectAssign.getCallee()));
  2536. return BlockObjectAssign;
  2537. }
  2538. llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
  2539. if (NSConcreteGlobalBlock)
  2540. return NSConcreteGlobalBlock;
  2541. NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
  2542. Int8PtrTy->getPointerTo(),
  2543. nullptr);
  2544. configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
  2545. return NSConcreteGlobalBlock;
  2546. }
  2547. llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
  2548. if (NSConcreteStackBlock)
  2549. return NSConcreteStackBlock;
  2550. NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
  2551. Int8PtrTy->getPointerTo(),
  2552. nullptr);
  2553. configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
  2554. return NSConcreteStackBlock;
  2555. }