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