CGBlocks.cpp 109 KB

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