CGBlocks.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022
  1. //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit blocks.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGDebugInfo.h"
  14. #include "CodeGenFunction.h"
  15. #include "CGObjCRuntime.h"
  16. #include "CodeGenModule.h"
  17. #include "CGBlocks.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "llvm/Module.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/Target/TargetData.h"
  22. #include <algorithm>
  23. using namespace clang;
  24. using namespace CodeGen;
  25. CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
  26. : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
  27. HasCXXObject(false), UsesStret(false), StructureType(0), Block(block),
  28. DominatingIP(0) {
  29. // Skip asm prefix, if any. 'name' is usually taken directly from
  30. // the mangled name of the enclosing function.
  31. if (!name.empty() && name[0] == '\01')
  32. name = name.substr(1);
  33. }
  34. // Anchor the vtable to this translation unit.
  35. CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
  36. /// Build the given block as a global block.
  37. static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
  38. const CGBlockInfo &blockInfo,
  39. llvm::Constant *blockFn);
  40. /// Build the helper function to copy a block.
  41. static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
  42. const CGBlockInfo &blockInfo) {
  43. return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
  44. }
  45. /// Build the helper function to dipose of a block.
  46. static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
  47. const CGBlockInfo &blockInfo) {
  48. return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
  49. }
  50. /// Build the block descriptor constant for a block.
  51. static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
  52. const CGBlockInfo &blockInfo) {
  53. ASTContext &C = CGM.getContext();
  54. llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
  55. llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
  56. SmallVector<llvm::Constant*, 6> elements;
  57. // reserved
  58. elements.push_back(llvm::ConstantInt::get(ulong, 0));
  59. // Size
  60. // FIXME: What is the right way to say this doesn't fit? We should give
  61. // a user diagnostic in that case. Better fix would be to change the
  62. // API to size_t.
  63. elements.push_back(llvm::ConstantInt::get(ulong,
  64. blockInfo.BlockSize.getQuantity()));
  65. // Optional copy/dispose helpers.
  66. if (blockInfo.NeedsCopyDispose) {
  67. // copy_func_helper_decl
  68. elements.push_back(buildCopyHelper(CGM, blockInfo));
  69. // destroy_func_decl
  70. elements.push_back(buildDisposeHelper(CGM, blockInfo));
  71. }
  72. // Signature. Mandatory ObjC-style method descriptor @encode sequence.
  73. std::string typeAtEncoding =
  74. CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
  75. elements.push_back(llvm::ConstantExpr::getBitCast(
  76. CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
  77. // GC layout.
  78. if (C.getLangOptions().ObjC1)
  79. elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
  80. else
  81. elements.push_back(llvm::Constant::getNullValue(i8p));
  82. llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
  83. llvm::GlobalVariable *global =
  84. new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
  85. llvm::GlobalValue::InternalLinkage,
  86. init, "__block_descriptor_tmp");
  87. return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
  88. }
  89. /*
  90. Purely notional variadic template describing the layout of a block.
  91. template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
  92. struct Block_literal {
  93. /// Initialized to one of:
  94. /// extern void *_NSConcreteStackBlock[];
  95. /// extern void *_NSConcreteGlobalBlock[];
  96. ///
  97. /// In theory, we could start one off malloc'ed by setting
  98. /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
  99. /// this isa:
  100. /// extern void *_NSConcreteMallocBlock[];
  101. struct objc_class *isa;
  102. /// These are the flags (with corresponding bit number) that the
  103. /// compiler is actually supposed to know about.
  104. /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
  105. /// descriptor provides copy and dispose helper functions
  106. /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
  107. /// object with a nontrivial destructor or copy constructor
  108. /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
  109. /// as global memory
  110. /// 29. BLOCK_USE_STRET - indicates that the block function
  111. /// uses stret, which objc_msgSend needs to know about
  112. /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
  113. /// @encoded signature string
  114. /// And we're not supposed to manipulate these:
  115. /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
  116. /// to malloc'ed memory
  117. /// 27. BLOCK_IS_GC - indicates that the block has been moved to
  118. /// to GC-allocated memory
  119. /// Additionally, the bottom 16 bits are a reference count which
  120. /// should be zero on the stack.
  121. int flags;
  122. /// Reserved; should be zero-initialized.
  123. int reserved;
  124. /// Function pointer generated from block literal.
  125. _ResultType (*invoke)(Block_literal *, _ParamTypes...);
  126. /// Block description metadata generated from block literal.
  127. struct Block_descriptor *block_descriptor;
  128. /// Captured values follow.
  129. _CapturesTypes captures...;
  130. };
  131. */
  132. /// The number of fields in a block header.
  133. const unsigned BlockHeaderSize = 5;
  134. namespace {
  135. /// A chunk of data that we actually have to capture in the block.
  136. struct BlockLayoutChunk {
  137. CharUnits Alignment;
  138. CharUnits Size;
  139. const BlockDecl::Capture *Capture; // null for 'this'
  140. llvm::Type *Type;
  141. BlockLayoutChunk(CharUnits align, CharUnits size,
  142. const BlockDecl::Capture *capture,
  143. llvm::Type *type)
  144. : Alignment(align), Size(size), Capture(capture), Type(type) {}
  145. /// Tell the block info that this chunk has the given field index.
  146. void setIndex(CGBlockInfo &info, unsigned index) {
  147. if (!Capture)
  148. info.CXXThisIndex = index;
  149. else
  150. info.Captures[Capture->getVariable()]
  151. = CGBlockInfo::Capture::makeIndex(index);
  152. }
  153. };
  154. /// Order by descending alignment.
  155. bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
  156. return left.Alignment > right.Alignment;
  157. }
  158. }
  159. /// Determines if the given type is safe for constant capture in C++.
  160. static bool isSafeForCXXConstantCapture(QualType type) {
  161. const RecordType *recordType =
  162. type->getBaseElementTypeUnsafe()->getAs<RecordType>();
  163. // Only records can be unsafe.
  164. if (!recordType) return true;
  165. const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
  166. // Maintain semantics for classes with non-trivial dtors or copy ctors.
  167. if (!record->hasTrivialDestructor()) return false;
  168. if (!record->hasTrivialCopyConstructor()) return false;
  169. // Otherwise, we just have to make sure there aren't any mutable
  170. // fields that might have changed since initialization.
  171. return !record->hasMutableFields();
  172. }
  173. /// It is illegal to modify a const object after initialization.
  174. /// Therefore, if a const object has a constant initializer, we don't
  175. /// actually need to keep storage for it in the block; we'll just
  176. /// rematerialize it at the start of the block function. This is
  177. /// acceptable because we make no promises about address stability of
  178. /// captured variables.
  179. static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
  180. CodeGenFunction *CGF,
  181. const VarDecl *var) {
  182. QualType type = var->getType();
  183. // We can only do this if the variable is const.
  184. if (!type.isConstQualified()) return 0;
  185. // Furthermore, in C++ we have to worry about mutable fields:
  186. // C++ [dcl.type.cv]p4:
  187. // Except that any class member declared mutable can be
  188. // modified, any attempt to modify a const object during its
  189. // lifetime results in undefined behavior.
  190. if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
  191. return 0;
  192. // If the variable doesn't have any initializer (shouldn't this be
  193. // invalid?), it's not clear what we should do. Maybe capture as
  194. // zero?
  195. const Expr *init = var->getInit();
  196. if (!init) return 0;
  197. return CGM.EmitConstantInit(*var, CGF);
  198. }
  199. /// Get the low bit of a nonzero character count. This is the
  200. /// alignment of the nth byte if the 0th byte is universally aligned.
  201. static CharUnits getLowBit(CharUnits v) {
  202. return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
  203. }
  204. static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
  205. SmallVectorImpl<llvm::Type*> &elementTypes) {
  206. ASTContext &C = CGM.getContext();
  207. // The header is basically a 'struct { void *; int; int; void *; void *; }'.
  208. CharUnits ptrSize, ptrAlign, intSize, intAlign;
  209. llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
  210. llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
  211. // Are there crazy embedded platforms where this isn't true?
  212. assert(intSize <= ptrSize && "layout assumptions horribly violated");
  213. CharUnits headerSize = ptrSize;
  214. if (2 * intSize < ptrAlign) headerSize += ptrSize;
  215. else headerSize += 2 * intSize;
  216. headerSize += 2 * ptrSize;
  217. info.BlockAlign = ptrAlign;
  218. info.BlockSize = headerSize;
  219. assert(elementTypes.empty());
  220. llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
  221. llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
  222. elementTypes.push_back(i8p);
  223. elementTypes.push_back(intTy);
  224. elementTypes.push_back(intTy);
  225. elementTypes.push_back(i8p);
  226. elementTypes.push_back(CGM.getBlockDescriptorType());
  227. assert(elementTypes.size() == BlockHeaderSize);
  228. }
  229. /// Compute the layout of the given block. Attempts to lay the block
  230. /// out with minimal space requirements.
  231. static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
  232. CGBlockInfo &info) {
  233. ASTContext &C = CGM.getContext();
  234. const BlockDecl *block = info.getBlockDecl();
  235. SmallVector<llvm::Type*, 8> elementTypes;
  236. initializeForBlockHeader(CGM, info, elementTypes);
  237. if (!block->hasCaptures()) {
  238. info.StructureType =
  239. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  240. info.CanBeGlobal = true;
  241. return;
  242. }
  243. // Collect the layout chunks.
  244. SmallVector<BlockLayoutChunk, 16> layout;
  245. layout.reserve(block->capturesCXXThis() +
  246. (block->capture_end() - block->capture_begin()));
  247. CharUnits maxFieldAlign;
  248. // First, 'this'.
  249. if (block->capturesCXXThis()) {
  250. const DeclContext *DC = block->getDeclContext();
  251. for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
  252. ;
  253. QualType thisType;
  254. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
  255. thisType = C.getPointerType(C.getRecordType(RD));
  256. else
  257. thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
  258. llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
  259. std::pair<CharUnits,CharUnits> tinfo
  260. = CGM.getContext().getTypeInfoInChars(thisType);
  261. maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
  262. layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
  263. }
  264. // Next, all the block captures.
  265. for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
  266. ce = block->capture_end(); ci != ce; ++ci) {
  267. const VarDecl *variable = ci->getVariable();
  268. if (ci->isByRef()) {
  269. // We have to copy/dispose of the __block reference.
  270. info.NeedsCopyDispose = true;
  271. // Just use void* instead of a pointer to the byref type.
  272. QualType byRefPtrTy = C.VoidPtrTy;
  273. llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
  274. std::pair<CharUnits,CharUnits> tinfo
  275. = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
  276. maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
  277. layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
  278. &*ci, llvmType));
  279. continue;
  280. }
  281. // Otherwise, build a layout chunk with the size and alignment of
  282. // the declaration.
  283. if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
  284. info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
  285. continue;
  286. }
  287. // If we have a lifetime qualifier, honor it for capture purposes.
  288. // That includes *not* copying it if it's __unsafe_unretained.
  289. if (Qualifiers::ObjCLifetime lifetime
  290. = variable->getType().getObjCLifetime()) {
  291. switch (lifetime) {
  292. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  293. case Qualifiers::OCL_ExplicitNone:
  294. case Qualifiers::OCL_Autoreleasing:
  295. break;
  296. case Qualifiers::OCL_Strong:
  297. case Qualifiers::OCL_Weak:
  298. info.NeedsCopyDispose = true;
  299. }
  300. // Block pointers require copy/dispose. So do Objective-C pointers.
  301. } else if (variable->getType()->isObjCRetainableType()) {
  302. info.NeedsCopyDispose = true;
  303. // So do types that require non-trivial copy construction.
  304. } else if (ci->hasCopyExpr()) {
  305. info.NeedsCopyDispose = true;
  306. info.HasCXXObject = true;
  307. // And so do types with destructors.
  308. } else if (CGM.getLangOptions().CPlusPlus) {
  309. if (const CXXRecordDecl *record =
  310. variable->getType()->getAsCXXRecordDecl()) {
  311. if (!record->hasTrivialDestructor()) {
  312. info.HasCXXObject = true;
  313. info.NeedsCopyDispose = true;
  314. }
  315. }
  316. }
  317. QualType VT = variable->getType();
  318. CharUnits size = C.getTypeSizeInChars(VT);
  319. CharUnits align = C.getDeclAlign(variable);
  320. maxFieldAlign = std::max(maxFieldAlign, align);
  321. llvm::Type *llvmType =
  322. CGM.getTypes().ConvertTypeForMem(VT);
  323. layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
  324. }
  325. // If that was everything, we're done here.
  326. if (layout.empty()) {
  327. info.StructureType =
  328. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  329. info.CanBeGlobal = true;
  330. return;
  331. }
  332. // Sort the layout by alignment. We have to use a stable sort here
  333. // to get reproducible results. There should probably be an
  334. // llvm::array_pod_stable_sort.
  335. std::stable_sort(layout.begin(), layout.end());
  336. CharUnits &blockSize = info.BlockSize;
  337. info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
  338. // Assuming that the first byte in the header is maximally aligned,
  339. // get the alignment of the first byte following the header.
  340. CharUnits endAlign = getLowBit(blockSize);
  341. // If the end of the header isn't satisfactorily aligned for the
  342. // maximum thing, look for things that are okay with the header-end
  343. // alignment, and keep appending them until we get something that's
  344. // aligned right. This algorithm is only guaranteed optimal if
  345. // that condition is satisfied at some point; otherwise we can get
  346. // things like:
  347. // header // next byte has alignment 4
  348. // something_with_size_5; // next byte has alignment 1
  349. // something_with_alignment_8;
  350. // which has 7 bytes of padding, as opposed to the naive solution
  351. // which might have less (?).
  352. if (endAlign < maxFieldAlign) {
  353. SmallVectorImpl<BlockLayoutChunk>::iterator
  354. li = layout.begin() + 1, le = layout.end();
  355. // Look for something that the header end is already
  356. // satisfactorily aligned for.
  357. for (; li != le && endAlign < li->Alignment; ++li)
  358. ;
  359. // If we found something that's naturally aligned for the end of
  360. // the header, keep adding things...
  361. if (li != le) {
  362. SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
  363. for (; li != le; ++li) {
  364. assert(endAlign >= li->Alignment);
  365. li->setIndex(info, elementTypes.size());
  366. elementTypes.push_back(li->Type);
  367. blockSize += li->Size;
  368. endAlign = getLowBit(blockSize);
  369. // ...until we get to the alignment of the maximum field.
  370. if (endAlign >= maxFieldAlign)
  371. break;
  372. }
  373. // Don't re-append everything we just appended.
  374. layout.erase(first, li);
  375. }
  376. }
  377. // At this point, we just have to add padding if the end align still
  378. // isn't aligned right.
  379. if (endAlign < maxFieldAlign) {
  380. CharUnits padding = maxFieldAlign - endAlign;
  381. elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
  382. padding.getQuantity()));
  383. blockSize += padding;
  384. endAlign = getLowBit(blockSize);
  385. assert(endAlign >= maxFieldAlign);
  386. }
  387. // Slam everything else on now. This works because they have
  388. // strictly decreasing alignment and we expect that size is always a
  389. // multiple of alignment.
  390. for (SmallVectorImpl<BlockLayoutChunk>::iterator
  391. li = layout.begin(), le = layout.end(); li != le; ++li) {
  392. assert(endAlign >= li->Alignment);
  393. li->setIndex(info, elementTypes.size());
  394. elementTypes.push_back(li->Type);
  395. blockSize += li->Size;
  396. endAlign = getLowBit(blockSize);
  397. }
  398. info.StructureType =
  399. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  400. }
  401. /// Enter the scope of a block. This should be run at the entrance to
  402. /// a full-expression so that the block's cleanups are pushed at the
  403. /// right place in the stack.
  404. static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
  405. // Allocate the block info and place it at the head of the list.
  406. CGBlockInfo &blockInfo =
  407. *new CGBlockInfo(block, CGF.CurFn->getName());
  408. blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
  409. CGF.FirstBlockInfo = &blockInfo;
  410. // Compute information about the layout, etc., of this block,
  411. // pushing cleanups as necessary.
  412. computeBlockInfo(CGF.CGM, &CGF, blockInfo);
  413. // Nothing else to do if it can be global.
  414. if (blockInfo.CanBeGlobal) return;
  415. // Make the allocation for the block.
  416. blockInfo.Address =
  417. CGF.CreateTempAlloca(blockInfo.StructureType, "block");
  418. blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
  419. // If there are cleanups to emit, enter them (but inactive).
  420. if (!blockInfo.NeedsCopyDispose) return;
  421. // Walk through the captures (in order) and find the ones not
  422. // captured by constant.
  423. for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
  424. ce = block->capture_end(); ci != ce; ++ci) {
  425. // Ignore __block captures; there's nothing special in the
  426. // on-stack block that we need to do for them.
  427. if (ci->isByRef()) continue;
  428. // Ignore variables that are constant-captured.
  429. const VarDecl *variable = ci->getVariable();
  430. CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  431. if (capture.isConstant()) continue;
  432. // Ignore objects that aren't destructed.
  433. QualType::DestructionKind dtorKind =
  434. variable->getType().isDestructedType();
  435. if (dtorKind == QualType::DK_none) continue;
  436. CodeGenFunction::Destroyer *destroyer;
  437. // Block captures count as local values and have imprecise semantics.
  438. // They also can't be arrays, so need to worry about that.
  439. if (dtorKind == QualType::DK_objc_strong_lifetime) {
  440. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  441. } else {
  442. destroyer = CGF.getDestroyer(dtorKind);
  443. }
  444. // GEP down to the address.
  445. llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
  446. capture.getIndex());
  447. // We can use that GEP as the dominating IP.
  448. if (!blockInfo.DominatingIP)
  449. blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
  450. CleanupKind cleanupKind = InactiveNormalCleanup;
  451. bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
  452. if (useArrayEHCleanup)
  453. cleanupKind = InactiveNormalAndEHCleanup;
  454. CGF.pushDestroy(cleanupKind, addr, variable->getType(),
  455. destroyer, useArrayEHCleanup);
  456. // Remember where that cleanup was.
  457. capture.setCleanup(CGF.EHStack.stable_begin());
  458. }
  459. }
  460. /// Enter a full-expression with a non-trivial number of objects to
  461. /// clean up. This is in this file because, at the moment, the only
  462. /// kind of cleanup object is a BlockDecl*.
  463. void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
  464. assert(E->getNumObjects() != 0);
  465. ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
  466. for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
  467. i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
  468. enterBlockScope(*this, *i);
  469. }
  470. }
  471. /// Find the layout for the given block in a linked list and remove it.
  472. static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
  473. const BlockDecl *block) {
  474. while (true) {
  475. assert(head && *head);
  476. CGBlockInfo *cur = *head;
  477. // If this is the block we're looking for, splice it out of the list.
  478. if (cur->getBlockDecl() == block) {
  479. *head = cur->NextBlockInfo;
  480. return cur;
  481. }
  482. head = &cur->NextBlockInfo;
  483. }
  484. }
  485. /// Destroy a chain of block layouts.
  486. void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
  487. assert(head && "destroying an empty chain");
  488. do {
  489. CGBlockInfo *cur = head;
  490. head = cur->NextBlockInfo;
  491. delete cur;
  492. } while (head != 0);
  493. }
  494. /// Emit a block literal expression in the current function.
  495. llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
  496. // If the block has no captures, we won't have a pre-computed
  497. // layout for it.
  498. if (!blockExpr->getBlockDecl()->hasCaptures()) {
  499. CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
  500. computeBlockInfo(CGM, this, blockInfo);
  501. blockInfo.BlockExpression = blockExpr;
  502. return EmitBlockLiteral(blockInfo);
  503. }
  504. // Find the block info for this block and take ownership of it.
  505. OwningPtr<CGBlockInfo> blockInfo;
  506. blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
  507. blockExpr->getBlockDecl()));
  508. blockInfo->BlockExpression = blockExpr;
  509. return EmitBlockLiteral(*blockInfo);
  510. }
  511. llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
  512. // Using the computed layout, generate the actual block function.
  513. llvm::Constant *blockFn
  514. = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
  515. CurFuncDecl, LocalDeclMap);
  516. blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
  517. // If there is nothing to capture, we can emit this as a global block.
  518. if (blockInfo.CanBeGlobal)
  519. return buildGlobalBlock(CGM, blockInfo, blockFn);
  520. // Otherwise, we have to emit this as a local block.
  521. llvm::Constant *isa = CGM.getNSConcreteStackBlock();
  522. isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
  523. // Build the block descriptor.
  524. llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
  525. llvm::AllocaInst *blockAddr = blockInfo.Address;
  526. assert(blockAddr && "block has no address!");
  527. // Compute the initial on-stack block flags.
  528. BlockFlags flags = BLOCK_HAS_SIGNATURE;
  529. if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
  530. if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
  531. if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
  532. // Initialize the block literal.
  533. Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
  534. Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
  535. Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
  536. Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
  537. Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
  538. Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
  539. "block.invoke"));
  540. Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
  541. "block.descriptor"));
  542. // Finally, capture all the values into the block.
  543. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  544. // First, 'this'.
  545. if (blockDecl->capturesCXXThis()) {
  546. llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
  547. blockInfo.CXXThisIndex,
  548. "block.captured-this.addr");
  549. Builder.CreateStore(LoadCXXThis(), addr);
  550. }
  551. // Next, captured variables.
  552. for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
  553. ce = blockDecl->capture_end(); ci != ce; ++ci) {
  554. const VarDecl *variable = ci->getVariable();
  555. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  556. // Ignore constant captures.
  557. if (capture.isConstant()) continue;
  558. QualType type = variable->getType();
  559. // This will be a [[type]]*, except that a byref entry will just be
  560. // an i8**.
  561. llvm::Value *blockField =
  562. Builder.CreateStructGEP(blockAddr, capture.getIndex(),
  563. "block.captured");
  564. // Compute the address of the thing we're going to move into the
  565. // block literal.
  566. llvm::Value *src;
  567. if (ci->isNested()) {
  568. // We need to use the capture from the enclosing block.
  569. const CGBlockInfo::Capture &enclosingCapture =
  570. BlockInfo->getCapture(variable);
  571. // This is a [[type]]*, except that a byref entry wil just be an i8**.
  572. src = Builder.CreateStructGEP(LoadBlockStruct(),
  573. enclosingCapture.getIndex(),
  574. "block.capture.addr");
  575. } else {
  576. // This is a [[type]]*.
  577. src = LocalDeclMap[variable];
  578. }
  579. // For byrefs, we just write the pointer to the byref struct into
  580. // the block field. There's no need to chase the forwarding
  581. // pointer at this point, since we're building something that will
  582. // live a shorter life than the stack byref anyway.
  583. if (ci->isByRef()) {
  584. // Get a void* that points to the byref struct.
  585. if (ci->isNested())
  586. src = Builder.CreateLoad(src, "byref.capture");
  587. else
  588. src = Builder.CreateBitCast(src, VoidPtrTy);
  589. // Write that void* into the capture field.
  590. Builder.CreateStore(src, blockField);
  591. // If we have a copy constructor, evaluate that into the block field.
  592. } else if (const Expr *copyExpr = ci->getCopyExpr()) {
  593. EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
  594. // If it's a reference variable, copy the reference into the block field.
  595. } else if (type->isReferenceType()) {
  596. Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
  597. // Otherwise, fake up a POD copy into the block field.
  598. } else {
  599. // Fake up a new variable so that EmitScalarInit doesn't think
  600. // we're referring to the variable in its own initializer.
  601. ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
  602. /*name*/ 0, type);
  603. // We use one of these or the other depending on whether the
  604. // reference is nested.
  605. DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
  606. SourceLocation());
  607. BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
  608. VK_LValue, SourceLocation(), /*byref*/ false);
  609. Expr *declRef =
  610. (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
  611. ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
  612. declRef, VK_RValue);
  613. EmitExprAsInit(&l2r, &blockFieldPseudoVar,
  614. MakeAddrLValue(blockField, type,
  615. getContext().getDeclAlign(variable)),
  616. /*captured by init*/ false);
  617. }
  618. // Activate the cleanup if layout pushed one.
  619. if (!ci->isByRef()) {
  620. EHScopeStack::stable_iterator cleanup = capture.getCleanup();
  621. if (cleanup.isValid())
  622. ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
  623. }
  624. }
  625. // Cast to the converted block-pointer type, which happens (somewhat
  626. // unfortunately) to be a pointer to function type.
  627. llvm::Value *result =
  628. Builder.CreateBitCast(blockAddr,
  629. ConvertType(blockInfo.getBlockExpr()->getType()));
  630. return result;
  631. }
  632. llvm::Type *CodeGenModule::getBlockDescriptorType() {
  633. if (BlockDescriptorType)
  634. return BlockDescriptorType;
  635. llvm::Type *UnsignedLongTy =
  636. getTypes().ConvertType(getContext().UnsignedLongTy);
  637. // struct __block_descriptor {
  638. // unsigned long reserved;
  639. // unsigned long block_size;
  640. //
  641. // // later, the following will be added
  642. //
  643. // struct {
  644. // void (*copyHelper)();
  645. // void (*copyHelper)();
  646. // } helpers; // !!! optional
  647. //
  648. // const char *signature; // the block signature
  649. // const char *layout; // reserved
  650. // };
  651. BlockDescriptorType =
  652. llvm::StructType::create("struct.__block_descriptor",
  653. UnsignedLongTy, UnsignedLongTy, NULL);
  654. // Now form a pointer to that.
  655. BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
  656. return BlockDescriptorType;
  657. }
  658. llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
  659. if (GenericBlockLiteralType)
  660. return GenericBlockLiteralType;
  661. llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
  662. // struct __block_literal_generic {
  663. // void *__isa;
  664. // int __flags;
  665. // int __reserved;
  666. // void (*__invoke)(void *);
  667. // struct __block_descriptor *__descriptor;
  668. // };
  669. GenericBlockLiteralType =
  670. llvm::StructType::create("struct.__block_literal_generic",
  671. VoidPtrTy, IntTy, IntTy, VoidPtrTy,
  672. BlockDescPtrTy, NULL);
  673. return GenericBlockLiteralType;
  674. }
  675. RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
  676. ReturnValueSlot ReturnValue) {
  677. const BlockPointerType *BPT =
  678. E->getCallee()->getType()->getAs<BlockPointerType>();
  679. llvm::Value *Callee = EmitScalarExpr(E->getCallee());
  680. // Get a pointer to the generic block literal.
  681. llvm::Type *BlockLiteralTy =
  682. llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
  683. // Bitcast the callee to a block literal.
  684. llvm::Value *BlockLiteral =
  685. Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
  686. // Get the function pointer from the literal.
  687. llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
  688. BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
  689. // Add the block literal.
  690. CallArgList Args;
  691. Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
  692. QualType FnType = BPT->getPointeeType();
  693. // And the rest of the arguments.
  694. EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
  695. E->arg_begin(), E->arg_end());
  696. // Load the function.
  697. llvm::Value *Func = Builder.CreateLoad(FuncPtr);
  698. const FunctionType *FuncTy = FnType->castAs<FunctionType>();
  699. const CGFunctionInfo &FnInfo =
  700. CGM.getTypes().arrangeFunctionCall(Args, FuncTy);
  701. // Cast the function pointer to the right type.
  702. llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
  703. llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
  704. Func = Builder.CreateBitCast(Func, BlockFTyPtr);
  705. // And call the block.
  706. return EmitCall(FnInfo, Func, ReturnValue, Args);
  707. }
  708. llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
  709. bool isByRef) {
  710. assert(BlockInfo && "evaluating block ref without block information?");
  711. const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
  712. // Handle constant captures.
  713. if (capture.isConstant()) return LocalDeclMap[variable];
  714. llvm::Value *addr =
  715. Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
  716. "block.capture.addr");
  717. if (isByRef) {
  718. // addr should be a void** right now. Load, then cast the result
  719. // to byref*.
  720. addr = Builder.CreateLoad(addr);
  721. llvm::PointerType *byrefPointerType
  722. = llvm::PointerType::get(BuildByRefType(variable), 0);
  723. addr = Builder.CreateBitCast(addr, byrefPointerType,
  724. "byref.addr");
  725. // Follow the forwarding pointer.
  726. addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
  727. addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
  728. // Cast back to byref* and GEP over to the actual object.
  729. addr = Builder.CreateBitCast(addr, byrefPointerType);
  730. addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
  731. variable->getNameAsString());
  732. }
  733. if (variable->getType()->isReferenceType())
  734. addr = Builder.CreateLoad(addr, "ref.tmp");
  735. return addr;
  736. }
  737. llvm::Constant *
  738. CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
  739. const char *name) {
  740. CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
  741. blockInfo.BlockExpression = blockExpr;
  742. // Compute information about the layout, etc., of this block.
  743. computeBlockInfo(*this, 0, blockInfo);
  744. // Using that metadata, generate the actual block function.
  745. llvm::Constant *blockFn;
  746. {
  747. llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
  748. blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
  749. blockInfo,
  750. 0, LocalDeclMap);
  751. }
  752. blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
  753. return buildGlobalBlock(*this, blockInfo, blockFn);
  754. }
  755. static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
  756. const CGBlockInfo &blockInfo,
  757. llvm::Constant *blockFn) {
  758. assert(blockInfo.CanBeGlobal);
  759. // Generate the constants for the block literal initializer.
  760. llvm::Constant *fields[BlockHeaderSize];
  761. // isa
  762. fields[0] = CGM.getNSConcreteGlobalBlock();
  763. // __flags
  764. BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
  765. if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
  766. fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
  767. // Reserved
  768. fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
  769. // Function
  770. fields[3] = blockFn;
  771. // Descriptor
  772. fields[4] = buildBlockDescriptor(CGM, blockInfo);
  773. llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
  774. llvm::GlobalVariable *literal =
  775. new llvm::GlobalVariable(CGM.getModule(),
  776. init->getType(),
  777. /*constant*/ true,
  778. llvm::GlobalVariable::InternalLinkage,
  779. init,
  780. "__block_literal_global");
  781. literal->setAlignment(blockInfo.BlockAlign.getQuantity());
  782. // Return a constant of the appropriately-casted type.
  783. llvm::Type *requiredType =
  784. CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
  785. return llvm::ConstantExpr::getBitCast(literal, requiredType);
  786. }
  787. llvm::Function *
  788. CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
  789. const CGBlockInfo &blockInfo,
  790. const Decl *outerFnDecl,
  791. const DeclMapTy &ldm) {
  792. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  793. // Check if we should generate debug info for this block function.
  794. if (CGM.getModuleDebugInfo())
  795. DebugInfo = CGM.getModuleDebugInfo();
  796. BlockInfo = &blockInfo;
  797. // Arrange for local static and local extern declarations to appear
  798. // to be local to this function as well, in case they're directly
  799. // referenced in a block.
  800. for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
  801. const VarDecl *var = dyn_cast<VarDecl>(i->first);
  802. if (var && !var->hasLocalStorage())
  803. LocalDeclMap[var] = i->second;
  804. }
  805. // Begin building the function declaration.
  806. // Build the argument list.
  807. FunctionArgList args;
  808. // The first argument is the block pointer. Just take it as a void*
  809. // and cast it later.
  810. QualType selfTy = getContext().VoidPtrTy;
  811. IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
  812. ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
  813. SourceLocation(), II, selfTy);
  814. args.push_back(&selfDecl);
  815. // Now add the rest of the parameters.
  816. for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
  817. e = blockDecl->param_end(); i != e; ++i)
  818. args.push_back(*i);
  819. // Create the function declaration.
  820. const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
  821. const CGFunctionInfo &fnInfo =
  822. CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
  823. fnType->getExtInfo(),
  824. fnType->isVariadic());
  825. if (CGM.ReturnTypeUsesSRet(fnInfo))
  826. blockInfo.UsesStret = true;
  827. llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
  828. MangleBuffer name;
  829. CGM.getBlockMangledName(GD, name, blockDecl);
  830. llvm::Function *fn =
  831. llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
  832. name.getString(), &CGM.getModule());
  833. CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
  834. // Begin generating the function.
  835. StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
  836. blockInfo.getBlockExpr()->getBody()->getLocStart());
  837. CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
  838. // Okay. Undo some of what StartFunction did.
  839. // Pull the 'self' reference out of the local decl map.
  840. llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
  841. LocalDeclMap.erase(&selfDecl);
  842. BlockPointer = Builder.CreateBitCast(blockAddr,
  843. blockInfo.StructureType->getPointerTo(),
  844. "block");
  845. // If we have a C++ 'this' reference, go ahead and force it into
  846. // existence now.
  847. if (blockDecl->capturesCXXThis()) {
  848. llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
  849. blockInfo.CXXThisIndex,
  850. "block.captured-this");
  851. CXXThisValue = Builder.CreateLoad(addr, "this");
  852. }
  853. // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
  854. // appease it.
  855. if (const ObjCMethodDecl *method
  856. = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
  857. const VarDecl *self = method->getSelfDecl();
  858. // There might not be a capture for 'self', but if there is...
  859. if (blockInfo.Captures.count(self)) {
  860. const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
  861. llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
  862. capture.getIndex(),
  863. "block.captured-self");
  864. LocalDeclMap[self] = selfAddr;
  865. }
  866. }
  867. // Also force all the constant captures.
  868. for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
  869. ce = blockDecl->capture_end(); ci != ce; ++ci) {
  870. const VarDecl *variable = ci->getVariable();
  871. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  872. if (!capture.isConstant()) continue;
  873. unsigned align = getContext().getDeclAlign(variable).getQuantity();
  874. llvm::AllocaInst *alloca =
  875. CreateMemTemp(variable->getType(), "block.captured-const");
  876. alloca->setAlignment(align);
  877. Builder.CreateStore(capture.getConstant(), alloca, align);
  878. LocalDeclMap[variable] = alloca;
  879. }
  880. // Save a spot to insert the debug information for all the BlockDeclRefDecls.
  881. llvm::BasicBlock *entry = Builder.GetInsertBlock();
  882. llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
  883. --entry_ptr;
  884. EmitStmt(blockDecl->getBody());
  885. // Remember where we were...
  886. llvm::BasicBlock *resume = Builder.GetInsertBlock();
  887. // Go back to the entry.
  888. ++entry_ptr;
  889. Builder.SetInsertPoint(entry, entry_ptr);
  890. // Emit debug information for all the BlockDeclRefDecls.
  891. // FIXME: also for 'this'
  892. if (CGDebugInfo *DI = getDebugInfo()) {
  893. for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
  894. ce = blockDecl->capture_end(); ci != ce; ++ci) {
  895. const VarDecl *variable = ci->getVariable();
  896. DI->EmitLocation(Builder, variable->getLocation());
  897. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  898. if (capture.isConstant()) {
  899. DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
  900. Builder);
  901. continue;
  902. }
  903. DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
  904. Builder, blockInfo);
  905. }
  906. }
  907. // And resume where we left off.
  908. if (resume == 0)
  909. Builder.ClearInsertionPoint();
  910. else
  911. Builder.SetInsertPoint(resume);
  912. FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
  913. return fn;
  914. }
  915. /*
  916. notes.push_back(HelperInfo());
  917. HelperInfo &note = notes.back();
  918. note.index = capture.getIndex();
  919. note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
  920. note.cxxbar_import = ci->getCopyExpr();
  921. if (ci->isByRef()) {
  922. note.flag = BLOCK_FIELD_IS_BYREF;
  923. if (type.isObjCGCWeak())
  924. note.flag |= BLOCK_FIELD_IS_WEAK;
  925. } else if (type->isBlockPointerType()) {
  926. note.flag = BLOCK_FIELD_IS_BLOCK;
  927. } else {
  928. note.flag = BLOCK_FIELD_IS_OBJECT;
  929. }
  930. */
  931. llvm::Constant *
  932. CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
  933. ASTContext &C = getContext();
  934. FunctionArgList args;
  935. ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
  936. args.push_back(&dstDecl);
  937. ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
  938. args.push_back(&srcDecl);
  939. const CGFunctionInfo &FI =
  940. CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
  941. FunctionType::ExtInfo(),
  942. /*variadic*/ false);
  943. // FIXME: it would be nice if these were mergeable with things with
  944. // identical semantics.
  945. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  946. llvm::Function *Fn =
  947. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  948. "__copy_helper_block_", &CGM.getModule());
  949. IdentifierInfo *II
  950. = &CGM.getContext().Idents.get("__copy_helper_block_");
  951. // Check if we should generate debug info for this block helper function.
  952. if (CGM.getModuleDebugInfo())
  953. DebugInfo = CGM.getModuleDebugInfo();
  954. FunctionDecl *FD = FunctionDecl::Create(C,
  955. C.getTranslationUnitDecl(),
  956. SourceLocation(),
  957. SourceLocation(), II, C.VoidTy, 0,
  958. SC_Static,
  959. SC_None,
  960. false,
  961. true);
  962. StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
  963. llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
  964. llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
  965. src = Builder.CreateLoad(src);
  966. src = Builder.CreateBitCast(src, structPtrTy, "block.source");
  967. llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
  968. dst = Builder.CreateLoad(dst);
  969. dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
  970. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  971. for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
  972. ce = blockDecl->capture_end(); ci != ce; ++ci) {
  973. const VarDecl *variable = ci->getVariable();
  974. QualType type = variable->getType();
  975. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  976. if (capture.isConstant()) continue;
  977. const Expr *copyExpr = ci->getCopyExpr();
  978. BlockFieldFlags flags;
  979. bool isARCWeakCapture = false;
  980. if (copyExpr) {
  981. assert(!ci->isByRef());
  982. // don't bother computing flags
  983. } else if (ci->isByRef()) {
  984. flags = BLOCK_FIELD_IS_BYREF;
  985. if (type.isObjCGCWeak())
  986. flags |= BLOCK_FIELD_IS_WEAK;
  987. } else if (type->isObjCRetainableType()) {
  988. flags = BLOCK_FIELD_IS_OBJECT;
  989. if (type->isBlockPointerType())
  990. flags = BLOCK_FIELD_IS_BLOCK;
  991. // Special rules for ARC captures:
  992. if (getLangOptions().ObjCAutoRefCount) {
  993. Qualifiers qs = type.getQualifiers();
  994. // Don't generate special copy logic for a captured object
  995. // unless it's __strong or __weak.
  996. if (!qs.hasStrongOrWeakObjCLifetime())
  997. continue;
  998. // Support __weak direct captures.
  999. if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
  1000. isARCWeakCapture = true;
  1001. }
  1002. } else {
  1003. continue;
  1004. }
  1005. unsigned index = capture.getIndex();
  1006. llvm::Value *srcField = Builder.CreateStructGEP(src, index);
  1007. llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
  1008. // If there's an explicit copy expression, we do that.
  1009. if (copyExpr) {
  1010. EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
  1011. } else if (isARCWeakCapture) {
  1012. EmitARCCopyWeak(dstField, srcField);
  1013. } else {
  1014. llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
  1015. srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
  1016. llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
  1017. Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
  1018. llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
  1019. }
  1020. }
  1021. FinishFunction();
  1022. return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  1023. }
  1024. llvm::Constant *
  1025. CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
  1026. ASTContext &C = getContext();
  1027. FunctionArgList args;
  1028. ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
  1029. args.push_back(&srcDecl);
  1030. const CGFunctionInfo &FI =
  1031. CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
  1032. FunctionType::ExtInfo(),
  1033. /*variadic*/ false);
  1034. // FIXME: We'd like to put these into a mergable by content, with
  1035. // internal linkage.
  1036. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  1037. llvm::Function *Fn =
  1038. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1039. "__destroy_helper_block_", &CGM.getModule());
  1040. // Check if we should generate debug info for this block destroy function.
  1041. if (CGM.getModuleDebugInfo())
  1042. DebugInfo = CGM.getModuleDebugInfo();
  1043. IdentifierInfo *II
  1044. = &CGM.getContext().Idents.get("__destroy_helper_block_");
  1045. FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
  1046. SourceLocation(),
  1047. SourceLocation(), II, C.VoidTy, 0,
  1048. SC_Static,
  1049. SC_None,
  1050. false, true);
  1051. StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
  1052. llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
  1053. llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
  1054. src = Builder.CreateLoad(src);
  1055. src = Builder.CreateBitCast(src, structPtrTy, "block");
  1056. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  1057. CodeGenFunction::RunCleanupsScope cleanups(*this);
  1058. for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
  1059. ce = blockDecl->capture_end(); ci != ce; ++ci) {
  1060. const VarDecl *variable = ci->getVariable();
  1061. QualType type = variable->getType();
  1062. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1063. if (capture.isConstant()) continue;
  1064. BlockFieldFlags flags;
  1065. const CXXDestructorDecl *dtor = 0;
  1066. bool isARCWeakCapture = false;
  1067. if (ci->isByRef()) {
  1068. flags = BLOCK_FIELD_IS_BYREF;
  1069. if (type.isObjCGCWeak())
  1070. flags |= BLOCK_FIELD_IS_WEAK;
  1071. } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
  1072. if (record->hasTrivialDestructor())
  1073. continue;
  1074. dtor = record->getDestructor();
  1075. } else if (type->isObjCRetainableType()) {
  1076. flags = BLOCK_FIELD_IS_OBJECT;
  1077. if (type->isBlockPointerType())
  1078. flags = BLOCK_FIELD_IS_BLOCK;
  1079. // Special rules for ARC captures.
  1080. if (getLangOptions().ObjCAutoRefCount) {
  1081. Qualifiers qs = type.getQualifiers();
  1082. // Don't generate special dispose logic for a captured object
  1083. // unless it's __strong or __weak.
  1084. if (!qs.hasStrongOrWeakObjCLifetime())
  1085. continue;
  1086. // Support __weak direct captures.
  1087. if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
  1088. isARCWeakCapture = true;
  1089. }
  1090. } else {
  1091. continue;
  1092. }
  1093. unsigned index = capture.getIndex();
  1094. llvm::Value *srcField = Builder.CreateStructGEP(src, index);
  1095. // If there's an explicit copy expression, we do that.
  1096. if (dtor) {
  1097. PushDestructorCleanup(dtor, srcField);
  1098. // If this is a __weak capture, emit the release directly.
  1099. } else if (isARCWeakCapture) {
  1100. EmitARCDestroyWeak(srcField);
  1101. // Otherwise we call _Block_object_dispose. It wouldn't be too
  1102. // hard to just emit this as a cleanup if we wanted to make sure
  1103. // that things were done in reverse.
  1104. } else {
  1105. llvm::Value *value = Builder.CreateLoad(srcField);
  1106. value = Builder.CreateBitCast(value, VoidPtrTy);
  1107. BuildBlockRelease(value, flags);
  1108. }
  1109. }
  1110. cleanups.ForceCleanup();
  1111. FinishFunction();
  1112. return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  1113. }
  1114. namespace {
  1115. /// Emits the copy/dispose helper functions for a __block object of id type.
  1116. class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
  1117. BlockFieldFlags Flags;
  1118. public:
  1119. ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
  1120. : ByrefHelpers(alignment), Flags(flags) {}
  1121. void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
  1122. llvm::Value *srcField) {
  1123. destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
  1124. srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
  1125. llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
  1126. unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
  1127. llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
  1128. llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
  1129. CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
  1130. }
  1131. void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
  1132. field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
  1133. llvm::Value *value = CGF.Builder.CreateLoad(field);
  1134. CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
  1135. }
  1136. void profileImpl(llvm::FoldingSetNodeID &id) const {
  1137. id.AddInteger(Flags.getBitMask());
  1138. }
  1139. };
  1140. /// Emits the copy/dispose helpers for an ARC __block __weak variable.
  1141. class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
  1142. public:
  1143. ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
  1144. void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
  1145. llvm::Value *srcField) {
  1146. CGF.EmitARCMoveWeak(destField, srcField);
  1147. }
  1148. void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
  1149. CGF.EmitARCDestroyWeak(field);
  1150. }
  1151. void profileImpl(llvm::FoldingSetNodeID &id) const {
  1152. // 0 is distinguishable from all pointers and byref flags
  1153. id.AddInteger(0);
  1154. }
  1155. };
  1156. /// Emits the copy/dispose helpers for an ARC __block __strong variable
  1157. /// that's not of block-pointer type.
  1158. class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
  1159. public:
  1160. ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
  1161. void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
  1162. llvm::Value *srcField) {
  1163. // Do a "move" by copying the value and then zeroing out the old
  1164. // variable.
  1165. llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
  1166. value->setAlignment(Alignment.getQuantity());
  1167. llvm::Value *null =
  1168. llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
  1169. llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
  1170. store->setAlignment(Alignment.getQuantity());
  1171. store = CGF.Builder.CreateStore(null, srcField);
  1172. store->setAlignment(Alignment.getQuantity());
  1173. }
  1174. void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
  1175. llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
  1176. value->setAlignment(Alignment.getQuantity());
  1177. CGF.EmitARCRelease(value, /*precise*/ false);
  1178. }
  1179. void profileImpl(llvm::FoldingSetNodeID &id) const {
  1180. // 1 is distinguishable from all pointers and byref flags
  1181. id.AddInteger(1);
  1182. }
  1183. };
  1184. /// Emits the copy/dispose helpers for an ARC __block __strong
  1185. /// variable that's of block-pointer type.
  1186. class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
  1187. public:
  1188. ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
  1189. void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
  1190. llvm::Value *srcField) {
  1191. // Do the copy with objc_retainBlock; that's all that
  1192. // _Block_object_assign would do anyway, and we'd have to pass the
  1193. // right arguments to make sure it doesn't get no-op'ed.
  1194. llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
  1195. oldValue->setAlignment(Alignment.getQuantity());
  1196. llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
  1197. llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
  1198. store->setAlignment(Alignment.getQuantity());
  1199. }
  1200. void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
  1201. llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
  1202. value->setAlignment(Alignment.getQuantity());
  1203. CGF.EmitARCRelease(value, /*precise*/ false);
  1204. }
  1205. void profileImpl(llvm::FoldingSetNodeID &id) const {
  1206. // 2 is distinguishable from all pointers and byref flags
  1207. id.AddInteger(2);
  1208. }
  1209. };
  1210. /// Emits the copy/dispose helpers for a __block variable with a
  1211. /// nontrivial copy constructor or destructor.
  1212. class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
  1213. QualType VarType;
  1214. const Expr *CopyExpr;
  1215. public:
  1216. CXXByrefHelpers(CharUnits alignment, QualType type,
  1217. const Expr *copyExpr)
  1218. : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
  1219. bool needsCopy() const { return CopyExpr != 0; }
  1220. void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
  1221. llvm::Value *srcField) {
  1222. if (!CopyExpr) return;
  1223. CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
  1224. }
  1225. void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
  1226. EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
  1227. CGF.PushDestructorCleanup(VarType, field);
  1228. CGF.PopCleanupBlocks(cleanupDepth);
  1229. }
  1230. void profileImpl(llvm::FoldingSetNodeID &id) const {
  1231. id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
  1232. }
  1233. };
  1234. } // end anonymous namespace
  1235. static llvm::Constant *
  1236. generateByrefCopyHelper(CodeGenFunction &CGF,
  1237. llvm::StructType &byrefType,
  1238. CodeGenModule::ByrefHelpers &byrefInfo) {
  1239. ASTContext &Context = CGF.getContext();
  1240. QualType R = Context.VoidTy;
  1241. FunctionArgList args;
  1242. ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
  1243. args.push_back(&dst);
  1244. ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
  1245. args.push_back(&src);
  1246. const CGFunctionInfo &FI =
  1247. CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
  1248. FunctionType::ExtInfo(),
  1249. /*variadic*/ false);
  1250. CodeGenTypes &Types = CGF.CGM.getTypes();
  1251. llvm::FunctionType *LTy = Types.GetFunctionType(FI);
  1252. // FIXME: We'd like to put these into a mergable by content, with
  1253. // internal linkage.
  1254. llvm::Function *Fn =
  1255. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1256. "__Block_byref_object_copy_", &CGF.CGM.getModule());
  1257. IdentifierInfo *II
  1258. = &Context.Idents.get("__Block_byref_object_copy_");
  1259. FunctionDecl *FD = FunctionDecl::Create(Context,
  1260. Context.getTranslationUnitDecl(),
  1261. SourceLocation(),
  1262. SourceLocation(), II, R, 0,
  1263. SC_Static,
  1264. SC_None,
  1265. false, true);
  1266. CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
  1267. if (byrefInfo.needsCopy()) {
  1268. llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
  1269. // dst->x
  1270. llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
  1271. destField = CGF.Builder.CreateLoad(destField);
  1272. destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
  1273. destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
  1274. // src->x
  1275. llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
  1276. srcField = CGF.Builder.CreateLoad(srcField);
  1277. srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
  1278. srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
  1279. byrefInfo.emitCopy(CGF, destField, srcField);
  1280. }
  1281. CGF.FinishFunction();
  1282. return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
  1283. }
  1284. /// Build the copy helper for a __block variable.
  1285. static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
  1286. llvm::StructType &byrefType,
  1287. CodeGenModule::ByrefHelpers &info) {
  1288. CodeGenFunction CGF(CGM);
  1289. return generateByrefCopyHelper(CGF, byrefType, info);
  1290. }
  1291. /// Generate code for a __block variable's dispose helper.
  1292. static llvm::Constant *
  1293. generateByrefDisposeHelper(CodeGenFunction &CGF,
  1294. llvm::StructType &byrefType,
  1295. CodeGenModule::ByrefHelpers &byrefInfo) {
  1296. ASTContext &Context = CGF.getContext();
  1297. QualType R = Context.VoidTy;
  1298. FunctionArgList args;
  1299. ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
  1300. args.push_back(&src);
  1301. const CGFunctionInfo &FI =
  1302. CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
  1303. FunctionType::ExtInfo(),
  1304. /*variadic*/ false);
  1305. CodeGenTypes &Types = CGF.CGM.getTypes();
  1306. llvm::FunctionType *LTy = Types.GetFunctionType(FI);
  1307. // FIXME: We'd like to put these into a mergable by content, with
  1308. // internal linkage.
  1309. llvm::Function *Fn =
  1310. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1311. "__Block_byref_object_dispose_",
  1312. &CGF.CGM.getModule());
  1313. IdentifierInfo *II
  1314. = &Context.Idents.get("__Block_byref_object_dispose_");
  1315. FunctionDecl *FD = FunctionDecl::Create(Context,
  1316. Context.getTranslationUnitDecl(),
  1317. SourceLocation(),
  1318. SourceLocation(), II, R, 0,
  1319. SC_Static,
  1320. SC_None,
  1321. false, true);
  1322. CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
  1323. if (byrefInfo.needsDispose()) {
  1324. llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
  1325. V = CGF.Builder.CreateLoad(V);
  1326. V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
  1327. V = CGF.Builder.CreateStructGEP(V, 6, "x");
  1328. byrefInfo.emitDispose(CGF, V);
  1329. }
  1330. CGF.FinishFunction();
  1331. return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
  1332. }
  1333. /// Build the dispose helper for a __block variable.
  1334. static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
  1335. llvm::StructType &byrefType,
  1336. CodeGenModule::ByrefHelpers &info) {
  1337. CodeGenFunction CGF(CGM);
  1338. return generateByrefDisposeHelper(CGF, byrefType, info);
  1339. }
  1340. ///
  1341. template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
  1342. llvm::StructType &byrefTy,
  1343. T &byrefInfo) {
  1344. // Increase the field's alignment to be at least pointer alignment,
  1345. // since the layout of the byref struct will guarantee at least that.
  1346. byrefInfo.Alignment = std::max(byrefInfo.Alignment,
  1347. CharUnits::fromQuantity(CGM.PointerAlignInBytes));
  1348. llvm::FoldingSetNodeID id;
  1349. byrefInfo.Profile(id);
  1350. void *insertPos;
  1351. CodeGenModule::ByrefHelpers *node
  1352. = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
  1353. if (node) return static_cast<T*>(node);
  1354. byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
  1355. byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
  1356. T *copy = new (CGM.getContext()) T(byrefInfo);
  1357. CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
  1358. return copy;
  1359. }
  1360. CodeGenModule::ByrefHelpers *
  1361. CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
  1362. const AutoVarEmission &emission) {
  1363. const VarDecl &var = *emission.Variable;
  1364. QualType type = var.getType();
  1365. if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
  1366. const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
  1367. if (!copyExpr && record->hasTrivialDestructor()) return 0;
  1368. CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
  1369. return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
  1370. }
  1371. // Otherwise, if we don't have a retainable type, there's nothing to do.
  1372. // that the runtime does extra copies.
  1373. if (!type->isObjCRetainableType()) return 0;
  1374. Qualifiers qs = type.getQualifiers();
  1375. // If we have lifetime, that dominates.
  1376. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
  1377. assert(getLangOptions().ObjCAutoRefCount);
  1378. switch (lifetime) {
  1379. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  1380. // These are just bits as far as the runtime is concerned.
  1381. case Qualifiers::OCL_ExplicitNone:
  1382. case Qualifiers::OCL_Autoreleasing:
  1383. return 0;
  1384. // Tell the runtime that this is ARC __weak, called by the
  1385. // byref routines.
  1386. case Qualifiers::OCL_Weak: {
  1387. ARCWeakByrefHelpers byrefInfo(emission.Alignment);
  1388. return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
  1389. }
  1390. // ARC __strong __block variables need to be retained.
  1391. case Qualifiers::OCL_Strong:
  1392. // Block pointers need to be copied, and there's no direct
  1393. // transfer possible.
  1394. if (type->isBlockPointerType()) {
  1395. ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
  1396. return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
  1397. // Otherwise, we transfer ownership of the retain from the stack
  1398. // to the heap.
  1399. } else {
  1400. ARCStrongByrefHelpers byrefInfo(emission.Alignment);
  1401. return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
  1402. }
  1403. }
  1404. llvm_unreachable("fell out of lifetime switch!");
  1405. }
  1406. BlockFieldFlags flags;
  1407. if (type->isBlockPointerType()) {
  1408. flags |= BLOCK_FIELD_IS_BLOCK;
  1409. } else if (CGM.getContext().isObjCNSObjectType(type) ||
  1410. type->isObjCObjectPointerType()) {
  1411. flags |= BLOCK_FIELD_IS_OBJECT;
  1412. } else {
  1413. return 0;
  1414. }
  1415. if (type.isObjCGCWeak())
  1416. flags |= BLOCK_FIELD_IS_WEAK;
  1417. ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
  1418. return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
  1419. }
  1420. unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
  1421. assert(ByRefValueInfo.count(VD) && "Did not find value!");
  1422. return ByRefValueInfo.find(VD)->second.second;
  1423. }
  1424. llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
  1425. const VarDecl *V) {
  1426. llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
  1427. Loc = Builder.CreateLoad(Loc);
  1428. Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
  1429. V->getNameAsString());
  1430. return Loc;
  1431. }
  1432. /// BuildByRefType - This routine changes a __block variable declared as T x
  1433. /// into:
  1434. ///
  1435. /// struct {
  1436. /// void *__isa;
  1437. /// void *__forwarding;
  1438. /// int32_t __flags;
  1439. /// int32_t __size;
  1440. /// void *__copy_helper; // only if needed
  1441. /// void *__destroy_helper; // only if needed
  1442. /// char padding[X]; // only if needed
  1443. /// T x;
  1444. /// } x
  1445. ///
  1446. llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
  1447. std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
  1448. if (Info.first)
  1449. return Info.first;
  1450. QualType Ty = D->getType();
  1451. SmallVector<llvm::Type *, 8> types;
  1452. llvm::StructType *ByRefType =
  1453. llvm::StructType::create(getLLVMContext(),
  1454. "struct.__block_byref_" + D->getNameAsString());
  1455. // void *__isa;
  1456. types.push_back(Int8PtrTy);
  1457. // void *__forwarding;
  1458. types.push_back(llvm::PointerType::getUnqual(ByRefType));
  1459. // int32_t __flags;
  1460. types.push_back(Int32Ty);
  1461. // int32_t __size;
  1462. types.push_back(Int32Ty);
  1463. bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
  1464. if (HasCopyAndDispose) {
  1465. /// void *__copy_helper;
  1466. types.push_back(Int8PtrTy);
  1467. /// void *__destroy_helper;
  1468. types.push_back(Int8PtrTy);
  1469. }
  1470. bool Packed = false;
  1471. CharUnits Align = getContext().getDeclAlign(D);
  1472. if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
  1473. // We have to insert padding.
  1474. // The struct above has 2 32-bit integers.
  1475. unsigned CurrentOffsetInBytes = 4 * 2;
  1476. // And either 2 or 4 pointers.
  1477. CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
  1478. CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
  1479. // Align the offset.
  1480. unsigned AlignedOffsetInBytes =
  1481. llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
  1482. unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
  1483. if (NumPaddingBytes > 0) {
  1484. llvm::Type *Ty = Int8Ty;
  1485. // FIXME: We need a sema error for alignment larger than the minimum of
  1486. // the maximal stack alignment and the alignment of malloc on the system.
  1487. if (NumPaddingBytes > 1)
  1488. Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
  1489. types.push_back(Ty);
  1490. // We want a packed struct.
  1491. Packed = true;
  1492. }
  1493. }
  1494. // T x;
  1495. types.push_back(ConvertTypeForMem(Ty));
  1496. ByRefType->setBody(types, Packed);
  1497. Info.first = ByRefType;
  1498. Info.second = types.size() - 1;
  1499. return Info.first;
  1500. }
  1501. /// Initialize the structural components of a __block variable, i.e.
  1502. /// everything but the actual object.
  1503. void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
  1504. // Find the address of the local.
  1505. llvm::Value *addr = emission.Address;
  1506. // That's an alloca of the byref structure type.
  1507. llvm::StructType *byrefType = cast<llvm::StructType>(
  1508. cast<llvm::PointerType>(addr->getType())->getElementType());
  1509. // Build the byref helpers if necessary. This is null if we don't need any.
  1510. CodeGenModule::ByrefHelpers *helpers =
  1511. buildByrefHelpers(*byrefType, emission);
  1512. const VarDecl &D = *emission.Variable;
  1513. QualType type = D.getType();
  1514. llvm::Value *V;
  1515. // Initialize the 'isa', which is just 0 or 1.
  1516. int isa = 0;
  1517. if (type.isObjCGCWeak())
  1518. isa = 1;
  1519. V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
  1520. Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
  1521. // Store the address of the variable into its own forwarding pointer.
  1522. Builder.CreateStore(addr,
  1523. Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
  1524. // Blocks ABI:
  1525. // c) the flags field is set to either 0 if no helper functions are
  1526. // needed or BLOCK_HAS_COPY_DISPOSE if they are,
  1527. BlockFlags flags;
  1528. if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
  1529. Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
  1530. Builder.CreateStructGEP(addr, 2, "byref.flags"));
  1531. CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
  1532. V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
  1533. Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
  1534. if (helpers) {
  1535. llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
  1536. Builder.CreateStore(helpers->CopyHelper, copy_helper);
  1537. llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
  1538. Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
  1539. }
  1540. }
  1541. void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
  1542. llvm::Value *F = CGM.getBlockObjectDispose();
  1543. llvm::Value *N;
  1544. V = Builder.CreateBitCast(V, Int8PtrTy);
  1545. N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
  1546. Builder.CreateCall2(F, V, N);
  1547. }
  1548. namespace {
  1549. struct CallBlockRelease : EHScopeStack::Cleanup {
  1550. llvm::Value *Addr;
  1551. CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
  1552. void Emit(CodeGenFunction &CGF, Flags flags) {
  1553. // Should we be passing FIELD_IS_WEAK here?
  1554. CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
  1555. }
  1556. };
  1557. }
  1558. /// Enter a cleanup to destroy a __block variable. Note that this
  1559. /// cleanup should be a no-op if the variable hasn't left the stack
  1560. /// yet; if a cleanup is required for the variable itself, that needs
  1561. /// to be done externally.
  1562. void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
  1563. // We don't enter this cleanup if we're in pure-GC mode.
  1564. if (CGM.getLangOptions().getGC() == LangOptions::GCOnly)
  1565. return;
  1566. EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
  1567. }
  1568. /// Adjust the declaration of something from the blocks API.
  1569. static void configureBlocksRuntimeObject(CodeGenModule &CGM,
  1570. llvm::Constant *C) {
  1571. if (!CGM.getLangOptions().BlocksRuntimeOptional) return;
  1572. llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
  1573. if (GV->isDeclaration() &&
  1574. GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
  1575. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1576. }
  1577. llvm::Constant *CodeGenModule::getBlockObjectDispose() {
  1578. if (BlockObjectDispose)
  1579. return BlockObjectDispose;
  1580. llvm::Type *args[] = { Int8PtrTy, Int32Ty };
  1581. llvm::FunctionType *fty
  1582. = llvm::FunctionType::get(VoidTy, args, false);
  1583. BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
  1584. configureBlocksRuntimeObject(*this, BlockObjectDispose);
  1585. return BlockObjectDispose;
  1586. }
  1587. llvm::Constant *CodeGenModule::getBlockObjectAssign() {
  1588. if (BlockObjectAssign)
  1589. return BlockObjectAssign;
  1590. llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
  1591. llvm::FunctionType *fty
  1592. = llvm::FunctionType::get(VoidTy, args, false);
  1593. BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
  1594. configureBlocksRuntimeObject(*this, BlockObjectAssign);
  1595. return BlockObjectAssign;
  1596. }
  1597. llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
  1598. if (NSConcreteGlobalBlock)
  1599. return NSConcreteGlobalBlock;
  1600. NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
  1601. Int8PtrTy->getPointerTo(), 0);
  1602. configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
  1603. return NSConcreteGlobalBlock;
  1604. }
  1605. llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
  1606. if (NSConcreteStackBlock)
  1607. return NSConcreteStackBlock;
  1608. NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
  1609. Int8PtrTy->getPointerTo(), 0);
  1610. configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
  1611. return NSConcreteStackBlock;
  1612. }