CGBlocks.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339
  1. //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit blocks.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGBlocks.h"
  14. #include "CGDebugInfo.h"
  15. #include "CGObjCRuntime.h"
  16. #include "CodeGenFunction.h"
  17. #include "CodeGenModule.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "llvm/ADT/SmallSet.h"
  20. #include "llvm/IR/CallSite.h"
  21. #include "llvm/IR/DataLayout.h"
  22. #include "llvm/IR/Module.h"
  23. #include <algorithm>
  24. #include <cstdio>
  25. using namespace clang;
  26. using namespace CodeGen;
  27. CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
  28. : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
  29. HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
  30. LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
  31. DominatingIP(nullptr) {
  32. // Skip asm prefix, if any. 'name' is usually taken directly from
  33. // the mangled name of the enclosing function.
  34. if (!name.empty() && name[0] == '\01')
  35. name = name.substr(1);
  36. }
  37. // Anchor the vtable to this translation unit.
  38. BlockByrefHelpers::~BlockByrefHelpers() {}
  39. /// Build the given block as a global block.
  40. static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
  41. const CGBlockInfo &blockInfo,
  42. llvm::Constant *blockFn);
  43. /// Build the helper function to copy a block.
  44. static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
  45. const CGBlockInfo &blockInfo) {
  46. return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
  47. }
  48. /// Build the helper function to dispose of a block.
  49. static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
  50. const CGBlockInfo &blockInfo) {
  51. return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
  52. }
  53. /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
  54. /// buildBlockDescriptor is accessed from 5th field of the Block_literal
  55. /// meta-data and contains stationary information about the block literal.
  56. /// Its definition will have 4 (or optinally 6) words.
  57. /// \code
  58. /// struct Block_descriptor {
  59. /// unsigned long reserved;
  60. /// unsigned long size; // size of Block_literal metadata in bytes.
  61. /// void *copy_func_helper_decl; // optional copy helper.
  62. /// void *destroy_func_decl; // optioanl destructor helper.
  63. /// void *block_method_encoding_address; // @encode for block literal signature.
  64. /// void *block_layout_info; // encoding of captured block variables.
  65. /// };
  66. /// \endcode
  67. static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
  68. const CGBlockInfo &blockInfo) {
  69. ASTContext &C = CGM.getContext();
  70. llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
  71. llvm::Type *i8p = nullptr;
  72. if (CGM.getLangOpts().OpenCL)
  73. i8p =
  74. llvm::Type::getInt8PtrTy(
  75. CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
  76. else
  77. i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
  78. SmallVector<llvm::Constant*, 6> elements;
  79. // reserved
  80. elements.push_back(llvm::ConstantInt::get(ulong, 0));
  81. // Size
  82. // FIXME: What is the right way to say this doesn't fit? We should give
  83. // a user diagnostic in that case. Better fix would be to change the
  84. // API to size_t.
  85. elements.push_back(llvm::ConstantInt::get(ulong,
  86. blockInfo.BlockSize.getQuantity()));
  87. // Optional copy/dispose helpers.
  88. if (blockInfo.NeedsCopyDispose) {
  89. // copy_func_helper_decl
  90. elements.push_back(buildCopyHelper(CGM, blockInfo));
  91. // destroy_func_decl
  92. elements.push_back(buildDisposeHelper(CGM, blockInfo));
  93. }
  94. // Signature. Mandatory ObjC-style method descriptor @encode sequence.
  95. std::string typeAtEncoding =
  96. CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
  97. elements.push_back(llvm::ConstantExpr::getBitCast(
  98. CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
  99. // GC layout.
  100. if (C.getLangOpts().ObjC1) {
  101. if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
  102. elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
  103. else
  104. elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
  105. }
  106. else
  107. elements.push_back(llvm::Constant::getNullValue(i8p));
  108. llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
  109. llvm::GlobalVariable *global =
  110. new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
  111. llvm::GlobalValue::InternalLinkage,
  112. init, "__block_descriptor_tmp");
  113. return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
  114. }
  115. /*
  116. Purely notional variadic template describing the layout of a block.
  117. template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
  118. struct Block_literal {
  119. /// Initialized to one of:
  120. /// extern void *_NSConcreteStackBlock[];
  121. /// extern void *_NSConcreteGlobalBlock[];
  122. ///
  123. /// In theory, we could start one off malloc'ed by setting
  124. /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
  125. /// this isa:
  126. /// extern void *_NSConcreteMallocBlock[];
  127. struct objc_class *isa;
  128. /// These are the flags (with corresponding bit number) that the
  129. /// compiler is actually supposed to know about.
  130. /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
  131. /// descriptor provides copy and dispose helper functions
  132. /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
  133. /// object with a nontrivial destructor or copy constructor
  134. /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
  135. /// as global memory
  136. /// 29. BLOCK_USE_STRET - indicates that the block function
  137. /// uses stret, which objc_msgSend needs to know about
  138. /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
  139. /// @encoded signature string
  140. /// And we're not supposed to manipulate these:
  141. /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
  142. /// to malloc'ed memory
  143. /// 27. BLOCK_IS_GC - indicates that the block has been moved to
  144. /// to GC-allocated memory
  145. /// Additionally, the bottom 16 bits are a reference count which
  146. /// should be zero on the stack.
  147. int flags;
  148. /// Reserved; should be zero-initialized.
  149. int reserved;
  150. /// Function pointer generated from block literal.
  151. _ResultType (*invoke)(Block_literal *, _ParamTypes...);
  152. /// Block description metadata generated from block literal.
  153. struct Block_descriptor *block_descriptor;
  154. /// Captured values follow.
  155. _CapturesTypes captures...;
  156. };
  157. */
  158. /// The number of fields in a block header.
  159. const unsigned BlockHeaderSize = 5;
  160. namespace {
  161. /// A chunk of data that we actually have to capture in the block.
  162. struct BlockLayoutChunk {
  163. CharUnits Alignment;
  164. CharUnits Size;
  165. Qualifiers::ObjCLifetime Lifetime;
  166. const BlockDecl::Capture *Capture; // null for 'this'
  167. llvm::Type *Type;
  168. BlockLayoutChunk(CharUnits align, CharUnits size,
  169. Qualifiers::ObjCLifetime lifetime,
  170. const BlockDecl::Capture *capture,
  171. llvm::Type *type)
  172. : Alignment(align), Size(size), Lifetime(lifetime),
  173. Capture(capture), Type(type) {}
  174. /// Tell the block info that this chunk has the given field index.
  175. void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
  176. if (!Capture) {
  177. info.CXXThisIndex = index;
  178. info.CXXThisOffset = offset;
  179. } else {
  180. info.Captures.insert({Capture->getVariable(),
  181. CGBlockInfo::Capture::makeIndex(index, offset)});
  182. }
  183. }
  184. };
  185. /// Order by 1) all __strong together 2) next, all byfref together 3) next,
  186. /// all __weak together. Preserve descending alignment in all situations.
  187. bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
  188. if (left.Alignment != right.Alignment)
  189. return left.Alignment > right.Alignment;
  190. auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
  191. if (chunk.Capture && chunk.Capture->isByRef())
  192. return 1;
  193. if (chunk.Lifetime == Qualifiers::OCL_Strong)
  194. return 0;
  195. if (chunk.Lifetime == Qualifiers::OCL_Weak)
  196. return 2;
  197. return 3;
  198. };
  199. return getPrefOrder(left) < getPrefOrder(right);
  200. }
  201. } // end anonymous namespace
  202. /// Determines if the given type is safe for constant capture in C++.
  203. static bool isSafeForCXXConstantCapture(QualType type) {
  204. const RecordType *recordType =
  205. type->getBaseElementTypeUnsafe()->getAs<RecordType>();
  206. // Only records can be unsafe.
  207. if (!recordType) return true;
  208. const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
  209. // Maintain semantics for classes with non-trivial dtors or copy ctors.
  210. if (!record->hasTrivialDestructor()) return false;
  211. if (record->hasNonTrivialCopyConstructor()) return false;
  212. // Otherwise, we just have to make sure there aren't any mutable
  213. // fields that might have changed since initialization.
  214. return !record->hasMutableFields();
  215. }
  216. /// It is illegal to modify a const object after initialization.
  217. /// Therefore, if a const object has a constant initializer, we don't
  218. /// actually need to keep storage for it in the block; we'll just
  219. /// rematerialize it at the start of the block function. This is
  220. /// acceptable because we make no promises about address stability of
  221. /// captured variables.
  222. static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
  223. CodeGenFunction *CGF,
  224. const VarDecl *var) {
  225. QualType type = var->getType();
  226. // We can only do this if the variable is const.
  227. if (!type.isConstQualified()) return nullptr;
  228. // Furthermore, in C++ we have to worry about mutable fields:
  229. // C++ [dcl.type.cv]p4:
  230. // Except that any class member declared mutable can be
  231. // modified, any attempt to modify a const object during its
  232. // lifetime results in undefined behavior.
  233. if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
  234. return nullptr;
  235. // If the variable doesn't have any initializer (shouldn't this be
  236. // invalid?), it's not clear what we should do. Maybe capture as
  237. // zero?
  238. const Expr *init = var->getInit();
  239. if (!init) return nullptr;
  240. return CGM.EmitConstantInit(*var, CGF);
  241. }
  242. /// Get the low bit of a nonzero character count. This is the
  243. /// alignment of the nth byte if the 0th byte is universally aligned.
  244. static CharUnits getLowBit(CharUnits v) {
  245. return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
  246. }
  247. static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
  248. SmallVectorImpl<llvm::Type*> &elementTypes) {
  249. // The header is basically 'struct { void *; int; int; void *; void *; }'.
  250. // Assert that that struct is packed.
  251. assert(CGM.getIntSize() <= CGM.getPointerSize());
  252. assert(CGM.getIntAlign() <= CGM.getPointerAlign());
  253. assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
  254. info.BlockAlign = CGM.getPointerAlign();
  255. info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
  256. assert(elementTypes.empty());
  257. elementTypes.push_back(CGM.VoidPtrTy);
  258. elementTypes.push_back(CGM.IntTy);
  259. elementTypes.push_back(CGM.IntTy);
  260. elementTypes.push_back(CGM.VoidPtrTy);
  261. elementTypes.push_back(CGM.getBlockDescriptorType());
  262. assert(elementTypes.size() == BlockHeaderSize);
  263. }
  264. /// Compute the layout of the given block. Attempts to lay the block
  265. /// out with minimal space requirements.
  266. static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
  267. CGBlockInfo &info) {
  268. ASTContext &C = CGM.getContext();
  269. const BlockDecl *block = info.getBlockDecl();
  270. SmallVector<llvm::Type*, 8> elementTypes;
  271. initializeForBlockHeader(CGM, info, elementTypes);
  272. if (!block->hasCaptures()) {
  273. info.StructureType =
  274. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  275. info.CanBeGlobal = true;
  276. return;
  277. }
  278. else if (C.getLangOpts().ObjC1 &&
  279. CGM.getLangOpts().getGC() == LangOptions::NonGC)
  280. info.HasCapturedVariableLayout = true;
  281. // Collect the layout chunks.
  282. SmallVector<BlockLayoutChunk, 16> layout;
  283. layout.reserve(block->capturesCXXThis() +
  284. (block->capture_end() - block->capture_begin()));
  285. CharUnits maxFieldAlign;
  286. // First, 'this'.
  287. if (block->capturesCXXThis()) {
  288. assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
  289. "Can't capture 'this' outside a method");
  290. QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
  291. // Theoretically, this could be in a different address space, so
  292. // don't assume standard pointer size/align.
  293. llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
  294. std::pair<CharUnits,CharUnits> tinfo
  295. = CGM.getContext().getTypeInfoInChars(thisType);
  296. maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
  297. layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
  298. Qualifiers::OCL_None,
  299. nullptr, llvmType));
  300. }
  301. // Next, all the block captures.
  302. for (const auto &CI : block->captures()) {
  303. const VarDecl *variable = CI.getVariable();
  304. if (CI.isByRef()) {
  305. // We have to copy/dispose of the __block reference.
  306. info.NeedsCopyDispose = true;
  307. // Just use void* instead of a pointer to the byref type.
  308. CharUnits align = CGM.getPointerAlign();
  309. maxFieldAlign = std::max(maxFieldAlign, align);
  310. layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
  311. Qualifiers::OCL_None, &CI,
  312. CGM.VoidPtrTy));
  313. continue;
  314. }
  315. // Otherwise, build a layout chunk with the size and alignment of
  316. // the declaration.
  317. if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
  318. info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
  319. continue;
  320. }
  321. // If we have a lifetime qualifier, honor it for capture purposes.
  322. // That includes *not* copying it if it's __unsafe_unretained.
  323. Qualifiers::ObjCLifetime lifetime =
  324. variable->getType().getObjCLifetime();
  325. if (lifetime) {
  326. switch (lifetime) {
  327. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  328. case Qualifiers::OCL_ExplicitNone:
  329. case Qualifiers::OCL_Autoreleasing:
  330. break;
  331. case Qualifiers::OCL_Strong:
  332. case Qualifiers::OCL_Weak:
  333. info.NeedsCopyDispose = true;
  334. }
  335. // Block pointers require copy/dispose. So do Objective-C pointers.
  336. } else if (variable->getType()->isObjCRetainableType()) {
  337. // But honor the inert __unsafe_unretained qualifier, which doesn't
  338. // actually make it into the type system.
  339. if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
  340. lifetime = Qualifiers::OCL_ExplicitNone;
  341. } else {
  342. info.NeedsCopyDispose = true;
  343. // used for mrr below.
  344. lifetime = Qualifiers::OCL_Strong;
  345. }
  346. // So do types that require non-trivial copy construction.
  347. } else if (CI.hasCopyExpr()) {
  348. info.NeedsCopyDispose = true;
  349. info.HasCXXObject = true;
  350. // And so do types with destructors.
  351. } else if (CGM.getLangOpts().CPlusPlus) {
  352. if (const CXXRecordDecl *record =
  353. variable->getType()->getAsCXXRecordDecl()) {
  354. if (!record->hasTrivialDestructor()) {
  355. info.HasCXXObject = true;
  356. info.NeedsCopyDispose = true;
  357. }
  358. }
  359. }
  360. QualType VT = variable->getType();
  361. CharUnits size = C.getTypeSizeInChars(VT);
  362. CharUnits align = C.getDeclAlign(variable);
  363. maxFieldAlign = std::max(maxFieldAlign, align);
  364. llvm::Type *llvmType =
  365. CGM.getTypes().ConvertTypeForMem(VT);
  366. layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
  367. }
  368. // If that was everything, we're done here.
  369. if (layout.empty()) {
  370. info.StructureType =
  371. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  372. info.CanBeGlobal = true;
  373. return;
  374. }
  375. // Sort the layout by alignment. We have to use a stable sort here
  376. // to get reproducible results. There should probably be an
  377. // llvm::array_pod_stable_sort.
  378. std::stable_sort(layout.begin(), layout.end());
  379. // Needed for blocks layout info.
  380. info.BlockHeaderForcedGapOffset = info.BlockSize;
  381. info.BlockHeaderForcedGapSize = CharUnits::Zero();
  382. CharUnits &blockSize = info.BlockSize;
  383. info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
  384. // Assuming that the first byte in the header is maximally aligned,
  385. // get the alignment of the first byte following the header.
  386. CharUnits endAlign = getLowBit(blockSize);
  387. // If the end of the header isn't satisfactorily aligned for the
  388. // maximum thing, look for things that are okay with the header-end
  389. // alignment, and keep appending them until we get something that's
  390. // aligned right. This algorithm is only guaranteed optimal if
  391. // that condition is satisfied at some point; otherwise we can get
  392. // things like:
  393. // header // next byte has alignment 4
  394. // something_with_size_5; // next byte has alignment 1
  395. // something_with_alignment_8;
  396. // which has 7 bytes of padding, as opposed to the naive solution
  397. // which might have less (?).
  398. if (endAlign < maxFieldAlign) {
  399. SmallVectorImpl<BlockLayoutChunk>::iterator
  400. li = layout.begin() + 1, le = layout.end();
  401. // Look for something that the header end is already
  402. // satisfactorily aligned for.
  403. for (; li != le && endAlign < li->Alignment; ++li)
  404. ;
  405. // If we found something that's naturally aligned for the end of
  406. // the header, keep adding things...
  407. if (li != le) {
  408. SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
  409. for (; li != le; ++li) {
  410. assert(endAlign >= li->Alignment);
  411. li->setIndex(info, elementTypes.size(), blockSize);
  412. elementTypes.push_back(li->Type);
  413. blockSize += li->Size;
  414. endAlign = getLowBit(blockSize);
  415. // ...until we get to the alignment of the maximum field.
  416. if (endAlign >= maxFieldAlign) {
  417. break;
  418. }
  419. }
  420. // Don't re-append everything we just appended.
  421. layout.erase(first, li);
  422. }
  423. }
  424. assert(endAlign == getLowBit(blockSize));
  425. // At this point, we just have to add padding if the end align still
  426. // isn't aligned right.
  427. if (endAlign < maxFieldAlign) {
  428. CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
  429. CharUnits padding = newBlockSize - blockSize;
  430. // If we haven't yet added any fields, remember that there was an
  431. // initial gap; this need to go into the block layout bit map.
  432. if (blockSize == info.BlockHeaderForcedGapOffset) {
  433. info.BlockHeaderForcedGapSize = padding;
  434. }
  435. elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
  436. padding.getQuantity()));
  437. blockSize = newBlockSize;
  438. endAlign = getLowBit(blockSize); // might be > maxFieldAlign
  439. }
  440. assert(endAlign >= maxFieldAlign);
  441. assert(endAlign == getLowBit(blockSize));
  442. // Slam everything else on now. This works because they have
  443. // strictly decreasing alignment and we expect that size is always a
  444. // multiple of alignment.
  445. for (SmallVectorImpl<BlockLayoutChunk>::iterator
  446. li = layout.begin(), le = layout.end(); li != le; ++li) {
  447. if (endAlign < li->Alignment) {
  448. // size may not be multiple of alignment. This can only happen with
  449. // an over-aligned variable. We will be adding a padding field to
  450. // make the size be multiple of alignment.
  451. CharUnits padding = li->Alignment - endAlign;
  452. elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
  453. padding.getQuantity()));
  454. blockSize += padding;
  455. endAlign = getLowBit(blockSize);
  456. }
  457. assert(endAlign >= li->Alignment);
  458. li->setIndex(info, elementTypes.size(), blockSize);
  459. elementTypes.push_back(li->Type);
  460. blockSize += li->Size;
  461. endAlign = getLowBit(blockSize);
  462. }
  463. info.StructureType =
  464. llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
  465. }
  466. /// Enter the scope of a block. This should be run at the entrance to
  467. /// a full-expression so that the block's cleanups are pushed at the
  468. /// right place in the stack.
  469. static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
  470. assert(CGF.HaveInsertPoint());
  471. // Allocate the block info and place it at the head of the list.
  472. CGBlockInfo &blockInfo =
  473. *new CGBlockInfo(block, CGF.CurFn->getName());
  474. blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
  475. CGF.FirstBlockInfo = &blockInfo;
  476. // Compute information about the layout, etc., of this block,
  477. // pushing cleanups as necessary.
  478. computeBlockInfo(CGF.CGM, &CGF, blockInfo);
  479. // Nothing else to do if it can be global.
  480. if (blockInfo.CanBeGlobal) return;
  481. // Make the allocation for the block.
  482. blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
  483. blockInfo.BlockAlign, "block");
  484. // If there are cleanups to emit, enter them (but inactive).
  485. if (!blockInfo.NeedsCopyDispose) return;
  486. // Walk through the captures (in order) and find the ones not
  487. // captured by constant.
  488. for (const auto &CI : block->captures()) {
  489. // Ignore __block captures; there's nothing special in the
  490. // on-stack block that we need to do for them.
  491. if (CI.isByRef()) continue;
  492. // Ignore variables that are constant-captured.
  493. const VarDecl *variable = CI.getVariable();
  494. CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  495. if (capture.isConstant()) continue;
  496. // Ignore objects that aren't destructed.
  497. QualType::DestructionKind dtorKind =
  498. variable->getType().isDestructedType();
  499. if (dtorKind == QualType::DK_none) continue;
  500. CodeGenFunction::Destroyer *destroyer;
  501. // Block captures count as local values and have imprecise semantics.
  502. // They also can't be arrays, so need to worry about that.
  503. if (dtorKind == QualType::DK_objc_strong_lifetime) {
  504. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  505. } else {
  506. destroyer = CGF.getDestroyer(dtorKind);
  507. }
  508. // GEP down to the address.
  509. Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
  510. capture.getIndex(),
  511. capture.getOffset());
  512. // We can use that GEP as the dominating IP.
  513. if (!blockInfo.DominatingIP)
  514. blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
  515. CleanupKind cleanupKind = InactiveNormalCleanup;
  516. bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
  517. if (useArrayEHCleanup)
  518. cleanupKind = InactiveNormalAndEHCleanup;
  519. CGF.pushDestroy(cleanupKind, addr, variable->getType(),
  520. destroyer, useArrayEHCleanup);
  521. // Remember where that cleanup was.
  522. capture.setCleanup(CGF.EHStack.stable_begin());
  523. }
  524. }
  525. /// Enter a full-expression with a non-trivial number of objects to
  526. /// clean up. This is in this file because, at the moment, the only
  527. /// kind of cleanup object is a BlockDecl*.
  528. void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
  529. assert(E->getNumObjects() != 0);
  530. ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
  531. for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
  532. i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
  533. enterBlockScope(*this, *i);
  534. }
  535. }
  536. /// Find the layout for the given block in a linked list and remove it.
  537. static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
  538. const BlockDecl *block) {
  539. while (true) {
  540. assert(head && *head);
  541. CGBlockInfo *cur = *head;
  542. // If this is the block we're looking for, splice it out of the list.
  543. if (cur->getBlockDecl() == block) {
  544. *head = cur->NextBlockInfo;
  545. return cur;
  546. }
  547. head = &cur->NextBlockInfo;
  548. }
  549. }
  550. /// Destroy a chain of block layouts.
  551. void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
  552. assert(head && "destroying an empty chain");
  553. do {
  554. CGBlockInfo *cur = head;
  555. head = cur->NextBlockInfo;
  556. delete cur;
  557. } while (head != nullptr);
  558. }
  559. /// Emit a block literal expression in the current function.
  560. llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
  561. // If the block has no captures, we won't have a pre-computed
  562. // layout for it.
  563. if (!blockExpr->getBlockDecl()->hasCaptures()) {
  564. CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
  565. computeBlockInfo(CGM, this, blockInfo);
  566. blockInfo.BlockExpression = blockExpr;
  567. return EmitBlockLiteral(blockInfo);
  568. }
  569. // Find the block info for this block and take ownership of it.
  570. std::unique_ptr<CGBlockInfo> blockInfo;
  571. blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
  572. blockExpr->getBlockDecl()));
  573. blockInfo->BlockExpression = blockExpr;
  574. return EmitBlockLiteral(*blockInfo);
  575. }
  576. llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
  577. // Using the computed layout, generate the actual block function.
  578. bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
  579. llvm::Constant *blockFn
  580. = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
  581. LocalDeclMap,
  582. isLambdaConv);
  583. blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
  584. // If there is nothing to capture, we can emit this as a global block.
  585. if (blockInfo.CanBeGlobal)
  586. return buildGlobalBlock(CGM, blockInfo, blockFn);
  587. // Otherwise, we have to emit this as a local block.
  588. llvm::Constant *isa = CGM.getNSConcreteStackBlock();
  589. isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
  590. // Build the block descriptor.
  591. llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
  592. Address blockAddr = blockInfo.LocalAddress;
  593. assert(blockAddr.isValid() && "block has no address!");
  594. // Compute the initial on-stack block flags.
  595. BlockFlags flags = BLOCK_HAS_SIGNATURE;
  596. if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
  597. if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
  598. if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
  599. if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
  600. auto projectField =
  601. [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
  602. return Builder.CreateStructGEP(blockAddr, index, offset, name);
  603. };
  604. auto storeField =
  605. [&](llvm::Value *value, unsigned index, CharUnits offset,
  606. const Twine &name) {
  607. Builder.CreateStore(value, projectField(index, offset, name));
  608. };
  609. // Initialize the block header.
  610. {
  611. // We assume all the header fields are densely packed.
  612. unsigned index = 0;
  613. CharUnits offset;
  614. auto addHeaderField =
  615. [&](llvm::Value *value, CharUnits size, const Twine &name) {
  616. storeField(value, index, offset, name);
  617. offset += size;
  618. index++;
  619. };
  620. addHeaderField(isa, getPointerSize(), "block.isa");
  621. addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
  622. getIntSize(), "block.flags");
  623. addHeaderField(llvm::ConstantInt::get(IntTy, 0),
  624. getIntSize(), "block.reserved");
  625. addHeaderField(blockFn, getPointerSize(), "block.invoke");
  626. addHeaderField(descriptor, getPointerSize(), "block.descriptor");
  627. }
  628. // Finally, capture all the values into the block.
  629. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  630. // First, 'this'.
  631. if (blockDecl->capturesCXXThis()) {
  632. Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
  633. "block.captured-this.addr");
  634. Builder.CreateStore(LoadCXXThis(), addr);
  635. }
  636. // Next, captured variables.
  637. for (const auto &CI : blockDecl->captures()) {
  638. const VarDecl *variable = CI.getVariable();
  639. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  640. // Ignore constant captures.
  641. if (capture.isConstant()) continue;
  642. QualType type = variable->getType();
  643. // This will be a [[type]]*, except that a byref entry will just be
  644. // an i8**.
  645. Address blockField =
  646. projectField(capture.getIndex(), capture.getOffset(), "block.captured");
  647. // Compute the address of the thing we're going to move into the
  648. // block literal.
  649. Address src = Address::invalid();
  650. if (BlockInfo && CI.isNested()) {
  651. // We need to use the capture from the enclosing block.
  652. const CGBlockInfo::Capture &enclosingCapture =
  653. BlockInfo->getCapture(variable);
  654. // This is a [[type]]*, except that a byref entry wil just be an i8**.
  655. src = Builder.CreateStructGEP(LoadBlockStruct(),
  656. enclosingCapture.getIndex(),
  657. enclosingCapture.getOffset(),
  658. "block.capture.addr");
  659. } else if (blockDecl->isConversionFromLambda()) {
  660. // The lambda capture in a lambda's conversion-to-block-pointer is
  661. // special; we'll simply emit it directly.
  662. src = Address::invalid();
  663. } else {
  664. // Just look it up in the locals map, which will give us back a
  665. // [[type]]*. If that doesn't work, do the more elaborate DRE
  666. // emission.
  667. auto it = LocalDeclMap.find(variable);
  668. if (it != LocalDeclMap.end()) {
  669. src = it->second;
  670. } else {
  671. DeclRefExpr declRef(
  672. const_cast<VarDecl *>(variable),
  673. /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), type,
  674. VK_LValue, SourceLocation());
  675. src = EmitDeclRefLValue(&declRef).getAddress();
  676. }
  677. }
  678. // For byrefs, we just write the pointer to the byref struct into
  679. // the block field. There's no need to chase the forwarding
  680. // pointer at this point, since we're building something that will
  681. // live a shorter life than the stack byref anyway.
  682. if (CI.isByRef()) {
  683. // Get a void* that points to the byref struct.
  684. llvm::Value *byrefPointer;
  685. if (CI.isNested())
  686. byrefPointer = Builder.CreateLoad(src, "byref.capture");
  687. else
  688. byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
  689. // Write that void* into the capture field.
  690. Builder.CreateStore(byrefPointer, blockField);
  691. // If we have a copy constructor, evaluate that into the block field.
  692. } else if (const Expr *copyExpr = CI.getCopyExpr()) {
  693. if (blockDecl->isConversionFromLambda()) {
  694. // If we have a lambda conversion, emit the expression
  695. // directly into the block instead.
  696. AggValueSlot Slot =
  697. AggValueSlot::forAddr(blockField, Qualifiers(),
  698. AggValueSlot::IsDestructed,
  699. AggValueSlot::DoesNotNeedGCBarriers,
  700. AggValueSlot::IsNotAliased);
  701. EmitAggExpr(copyExpr, Slot);
  702. } else {
  703. EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
  704. }
  705. // If it's a reference variable, copy the reference into the block field.
  706. } else if (type->isReferenceType()) {
  707. llvm::Value *ref = Builder.CreateLoad(src, "ref.val");
  708. Builder.CreateStore(ref, blockField);
  709. // If this is an ARC __strong block-pointer variable, don't do a
  710. // block copy.
  711. //
  712. // TODO: this can be generalized into the normal initialization logic:
  713. // we should never need to do a block-copy when initializing a local
  714. // variable, because the local variable's lifetime should be strictly
  715. // contained within the stack block's.
  716. } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
  717. type->isBlockPointerType()) {
  718. // Load the block and do a simple retain.
  719. llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
  720. value = EmitARCRetainNonBlock(value);
  721. // Do a primitive store to the block field.
  722. Builder.CreateStore(value, blockField);
  723. // Otherwise, fake up a POD copy into the block field.
  724. } else {
  725. // Fake up a new variable so that EmitScalarInit doesn't think
  726. // we're referring to the variable in its own initializer.
  727. ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
  728. SourceLocation(), /*name*/ nullptr,
  729. type);
  730. // We use one of these or the other depending on whether the
  731. // reference is nested.
  732. DeclRefExpr declRef(const_cast<VarDecl *>(variable),
  733. /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
  734. type, VK_LValue, SourceLocation());
  735. ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
  736. &declRef, VK_RValue);
  737. // FIXME: Pass a specific location for the expr init so that the store is
  738. // attributed to a reasonable location - otherwise it may be attributed to
  739. // locations of subexpressions in the initialization.
  740. EmitExprAsInit(&l2r, &blockFieldPseudoVar,
  741. MakeAddrLValue(blockField, type, AlignmentSource::Decl),
  742. /*captured by init*/ false);
  743. }
  744. // Activate the cleanup if layout pushed one.
  745. if (!CI.isByRef()) {
  746. EHScopeStack::stable_iterator cleanup = capture.getCleanup();
  747. if (cleanup.isValid())
  748. ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
  749. }
  750. }
  751. // Cast to the converted block-pointer type, which happens (somewhat
  752. // unfortunately) to be a pointer to function type.
  753. llvm::Value *result =
  754. Builder.CreateBitCast(blockAddr.getPointer(),
  755. ConvertType(blockInfo.getBlockExpr()->getType()));
  756. return result;
  757. }
  758. llvm::Type *CodeGenModule::getBlockDescriptorType() {
  759. if (BlockDescriptorType)
  760. return BlockDescriptorType;
  761. llvm::Type *UnsignedLongTy =
  762. getTypes().ConvertType(getContext().UnsignedLongTy);
  763. // struct __block_descriptor {
  764. // unsigned long reserved;
  765. // unsigned long block_size;
  766. //
  767. // // later, the following will be added
  768. //
  769. // struct {
  770. // void (*copyHelper)();
  771. // void (*copyHelper)();
  772. // } helpers; // !!! optional
  773. //
  774. // const char *signature; // the block signature
  775. // const char *layout; // reserved
  776. // };
  777. BlockDescriptorType =
  778. llvm::StructType::create("struct.__block_descriptor",
  779. UnsignedLongTy, UnsignedLongTy, nullptr);
  780. // Now form a pointer to that.
  781. BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
  782. return BlockDescriptorType;
  783. }
  784. llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
  785. if (GenericBlockLiteralType)
  786. return GenericBlockLiteralType;
  787. llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
  788. // struct __block_literal_generic {
  789. // void *__isa;
  790. // int __flags;
  791. // int __reserved;
  792. // void (*__invoke)(void *);
  793. // struct __block_descriptor *__descriptor;
  794. // };
  795. GenericBlockLiteralType =
  796. llvm::StructType::create("struct.__block_literal_generic",
  797. VoidPtrTy, IntTy, IntTy, VoidPtrTy,
  798. BlockDescPtrTy, nullptr);
  799. return GenericBlockLiteralType;
  800. }
  801. RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
  802. ReturnValueSlot ReturnValue) {
  803. const BlockPointerType *BPT =
  804. E->getCallee()->getType()->getAs<BlockPointerType>();
  805. llvm::Value *Callee = EmitScalarExpr(E->getCallee());
  806. // Get a pointer to the generic block literal.
  807. llvm::Type *BlockLiteralTy =
  808. llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
  809. // Bitcast the callee to a block literal.
  810. llvm::Value *BlockLiteral =
  811. Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
  812. // Get the function pointer from the literal.
  813. llvm::Value *FuncPtr =
  814. Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
  815. BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
  816. // Add the block literal.
  817. CallArgList Args;
  818. Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
  819. QualType FnType = BPT->getPointeeType();
  820. // And the rest of the arguments.
  821. EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
  822. // Load the function.
  823. llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
  824. const FunctionType *FuncTy = FnType->castAs<FunctionType>();
  825. const CGFunctionInfo &FnInfo =
  826. CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
  827. // Cast the function pointer to the right type.
  828. llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
  829. llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
  830. Func = Builder.CreateBitCast(Func, BlockFTyPtr);
  831. // And call the block.
  832. return EmitCall(FnInfo, Func, ReturnValue, Args);
  833. }
  834. Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
  835. bool isByRef) {
  836. assert(BlockInfo && "evaluating block ref without block information?");
  837. const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
  838. // Handle constant captures.
  839. if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
  840. Address addr =
  841. Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
  842. capture.getOffset(), "block.capture.addr");
  843. if (isByRef) {
  844. // addr should be a void** right now. Load, then cast the result
  845. // to byref*.
  846. auto &byrefInfo = getBlockByrefInfo(variable);
  847. addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
  848. auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
  849. addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
  850. addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
  851. variable->getName());
  852. }
  853. if (auto refType = variable->getType()->getAs<ReferenceType>()) {
  854. addr = EmitLoadOfReference(addr, refType);
  855. }
  856. return addr;
  857. }
  858. llvm::Constant *
  859. CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
  860. const char *name) {
  861. CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
  862. blockInfo.BlockExpression = blockExpr;
  863. // Compute information about the layout, etc., of this block.
  864. computeBlockInfo(*this, nullptr, blockInfo);
  865. // Using that metadata, generate the actual block function.
  866. llvm::Constant *blockFn;
  867. {
  868. CodeGenFunction::DeclMapTy LocalDeclMap;
  869. blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
  870. blockInfo,
  871. LocalDeclMap,
  872. false);
  873. }
  874. blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
  875. return buildGlobalBlock(*this, blockInfo, blockFn);
  876. }
  877. static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
  878. const CGBlockInfo &blockInfo,
  879. llvm::Constant *blockFn) {
  880. assert(blockInfo.CanBeGlobal);
  881. // Generate the constants for the block literal initializer.
  882. llvm::Constant *fields[BlockHeaderSize];
  883. // isa
  884. fields[0] = CGM.getNSConcreteGlobalBlock();
  885. // __flags
  886. BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
  887. if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
  888. fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
  889. // Reserved
  890. fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
  891. // Function
  892. fields[3] = blockFn;
  893. // Descriptor
  894. fields[4] = buildBlockDescriptor(CGM, blockInfo);
  895. llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
  896. llvm::GlobalVariable *literal =
  897. new llvm::GlobalVariable(CGM.getModule(),
  898. init->getType(),
  899. /*constant*/ true,
  900. llvm::GlobalVariable::InternalLinkage,
  901. init,
  902. "__block_literal_global");
  903. literal->setAlignment(blockInfo.BlockAlign.getQuantity());
  904. // Return a constant of the appropriately-casted type.
  905. llvm::Type *requiredType =
  906. CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
  907. return llvm::ConstantExpr::getBitCast(literal, requiredType);
  908. }
  909. void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
  910. unsigned argNum,
  911. llvm::Value *arg) {
  912. assert(BlockInfo && "not emitting prologue of block invocation function?!");
  913. llvm::Value *localAddr = nullptr;
  914. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  915. // Allocate a stack slot to let the debug info survive the RA.
  916. Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
  917. Builder.CreateStore(arg, alloc);
  918. localAddr = Builder.CreateLoad(alloc);
  919. }
  920. if (CGDebugInfo *DI = getDebugInfo()) {
  921. if (CGM.getCodeGenOpts().getDebugInfo() >=
  922. codegenoptions::LimitedDebugInfo) {
  923. DI->setLocation(D->getLocation());
  924. DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
  925. localAddr, Builder);
  926. }
  927. }
  928. SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
  929. ApplyDebugLocation Scope(*this, StartLoc);
  930. // Instead of messing around with LocalDeclMap, just set the value
  931. // directly as BlockPointer.
  932. BlockPointer = Builder.CreateBitCast(arg,
  933. BlockInfo->StructureType->getPointerTo(),
  934. "block");
  935. }
  936. Address CodeGenFunction::LoadBlockStruct() {
  937. assert(BlockInfo && "not in a block invocation function!");
  938. assert(BlockPointer && "no block pointer set!");
  939. return Address(BlockPointer, BlockInfo->BlockAlign);
  940. }
  941. llvm::Function *
  942. CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
  943. const CGBlockInfo &blockInfo,
  944. const DeclMapTy &ldm,
  945. bool IsLambdaConversionToBlock) {
  946. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  947. CurGD = GD;
  948. CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
  949. BlockInfo = &blockInfo;
  950. // Arrange for local static and local extern declarations to appear
  951. // to be local to this function as well, in case they're directly
  952. // referenced in a block.
  953. for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
  954. const auto *var = dyn_cast<VarDecl>(i->first);
  955. if (var && !var->hasLocalStorage())
  956. setAddrOfLocalVar(var, i->second);
  957. }
  958. // Begin building the function declaration.
  959. // Build the argument list.
  960. FunctionArgList args;
  961. // The first argument is the block pointer. Just take it as a void*
  962. // and cast it later.
  963. QualType selfTy = getContext().VoidPtrTy;
  964. IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
  965. ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
  966. SourceLocation(), II, selfTy);
  967. args.push_back(&selfDecl);
  968. // Now add the rest of the parameters.
  969. args.append(blockDecl->param_begin(), blockDecl->param_end());
  970. // Create the function declaration.
  971. const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
  972. const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
  973. fnType->getReturnType(), args, fnType->getExtInfo(),
  974. fnType->isVariadic());
  975. if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
  976. blockInfo.UsesStret = true;
  977. llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
  978. StringRef name = CGM.getBlockMangledName(GD, blockDecl);
  979. llvm::Function *fn = llvm::Function::Create(
  980. fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
  981. CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
  982. // Begin generating the function.
  983. StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
  984. blockDecl->getLocation(),
  985. blockInfo.getBlockExpr()->getBody()->getLocStart());
  986. // Okay. Undo some of what StartFunction did.
  987. // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
  988. // won't delete the dbg.declare intrinsics for captured variables.
  989. llvm::Value *BlockPointerDbgLoc = BlockPointer;
  990. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  991. // Allocate a stack slot for it, so we can point the debugger to it
  992. Address Alloca = CreateTempAlloca(BlockPointer->getType(),
  993. getPointerAlign(),
  994. "block.addr");
  995. // Set the DebugLocation to empty, so the store is recognized as a
  996. // frame setup instruction by llvm::DwarfDebug::beginFunction().
  997. auto NL = ApplyDebugLocation::CreateEmpty(*this);
  998. Builder.CreateStore(BlockPointer, Alloca);
  999. BlockPointerDbgLoc = Alloca.getPointer();
  1000. }
  1001. // If we have a C++ 'this' reference, go ahead and force it into
  1002. // existence now.
  1003. if (blockDecl->capturesCXXThis()) {
  1004. Address addr =
  1005. Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
  1006. blockInfo.CXXThisOffset, "block.captured-this");
  1007. CXXThisValue = Builder.CreateLoad(addr, "this");
  1008. }
  1009. // Also force all the constant captures.
  1010. for (const auto &CI : blockDecl->captures()) {
  1011. const VarDecl *variable = CI.getVariable();
  1012. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1013. if (!capture.isConstant()) continue;
  1014. CharUnits align = getContext().getDeclAlign(variable);
  1015. Address alloca =
  1016. CreateMemTemp(variable->getType(), align, "block.captured-const");
  1017. Builder.CreateStore(capture.getConstant(), alloca);
  1018. setAddrOfLocalVar(variable, alloca);
  1019. }
  1020. // Save a spot to insert the debug information for all the DeclRefExprs.
  1021. llvm::BasicBlock *entry = Builder.GetInsertBlock();
  1022. llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
  1023. --entry_ptr;
  1024. if (IsLambdaConversionToBlock)
  1025. EmitLambdaBlockInvokeBody();
  1026. else {
  1027. PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
  1028. incrementProfileCounter(blockDecl->getBody());
  1029. EmitStmt(blockDecl->getBody());
  1030. }
  1031. // Remember where we were...
  1032. llvm::BasicBlock *resume = Builder.GetInsertBlock();
  1033. // Go back to the entry.
  1034. ++entry_ptr;
  1035. Builder.SetInsertPoint(entry, entry_ptr);
  1036. // Emit debug information for all the DeclRefExprs.
  1037. // FIXME: also for 'this'
  1038. if (CGDebugInfo *DI = getDebugInfo()) {
  1039. for (const auto &CI : blockDecl->captures()) {
  1040. const VarDecl *variable = CI.getVariable();
  1041. DI->EmitLocation(Builder, variable->getLocation());
  1042. if (CGM.getCodeGenOpts().getDebugInfo() >=
  1043. codegenoptions::LimitedDebugInfo) {
  1044. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1045. if (capture.isConstant()) {
  1046. auto addr = LocalDeclMap.find(variable)->second;
  1047. DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
  1048. Builder);
  1049. continue;
  1050. }
  1051. DI->EmitDeclareOfBlockDeclRefVariable(
  1052. variable, BlockPointerDbgLoc, Builder, blockInfo,
  1053. entry_ptr == entry->end() ? nullptr : &*entry_ptr);
  1054. }
  1055. }
  1056. // Recover location if it was changed in the above loop.
  1057. DI->EmitLocation(Builder,
  1058. cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
  1059. }
  1060. // And resume where we left off.
  1061. if (resume == nullptr)
  1062. Builder.ClearInsertionPoint();
  1063. else
  1064. Builder.SetInsertPoint(resume);
  1065. FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
  1066. return fn;
  1067. }
  1068. /*
  1069. notes.push_back(HelperInfo());
  1070. HelperInfo &note = notes.back();
  1071. note.index = capture.getIndex();
  1072. note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
  1073. note.cxxbar_import = ci->getCopyExpr();
  1074. if (ci->isByRef()) {
  1075. note.flag = BLOCK_FIELD_IS_BYREF;
  1076. if (type.isObjCGCWeak())
  1077. note.flag |= BLOCK_FIELD_IS_WEAK;
  1078. } else if (type->isBlockPointerType()) {
  1079. note.flag = BLOCK_FIELD_IS_BLOCK;
  1080. } else {
  1081. note.flag = BLOCK_FIELD_IS_OBJECT;
  1082. }
  1083. */
  1084. /// Generate the copy-helper function for a block closure object:
  1085. /// static void block_copy_helper(block_t *dst, block_t *src);
  1086. /// The runtime will have previously initialized 'dst' by doing a
  1087. /// bit-copy of 'src'.
  1088. ///
  1089. /// Note that this copies an entire block closure object to the heap;
  1090. /// it should not be confused with a 'byref copy helper', which moves
  1091. /// the contents of an individual __block variable to the heap.
  1092. llvm::Constant *
  1093. CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
  1094. ASTContext &C = getContext();
  1095. FunctionArgList args;
  1096. ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
  1097. C.VoidPtrTy);
  1098. args.push_back(&dstDecl);
  1099. ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
  1100. C.VoidPtrTy);
  1101. args.push_back(&srcDecl);
  1102. const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
  1103. C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
  1104. // FIXME: it would be nice if these were mergeable with things with
  1105. // identical semantics.
  1106. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  1107. llvm::Function *Fn =
  1108. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1109. "__copy_helper_block_", &CGM.getModule());
  1110. IdentifierInfo *II
  1111. = &CGM.getContext().Idents.get("__copy_helper_block_");
  1112. FunctionDecl *FD = FunctionDecl::Create(C,
  1113. C.getTranslationUnitDecl(),
  1114. SourceLocation(),
  1115. SourceLocation(), II, C.VoidTy,
  1116. nullptr, SC_Static,
  1117. false,
  1118. false);
  1119. CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
  1120. auto NL = ApplyDebugLocation::CreateEmpty(*this);
  1121. StartFunction(FD, C.VoidTy, Fn, FI, args);
  1122. // Create a scope with an artificial location for the body of this function.
  1123. auto AL = ApplyDebugLocation::CreateArtificial(*this);
  1124. llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
  1125. Address src = GetAddrOfLocalVar(&srcDecl);
  1126. src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
  1127. src = Builder.CreateBitCast(src, structPtrTy, "block.source");
  1128. Address dst = GetAddrOfLocalVar(&dstDecl);
  1129. dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
  1130. dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
  1131. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  1132. for (const auto &CI : blockDecl->captures()) {
  1133. const VarDecl *variable = CI.getVariable();
  1134. QualType type = variable->getType();
  1135. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1136. if (capture.isConstant()) continue;
  1137. const Expr *copyExpr = CI.getCopyExpr();
  1138. BlockFieldFlags flags;
  1139. bool useARCWeakCopy = false;
  1140. bool useARCStrongCopy = false;
  1141. if (copyExpr) {
  1142. assert(!CI.isByRef());
  1143. // don't bother computing flags
  1144. } else if (CI.isByRef()) {
  1145. flags = BLOCK_FIELD_IS_BYREF;
  1146. if (type.isObjCGCWeak())
  1147. flags |= BLOCK_FIELD_IS_WEAK;
  1148. } else if (type->isObjCRetainableType()) {
  1149. flags = BLOCK_FIELD_IS_OBJECT;
  1150. bool isBlockPointer = type->isBlockPointerType();
  1151. if (isBlockPointer)
  1152. flags = BLOCK_FIELD_IS_BLOCK;
  1153. // Special rules for ARC captures:
  1154. Qualifiers qs = type.getQualifiers();
  1155. // We need to register __weak direct captures with the runtime.
  1156. if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
  1157. useARCWeakCopy = true;
  1158. // We need to retain the copied value for __strong direct captures.
  1159. } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
  1160. // If it's a block pointer, we have to copy the block and
  1161. // assign that to the destination pointer, so we might as
  1162. // well use _Block_object_assign. Otherwise we can avoid that.
  1163. if (!isBlockPointer)
  1164. useARCStrongCopy = true;
  1165. // Non-ARC captures of retainable pointers are strong and
  1166. // therefore require a call to _Block_object_assign.
  1167. } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
  1168. // fall through
  1169. // Otherwise the memcpy is fine.
  1170. } else {
  1171. continue;
  1172. }
  1173. // For all other types, the memcpy is fine.
  1174. } else {
  1175. continue;
  1176. }
  1177. unsigned index = capture.getIndex();
  1178. Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
  1179. Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
  1180. // If there's an explicit copy expression, we do that.
  1181. if (copyExpr) {
  1182. EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
  1183. } else if (useARCWeakCopy) {
  1184. EmitARCCopyWeak(dstField, srcField);
  1185. } else {
  1186. llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
  1187. if (useARCStrongCopy) {
  1188. // At -O0, store null into the destination field (so that the
  1189. // storeStrong doesn't over-release) and then call storeStrong.
  1190. // This is a workaround to not having an initStrong call.
  1191. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1192. auto *ty = cast<llvm::PointerType>(srcValue->getType());
  1193. llvm::Value *null = llvm::ConstantPointerNull::get(ty);
  1194. Builder.CreateStore(null, dstField);
  1195. EmitARCStoreStrongCall(dstField, srcValue, true);
  1196. // With optimization enabled, take advantage of the fact that
  1197. // the blocks runtime guarantees a memcpy of the block data, and
  1198. // just emit a retain of the src field.
  1199. } else {
  1200. EmitARCRetainNonBlock(srcValue);
  1201. // We don't need this anymore, so kill it. It's not quite
  1202. // worth the annoyance to avoid creating it in the first place.
  1203. cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
  1204. }
  1205. } else {
  1206. srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
  1207. llvm::Value *dstAddr =
  1208. Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
  1209. llvm::Value *args[] = {
  1210. dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
  1211. };
  1212. bool copyCanThrow = false;
  1213. if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
  1214. const Expr *copyExpr =
  1215. CGM.getContext().getBlockVarCopyInits(variable);
  1216. if (copyExpr) {
  1217. copyCanThrow = true; // FIXME: reuse the noexcept logic
  1218. }
  1219. }
  1220. if (copyCanThrow) {
  1221. EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
  1222. } else {
  1223. EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
  1224. }
  1225. }
  1226. }
  1227. }
  1228. FinishFunction();
  1229. return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  1230. }
  1231. /// Generate the destroy-helper function for a block closure object:
  1232. /// static void block_destroy_helper(block_t *theBlock);
  1233. ///
  1234. /// Note that this destroys a heap-allocated block closure object;
  1235. /// it should not be confused with a 'byref destroy helper', which
  1236. /// destroys the heap-allocated contents of an individual __block
  1237. /// variable.
  1238. llvm::Constant *
  1239. CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
  1240. ASTContext &C = getContext();
  1241. FunctionArgList args;
  1242. ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
  1243. C.VoidPtrTy);
  1244. args.push_back(&srcDecl);
  1245. const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
  1246. C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
  1247. // FIXME: We'd like to put these into a mergable by content, with
  1248. // internal linkage.
  1249. llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
  1250. llvm::Function *Fn =
  1251. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1252. "__destroy_helper_block_", &CGM.getModule());
  1253. IdentifierInfo *II
  1254. = &CGM.getContext().Idents.get("__destroy_helper_block_");
  1255. FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
  1256. SourceLocation(),
  1257. SourceLocation(), II, C.VoidTy,
  1258. nullptr, SC_Static,
  1259. false, false);
  1260. CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
  1261. // Create a scope with an artificial location for the body of this function.
  1262. auto NL = ApplyDebugLocation::CreateEmpty(*this);
  1263. StartFunction(FD, C.VoidTy, Fn, FI, args);
  1264. auto AL = ApplyDebugLocation::CreateArtificial(*this);
  1265. llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
  1266. Address src = GetAddrOfLocalVar(&srcDecl);
  1267. src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
  1268. src = Builder.CreateBitCast(src, structPtrTy, "block");
  1269. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  1270. CodeGenFunction::RunCleanupsScope cleanups(*this);
  1271. for (const auto &CI : blockDecl->captures()) {
  1272. const VarDecl *variable = CI.getVariable();
  1273. QualType type = variable->getType();
  1274. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1275. if (capture.isConstant()) continue;
  1276. BlockFieldFlags flags;
  1277. const CXXDestructorDecl *dtor = nullptr;
  1278. bool useARCWeakDestroy = false;
  1279. bool useARCStrongDestroy = false;
  1280. if (CI.isByRef()) {
  1281. flags = BLOCK_FIELD_IS_BYREF;
  1282. if (type.isObjCGCWeak())
  1283. flags |= BLOCK_FIELD_IS_WEAK;
  1284. } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
  1285. if (record->hasTrivialDestructor())
  1286. continue;
  1287. dtor = record->getDestructor();
  1288. } else if (type->isObjCRetainableType()) {
  1289. flags = BLOCK_FIELD_IS_OBJECT;
  1290. if (type->isBlockPointerType())
  1291. flags = BLOCK_FIELD_IS_BLOCK;
  1292. // Special rules for ARC captures.
  1293. Qualifiers qs = type.getQualifiers();
  1294. // Use objc_storeStrong for __strong direct captures; the
  1295. // dynamic tools really like it when we do this.
  1296. if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
  1297. useARCStrongDestroy = true;
  1298. // Support __weak direct captures.
  1299. } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
  1300. useARCWeakDestroy = true;
  1301. // Non-ARC captures are strong, and we need to use _Block_object_dispose.
  1302. } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
  1303. // fall through
  1304. // Otherwise, we have nothing to do.
  1305. } else {
  1306. continue;
  1307. }
  1308. } else {
  1309. continue;
  1310. }
  1311. Address srcField =
  1312. Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
  1313. // If there's an explicit copy expression, we do that.
  1314. if (dtor) {
  1315. PushDestructorCleanup(dtor, srcField);
  1316. // If this is a __weak capture, emit the release directly.
  1317. } else if (useARCWeakDestroy) {
  1318. EmitARCDestroyWeak(srcField);
  1319. // Destroy strong objects with a call if requested.
  1320. } else if (useARCStrongDestroy) {
  1321. EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
  1322. // Otherwise we call _Block_object_dispose. It wouldn't be too
  1323. // hard to just emit this as a cleanup if we wanted to make sure
  1324. // that things were done in reverse.
  1325. } else {
  1326. llvm::Value *value = Builder.CreateLoad(srcField);
  1327. value = Builder.CreateBitCast(value, VoidPtrTy);
  1328. BuildBlockRelease(value, flags);
  1329. }
  1330. }
  1331. cleanups.ForceCleanup();
  1332. FinishFunction();
  1333. return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
  1334. }
  1335. namespace {
  1336. /// Emits the copy/dispose helper functions for a __block object of id type.
  1337. class ObjectByrefHelpers final : public BlockByrefHelpers {
  1338. BlockFieldFlags Flags;
  1339. public:
  1340. ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
  1341. : BlockByrefHelpers(alignment), Flags(flags) {}
  1342. void emitCopy(CodeGenFunction &CGF, Address destField,
  1343. Address srcField) override {
  1344. destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
  1345. srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
  1346. llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
  1347. unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
  1348. llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
  1349. llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
  1350. llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
  1351. CGF.EmitNounwindRuntimeCall(fn, args);
  1352. }
  1353. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1354. field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
  1355. llvm::Value *value = CGF.Builder.CreateLoad(field);
  1356. CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
  1357. }
  1358. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1359. id.AddInteger(Flags.getBitMask());
  1360. }
  1361. };
  1362. /// Emits the copy/dispose helpers for an ARC __block __weak variable.
  1363. class ARCWeakByrefHelpers final : public BlockByrefHelpers {
  1364. public:
  1365. ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
  1366. void emitCopy(CodeGenFunction &CGF, Address destField,
  1367. Address srcField) override {
  1368. CGF.EmitARCMoveWeak(destField, srcField);
  1369. }
  1370. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1371. CGF.EmitARCDestroyWeak(field);
  1372. }
  1373. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1374. // 0 is distinguishable from all pointers and byref flags
  1375. id.AddInteger(0);
  1376. }
  1377. };
  1378. /// Emits the copy/dispose helpers for an ARC __block __strong variable
  1379. /// that's not of block-pointer type.
  1380. class ARCStrongByrefHelpers final : public BlockByrefHelpers {
  1381. public:
  1382. ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
  1383. void emitCopy(CodeGenFunction &CGF, Address destField,
  1384. Address srcField) override {
  1385. // Do a "move" by copying the value and then zeroing out the old
  1386. // variable.
  1387. llvm::Value *value = CGF.Builder.CreateLoad(srcField);
  1388. llvm::Value *null =
  1389. llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
  1390. if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1391. CGF.Builder.CreateStore(null, destField);
  1392. CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
  1393. CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
  1394. return;
  1395. }
  1396. CGF.Builder.CreateStore(value, destField);
  1397. CGF.Builder.CreateStore(null, srcField);
  1398. }
  1399. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1400. CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
  1401. }
  1402. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1403. // 1 is distinguishable from all pointers and byref flags
  1404. id.AddInteger(1);
  1405. }
  1406. };
  1407. /// Emits the copy/dispose helpers for an ARC __block __strong
  1408. /// variable that's of block-pointer type.
  1409. class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
  1410. public:
  1411. ARCStrongBlockByrefHelpers(CharUnits alignment)
  1412. : BlockByrefHelpers(alignment) {}
  1413. void emitCopy(CodeGenFunction &CGF, Address destField,
  1414. Address srcField) override {
  1415. // Do the copy with objc_retainBlock; that's all that
  1416. // _Block_object_assign would do anyway, and we'd have to pass the
  1417. // right arguments to make sure it doesn't get no-op'ed.
  1418. llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
  1419. llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
  1420. CGF.Builder.CreateStore(copy, destField);
  1421. }
  1422. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1423. CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
  1424. }
  1425. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1426. // 2 is distinguishable from all pointers and byref flags
  1427. id.AddInteger(2);
  1428. }
  1429. };
  1430. /// Emits the copy/dispose helpers for a __block variable with a
  1431. /// nontrivial copy constructor or destructor.
  1432. class CXXByrefHelpers final : public BlockByrefHelpers {
  1433. QualType VarType;
  1434. const Expr *CopyExpr;
  1435. public:
  1436. CXXByrefHelpers(CharUnits alignment, QualType type,
  1437. const Expr *copyExpr)
  1438. : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
  1439. bool needsCopy() const override { return CopyExpr != nullptr; }
  1440. void emitCopy(CodeGenFunction &CGF, Address destField,
  1441. Address srcField) override {
  1442. if (!CopyExpr) return;
  1443. CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
  1444. }
  1445. void emitDispose(CodeGenFunction &CGF, Address field) override {
  1446. EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
  1447. CGF.PushDestructorCleanup(VarType, field);
  1448. CGF.PopCleanupBlocks(cleanupDepth);
  1449. }
  1450. void profileImpl(llvm::FoldingSetNodeID &id) const override {
  1451. id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
  1452. }
  1453. };
  1454. } // end anonymous namespace
  1455. static llvm::Constant *
  1456. generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
  1457. BlockByrefHelpers &generator) {
  1458. ASTContext &Context = CGF.getContext();
  1459. QualType R = Context.VoidTy;
  1460. FunctionArgList args;
  1461. ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
  1462. Context.VoidPtrTy);
  1463. args.push_back(&dst);
  1464. ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
  1465. Context.VoidPtrTy);
  1466. args.push_back(&src);
  1467. const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
  1468. R, args, FunctionType::ExtInfo(), /*variadic=*/false);
  1469. llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
  1470. // FIXME: We'd like to put these into a mergable by content, with
  1471. // internal linkage.
  1472. llvm::Function *Fn =
  1473. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1474. "__Block_byref_object_copy_", &CGF.CGM.getModule());
  1475. IdentifierInfo *II
  1476. = &Context.Idents.get("__Block_byref_object_copy_");
  1477. FunctionDecl *FD = FunctionDecl::Create(Context,
  1478. Context.getTranslationUnitDecl(),
  1479. SourceLocation(),
  1480. SourceLocation(), II, R, nullptr,
  1481. SC_Static,
  1482. false, false);
  1483. CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
  1484. CGF.StartFunction(FD, R, Fn, FI, args);
  1485. if (generator.needsCopy()) {
  1486. llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
  1487. // dst->x
  1488. Address destField = CGF.GetAddrOfLocalVar(&dst);
  1489. destField = Address(CGF.Builder.CreateLoad(destField),
  1490. byrefInfo.ByrefAlignment);
  1491. destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
  1492. destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
  1493. "dest-object");
  1494. // src->x
  1495. Address srcField = CGF.GetAddrOfLocalVar(&src);
  1496. srcField = Address(CGF.Builder.CreateLoad(srcField),
  1497. byrefInfo.ByrefAlignment);
  1498. srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
  1499. srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
  1500. "src-object");
  1501. generator.emitCopy(CGF, destField, srcField);
  1502. }
  1503. CGF.FinishFunction();
  1504. return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
  1505. }
  1506. /// Build the copy helper for a __block variable.
  1507. static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
  1508. const BlockByrefInfo &byrefInfo,
  1509. BlockByrefHelpers &generator) {
  1510. CodeGenFunction CGF(CGM);
  1511. return generateByrefCopyHelper(CGF, byrefInfo, generator);
  1512. }
  1513. /// Generate code for a __block variable's dispose helper.
  1514. static llvm::Constant *
  1515. generateByrefDisposeHelper(CodeGenFunction &CGF,
  1516. const BlockByrefInfo &byrefInfo,
  1517. BlockByrefHelpers &generator) {
  1518. ASTContext &Context = CGF.getContext();
  1519. QualType R = Context.VoidTy;
  1520. FunctionArgList args;
  1521. ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
  1522. Context.VoidPtrTy);
  1523. args.push_back(&src);
  1524. const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
  1525. R, args, FunctionType::ExtInfo(), /*variadic=*/false);
  1526. llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
  1527. // FIXME: We'd like to put these into a mergable by content, with
  1528. // internal linkage.
  1529. llvm::Function *Fn =
  1530. llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
  1531. "__Block_byref_object_dispose_",
  1532. &CGF.CGM.getModule());
  1533. IdentifierInfo *II
  1534. = &Context.Idents.get("__Block_byref_object_dispose_");
  1535. FunctionDecl *FD = FunctionDecl::Create(Context,
  1536. Context.getTranslationUnitDecl(),
  1537. SourceLocation(),
  1538. SourceLocation(), II, R, nullptr,
  1539. SC_Static,
  1540. false, false);
  1541. CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
  1542. CGF.StartFunction(FD, R, Fn, FI, args);
  1543. if (generator.needsDispose()) {
  1544. Address addr = CGF.GetAddrOfLocalVar(&src);
  1545. addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
  1546. auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
  1547. addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
  1548. addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
  1549. generator.emitDispose(CGF, addr);
  1550. }
  1551. CGF.FinishFunction();
  1552. return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
  1553. }
  1554. /// Build the dispose helper for a __block variable.
  1555. static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
  1556. const BlockByrefInfo &byrefInfo,
  1557. BlockByrefHelpers &generator) {
  1558. CodeGenFunction CGF(CGM);
  1559. return generateByrefDisposeHelper(CGF, byrefInfo, generator);
  1560. }
  1561. /// Lazily build the copy and dispose helpers for a __block variable
  1562. /// with the given information.
  1563. template <class T>
  1564. static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
  1565. T &&generator) {
  1566. llvm::FoldingSetNodeID id;
  1567. generator.Profile(id);
  1568. void *insertPos;
  1569. BlockByrefHelpers *node
  1570. = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
  1571. if (node) return static_cast<T*>(node);
  1572. generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
  1573. generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
  1574. T *copy = new (CGM.getContext()) T(std::move(generator));
  1575. CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
  1576. return copy;
  1577. }
  1578. /// Build the copy and dispose helpers for the given __block variable
  1579. /// emission. Places the helpers in the global cache. Returns null
  1580. /// if no helpers are required.
  1581. BlockByrefHelpers *
  1582. CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
  1583. const AutoVarEmission &emission) {
  1584. const VarDecl &var = *emission.Variable;
  1585. QualType type = var.getType();
  1586. auto &byrefInfo = getBlockByrefInfo(&var);
  1587. // The alignment we care about for the purposes of uniquing byref
  1588. // helpers is the alignment of the actual byref value field.
  1589. CharUnits valueAlignment =
  1590. byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
  1591. if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
  1592. const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
  1593. if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
  1594. return ::buildByrefHelpers(
  1595. CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
  1596. }
  1597. // Otherwise, if we don't have a retainable type, there's nothing to do.
  1598. // that the runtime does extra copies.
  1599. if (!type->isObjCRetainableType()) return nullptr;
  1600. Qualifiers qs = type.getQualifiers();
  1601. // If we have lifetime, that dominates.
  1602. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
  1603. switch (lifetime) {
  1604. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  1605. // These are just bits as far as the runtime is concerned.
  1606. case Qualifiers::OCL_ExplicitNone:
  1607. case Qualifiers::OCL_Autoreleasing:
  1608. return nullptr;
  1609. // Tell the runtime that this is ARC __weak, called by the
  1610. // byref routines.
  1611. case Qualifiers::OCL_Weak:
  1612. return ::buildByrefHelpers(CGM, byrefInfo,
  1613. ARCWeakByrefHelpers(valueAlignment));
  1614. // ARC __strong __block variables need to be retained.
  1615. case Qualifiers::OCL_Strong:
  1616. // Block pointers need to be copied, and there's no direct
  1617. // transfer possible.
  1618. if (type->isBlockPointerType()) {
  1619. return ::buildByrefHelpers(CGM, byrefInfo,
  1620. ARCStrongBlockByrefHelpers(valueAlignment));
  1621. // Otherwise, we transfer ownership of the retain from the stack
  1622. // to the heap.
  1623. } else {
  1624. return ::buildByrefHelpers(CGM, byrefInfo,
  1625. ARCStrongByrefHelpers(valueAlignment));
  1626. }
  1627. }
  1628. llvm_unreachable("fell out of lifetime switch!");
  1629. }
  1630. BlockFieldFlags flags;
  1631. if (type->isBlockPointerType()) {
  1632. flags |= BLOCK_FIELD_IS_BLOCK;
  1633. } else if (CGM.getContext().isObjCNSObjectType(type) ||
  1634. type->isObjCObjectPointerType()) {
  1635. flags |= BLOCK_FIELD_IS_OBJECT;
  1636. } else {
  1637. return nullptr;
  1638. }
  1639. if (type.isObjCGCWeak())
  1640. flags |= BLOCK_FIELD_IS_WEAK;
  1641. return ::buildByrefHelpers(CGM, byrefInfo,
  1642. ObjectByrefHelpers(valueAlignment, flags));
  1643. }
  1644. Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
  1645. const VarDecl *var,
  1646. bool followForward) {
  1647. auto &info = getBlockByrefInfo(var);
  1648. return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
  1649. }
  1650. Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
  1651. const BlockByrefInfo &info,
  1652. bool followForward,
  1653. const llvm::Twine &name) {
  1654. // Chase the forwarding address if requested.
  1655. if (followForward) {
  1656. Address forwardingAddr =
  1657. Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
  1658. baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
  1659. }
  1660. return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
  1661. info.FieldOffset, name);
  1662. }
  1663. /// BuildByrefInfo - This routine changes a __block variable declared as T x
  1664. /// into:
  1665. ///
  1666. /// struct {
  1667. /// void *__isa;
  1668. /// void *__forwarding;
  1669. /// int32_t __flags;
  1670. /// int32_t __size;
  1671. /// void *__copy_helper; // only if needed
  1672. /// void *__destroy_helper; // only if needed
  1673. /// void *__byref_variable_layout;// only if needed
  1674. /// char padding[X]; // only if needed
  1675. /// T x;
  1676. /// } x
  1677. ///
  1678. const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
  1679. auto it = BlockByrefInfos.find(D);
  1680. if (it != BlockByrefInfos.end())
  1681. return it->second;
  1682. llvm::StructType *byrefType =
  1683. llvm::StructType::create(getLLVMContext(),
  1684. "struct.__block_byref_" + D->getNameAsString());
  1685. QualType Ty = D->getType();
  1686. CharUnits size;
  1687. SmallVector<llvm::Type *, 8> types;
  1688. // void *__isa;
  1689. types.push_back(Int8PtrTy);
  1690. size += getPointerSize();
  1691. // void *__forwarding;
  1692. types.push_back(llvm::PointerType::getUnqual(byrefType));
  1693. size += getPointerSize();
  1694. // int32_t __flags;
  1695. types.push_back(Int32Ty);
  1696. size += CharUnits::fromQuantity(4);
  1697. // int32_t __size;
  1698. types.push_back(Int32Ty);
  1699. size += CharUnits::fromQuantity(4);
  1700. // Note that this must match *exactly* the logic in buildByrefHelpers.
  1701. bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
  1702. if (hasCopyAndDispose) {
  1703. /// void *__copy_helper;
  1704. types.push_back(Int8PtrTy);
  1705. size += getPointerSize();
  1706. /// void *__destroy_helper;
  1707. types.push_back(Int8PtrTy);
  1708. size += getPointerSize();
  1709. }
  1710. bool HasByrefExtendedLayout = false;
  1711. Qualifiers::ObjCLifetime Lifetime;
  1712. if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
  1713. HasByrefExtendedLayout) {
  1714. /// void *__byref_variable_layout;
  1715. types.push_back(Int8PtrTy);
  1716. size += CharUnits::fromQuantity(PointerSizeInBytes);
  1717. }
  1718. // T x;
  1719. llvm::Type *varTy = ConvertTypeForMem(Ty);
  1720. bool packed = false;
  1721. CharUnits varAlign = getContext().getDeclAlign(D);
  1722. CharUnits varOffset = size.alignTo(varAlign);
  1723. // We may have to insert padding.
  1724. if (varOffset != size) {
  1725. llvm::Type *paddingTy =
  1726. llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
  1727. types.push_back(paddingTy);
  1728. size = varOffset;
  1729. // Conversely, we might have to prevent LLVM from inserting padding.
  1730. } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
  1731. > varAlign.getQuantity()) {
  1732. packed = true;
  1733. }
  1734. types.push_back(varTy);
  1735. byrefType->setBody(types, packed);
  1736. BlockByrefInfo info;
  1737. info.Type = byrefType;
  1738. info.FieldIndex = types.size() - 1;
  1739. info.FieldOffset = varOffset;
  1740. info.ByrefAlignment = std::max(varAlign, getPointerAlign());
  1741. auto pair = BlockByrefInfos.insert({D, info});
  1742. assert(pair.second && "info was inserted recursively?");
  1743. return pair.first->second;
  1744. }
  1745. /// Initialize the structural components of a __block variable, i.e.
  1746. /// everything but the actual object.
  1747. void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
  1748. // Find the address of the local.
  1749. Address addr = emission.Addr;
  1750. // That's an alloca of the byref structure type.
  1751. llvm::StructType *byrefType = cast<llvm::StructType>(
  1752. cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
  1753. unsigned nextHeaderIndex = 0;
  1754. CharUnits nextHeaderOffset;
  1755. auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
  1756. const Twine &name) {
  1757. auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
  1758. nextHeaderOffset, name);
  1759. Builder.CreateStore(value, fieldAddr);
  1760. nextHeaderIndex++;
  1761. nextHeaderOffset += fieldSize;
  1762. };
  1763. // Build the byref helpers if necessary. This is null if we don't need any.
  1764. BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
  1765. const VarDecl &D = *emission.Variable;
  1766. QualType type = D.getType();
  1767. bool HasByrefExtendedLayout;
  1768. Qualifiers::ObjCLifetime ByrefLifetime;
  1769. bool ByRefHasLifetime =
  1770. getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
  1771. llvm::Value *V;
  1772. // Initialize the 'isa', which is just 0 or 1.
  1773. int isa = 0;
  1774. if (type.isObjCGCWeak())
  1775. isa = 1;
  1776. V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
  1777. storeHeaderField(V, getPointerSize(), "byref.isa");
  1778. // Store the address of the variable into its own forwarding pointer.
  1779. storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
  1780. // Blocks ABI:
  1781. // c) the flags field is set to either 0 if no helper functions are
  1782. // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
  1783. BlockFlags flags;
  1784. if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
  1785. if (ByRefHasLifetime) {
  1786. if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
  1787. else switch (ByrefLifetime) {
  1788. case Qualifiers::OCL_Strong:
  1789. flags |= BLOCK_BYREF_LAYOUT_STRONG;
  1790. break;
  1791. case Qualifiers::OCL_Weak:
  1792. flags |= BLOCK_BYREF_LAYOUT_WEAK;
  1793. break;
  1794. case Qualifiers::OCL_ExplicitNone:
  1795. flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
  1796. break;
  1797. case Qualifiers::OCL_None:
  1798. if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
  1799. flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
  1800. break;
  1801. default:
  1802. break;
  1803. }
  1804. if (CGM.getLangOpts().ObjCGCBitmapPrint) {
  1805. printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
  1806. if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
  1807. printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
  1808. if (flags & BLOCK_BYREF_LAYOUT_MASK) {
  1809. BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
  1810. if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
  1811. printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
  1812. if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
  1813. printf(" BLOCK_BYREF_LAYOUT_STRONG");
  1814. if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
  1815. printf(" BLOCK_BYREF_LAYOUT_WEAK");
  1816. if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
  1817. printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
  1818. if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
  1819. printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
  1820. }
  1821. printf("\n");
  1822. }
  1823. }
  1824. storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
  1825. getIntSize(), "byref.flags");
  1826. CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
  1827. V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
  1828. storeHeaderField(V, getIntSize(), "byref.size");
  1829. if (helpers) {
  1830. storeHeaderField(helpers->CopyHelper, getPointerSize(),
  1831. "byref.copyHelper");
  1832. storeHeaderField(helpers->DisposeHelper, getPointerSize(),
  1833. "byref.disposeHelper");
  1834. }
  1835. if (ByRefHasLifetime && HasByrefExtendedLayout) {
  1836. auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
  1837. storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
  1838. }
  1839. }
  1840. void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
  1841. llvm::Value *F = CGM.getBlockObjectDispose();
  1842. llvm::Value *args[] = {
  1843. Builder.CreateBitCast(V, Int8PtrTy),
  1844. llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
  1845. };
  1846. EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
  1847. }
  1848. namespace {
  1849. /// Release a __block variable.
  1850. struct CallBlockRelease final : EHScopeStack::Cleanup {
  1851. llvm::Value *Addr;
  1852. CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
  1853. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1854. // Should we be passing FIELD_IS_WEAK here?
  1855. CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
  1856. }
  1857. };
  1858. } // end anonymous namespace
  1859. /// Enter a cleanup to destroy a __block variable. Note that this
  1860. /// cleanup should be a no-op if the variable hasn't left the stack
  1861. /// yet; if a cleanup is required for the variable itself, that needs
  1862. /// to be done externally.
  1863. void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
  1864. // We don't enter this cleanup if we're in pure-GC mode.
  1865. if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
  1866. return;
  1867. EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
  1868. emission.Addr.getPointer());
  1869. }
  1870. /// Adjust the declaration of something from the blocks API.
  1871. static void configureBlocksRuntimeObject(CodeGenModule &CGM,
  1872. llvm::Constant *C) {
  1873. if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
  1874. auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
  1875. if (GV->isDeclaration() && GV->hasExternalLinkage())
  1876. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1877. }
  1878. llvm::Constant *CodeGenModule::getBlockObjectDispose() {
  1879. if (BlockObjectDispose)
  1880. return BlockObjectDispose;
  1881. llvm::Type *args[] = { Int8PtrTy, Int32Ty };
  1882. llvm::FunctionType *fty
  1883. = llvm::FunctionType::get(VoidTy, args, false);
  1884. BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
  1885. configureBlocksRuntimeObject(*this, BlockObjectDispose);
  1886. return BlockObjectDispose;
  1887. }
  1888. llvm::Constant *CodeGenModule::getBlockObjectAssign() {
  1889. if (BlockObjectAssign)
  1890. return BlockObjectAssign;
  1891. llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
  1892. llvm::FunctionType *fty
  1893. = llvm::FunctionType::get(VoidTy, args, false);
  1894. BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
  1895. configureBlocksRuntimeObject(*this, BlockObjectAssign);
  1896. return BlockObjectAssign;
  1897. }
  1898. llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
  1899. if (NSConcreteGlobalBlock)
  1900. return NSConcreteGlobalBlock;
  1901. NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
  1902. Int8PtrTy->getPointerTo(),
  1903. nullptr);
  1904. configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
  1905. return NSConcreteGlobalBlock;
  1906. }
  1907. llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
  1908. if (NSConcreteStackBlock)
  1909. return NSConcreteStackBlock;
  1910. NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
  1911. Int8PtrTy->getPointerTo(),
  1912. nullptr);
  1913. configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
  1914. return NSConcreteStackBlock;
  1915. }