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