CGBlocks.cpp 109 KB

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