CGBlocks.cpp 85 KB

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