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