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