CGBlocks.cpp 92 KB

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