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