1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit blocks. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGDebugInfo.h" 15 #include "CodeGenFunction.h" 16 #include "CGObjCRuntime.h" 17 #include "CodeGenModule.h" 18 #include "CGBlocks.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "llvm/Module.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/Target/TargetData.h" 23 #include <algorithm> 24 25 using namespace clang; 26 using namespace CodeGen; 27 28 CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N) 29 : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false), 30 HasCXXObject(false), UsesStret(false), StructureType(0), Block(blockExpr) { 31 32 // Skip asm prefix, if any. 33 if (Name && Name[0] == '\01') 34 ++Name; 35 } 36 37 // Anchor the vtable to this translation unit. 38 CodeGenModule::ByrefHelpers::~ByrefHelpers() {} 39 40 /// Build the given block as a global block. 41 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM, 42 const CGBlockInfo &blockInfo, 43 llvm::Constant *blockFn); 44 45 /// Build the helper function to copy a block. 46 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM, 47 const CGBlockInfo &blockInfo) { 48 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo); 49 } 50 51 /// Build the helper function to dipose of a block. 52 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM, 53 const CGBlockInfo &blockInfo) { 54 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo); 55 } 56 57 /// Build the block descriptor constant for a block. 58 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM, 59 const CGBlockInfo &blockInfo) { 60 ASTContext &C = CGM.getContext(); 61 62 const llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy); 63 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy); 64 65 llvm::SmallVector<llvm::Constant*, 6> elements; 66 67 // reserved 68 elements.push_back(llvm::ConstantInt::get(ulong, 0)); 69 70 // Size 71 // FIXME: What is the right way to say this doesn't fit? We should give 72 // a user diagnostic in that case. Better fix would be to change the 73 // API to size_t. 74 elements.push_back(llvm::ConstantInt::get(ulong, 75 blockInfo.BlockSize.getQuantity())); 76 77 // Optional copy/dispose helpers. 78 if (blockInfo.NeedsCopyDispose) { 79 // copy_func_helper_decl 80 elements.push_back(buildCopyHelper(CGM, blockInfo)); 81 82 // destroy_func_decl 83 elements.push_back(buildDisposeHelper(CGM, blockInfo)); 84 } 85 86 // Signature. Mandatory ObjC-style method descriptor @encode sequence. 87 std::string typeAtEncoding = 88 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr()); 89 elements.push_back(llvm::ConstantExpr::getBitCast( 90 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p)); 91 92 // GC layout. 93 if (C.getLangOptions().ObjC1) 94 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo)); 95 else 96 elements.push_back(llvm::Constant::getNullValue(i8p)); 97 98 llvm::Constant *init = 99 llvm::ConstantStruct::get(CGM.getLLVMContext(), elements.data(), 100 elements.size(), false); 101 102 llvm::GlobalVariable *global = 103 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true, 104 llvm::GlobalValue::InternalLinkage, 105 init, "__block_descriptor_tmp"); 106 107 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType()); 108 } 109 110 /* 111 Purely notional variadic template describing the layout of a block. 112 113 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes> 114 struct Block_literal { 115 /// Initialized to one of: 116 /// extern void *_NSConcreteStackBlock[]; 117 /// extern void *_NSConcreteGlobalBlock[]; 118 /// 119 /// In theory, we could start one off malloc'ed by setting 120 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using 121 /// this isa: 122 /// extern void *_NSConcreteMallocBlock[]; 123 struct objc_class *isa; 124 125 /// These are the flags (with corresponding bit number) that the 126 /// compiler is actually supposed to know about. 127 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block 128 /// descriptor provides copy and dispose helper functions 129 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured 130 /// object with a nontrivial destructor or copy constructor 131 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated 132 /// as global memory 133 /// 29. BLOCK_USE_STRET - indicates that the block function 134 /// uses stret, which objc_msgSend needs to know about 135 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an 136 /// @encoded signature string 137 /// And we're not supposed to manipulate these: 138 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved 139 /// to malloc'ed memory 140 /// 27. BLOCK_IS_GC - indicates that the block has been moved to 141 /// to GC-allocated memory 142 /// Additionally, the bottom 16 bits are a reference count which 143 /// should be zero on the stack. 144 int flags; 145 146 /// Reserved; should be zero-initialized. 147 int reserved; 148 149 /// Function pointer generated from block literal. 150 _ResultType (*invoke)(Block_literal *, _ParamTypes...); 151 152 /// Block description metadata generated from block literal. 153 struct Block_descriptor *block_descriptor; 154 155 /// Captured values follow. 156 _CapturesTypes captures...; 157 }; 158 */ 159 160 /// The number of fields in a block header. 161 const unsigned BlockHeaderSize = 5; 162 163 namespace { 164 /// A chunk of data that we actually have to capture in the block. 165 struct BlockLayoutChunk { 166 CharUnits Alignment; 167 CharUnits Size; 168 const BlockDecl::Capture *Capture; // null for 'this' 169 const llvm::Type *Type; 170 171 BlockLayoutChunk(CharUnits align, CharUnits size, 172 const BlockDecl::Capture *capture, 173 const llvm::Type *type) 174 : Alignment(align), Size(size), Capture(capture), Type(type) {} 175 176 /// Tell the block info that this chunk has the given field index. 177 void setIndex(CGBlockInfo &info, unsigned index) { 178 if (!Capture) 179 info.CXXThisIndex = index; 180 else 181 info.Captures[Capture->getVariable()] 182 = CGBlockInfo::Capture::makeIndex(index); 183 } 184 }; 185 186 /// Order by descending alignment. 187 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) { 188 return left.Alignment > right.Alignment; 189 } 190 } 191 192 /// Determines if the given type is safe for constant capture in C++. 193 static bool isSafeForCXXConstantCapture(QualType type) { 194 const RecordType *recordType = 195 type->getBaseElementTypeUnsafe()->getAs<RecordType>(); 196 197 // Only records can be unsafe. 198 if (!recordType) return true; 199 200 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl()); 201 202 // Maintain semantics for classes with non-trivial dtors or copy ctors. 203 if (!record->hasTrivialDestructor()) return false; 204 if (!record->hasTrivialCopyConstructor()) return false; 205 206 // Otherwise, we just have to make sure there aren't any mutable 207 // fields that might have changed since initialization. 208 return !record->hasMutableFields(); 209 } 210 211 /// It is illegal to modify a const object after initialization. 212 /// Therefore, if a const object has a constant initializer, we don't 213 /// actually need to keep storage for it in the block; we'll just 214 /// rematerialize it at the start of the block function. This is 215 /// acceptable because we make no promises about address stability of 216 /// captured variables. 217 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM, 218 const VarDecl *var) { 219 QualType type = var->getType(); 220 221 // We can only do this if the variable is const. 222 if (!type.isConstQualified()) return 0; 223 224 // Furthermore, in C++ we have to worry about mutable fields: 225 // C++ [dcl.type.cv]p4: 226 // Except that any class member declared mutable can be 227 // modified, any attempt to modify a const object during its 228 // lifetime results in undefined behavior. 229 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type)) 230 return 0; 231 232 // If the variable doesn't have any initializer (shouldn't this be 233 // invalid?), it's not clear what we should do. Maybe capture as 234 // zero? 235 const Expr *init = var->getInit(); 236 if (!init) return 0; 237 238 return CGM.EmitConstantExpr(init, var->getType()); 239 } 240 241 /// Get the low bit of a nonzero character count. This is the 242 /// alignment of the nth byte if the 0th byte is universally aligned. 243 static CharUnits getLowBit(CharUnits v) { 244 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1)); 245 } 246 247 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info, 248 llvm::SmallVectorImpl<const llvm::Type*> &elementTypes) { 249 ASTContext &C = CGM.getContext(); 250 251 // The header is basically a 'struct { void *; int; int; void *; void *; }'. 252 CharUnits ptrSize, ptrAlign, intSize, intAlign; 253 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy); 254 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy); 255 256 // Are there crazy embedded platforms where this isn't true? 257 assert(intSize <= ptrSize && "layout assumptions horribly violated"); 258 259 CharUnits headerSize = ptrSize; 260 if (2 * intSize < ptrAlign) headerSize += ptrSize; 261 else headerSize += 2 * intSize; 262 headerSize += 2 * ptrSize; 263 264 info.BlockAlign = ptrAlign; 265 info.BlockSize = headerSize; 266 267 assert(elementTypes.empty()); 268 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy); 269 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy); 270 elementTypes.push_back(i8p); 271 elementTypes.push_back(intTy); 272 elementTypes.push_back(intTy); 273 elementTypes.push_back(i8p); 274 elementTypes.push_back(CGM.getBlockDescriptorType()); 275 276 assert(elementTypes.size() == BlockHeaderSize); 277 } 278 279 /// Compute the layout of the given block. Attempts to lay the block 280 /// out with minimal space requirements. 281 static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) { 282 ASTContext &C = CGM.getContext(); 283 const BlockDecl *block = info.getBlockDecl(); 284 285 llvm::SmallVector<const llvm::Type*, 8> elementTypes; 286 initializeForBlockHeader(CGM, info, elementTypes); 287 288 if (!block->hasCaptures()) { 289 info.StructureType = 290 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true); 291 info.CanBeGlobal = true; 292 return; 293 } 294 295 // Collect the layout chunks. 296 llvm::SmallVector<BlockLayoutChunk, 16> layout; 297 layout.reserve(block->capturesCXXThis() + 298 (block->capture_end() - block->capture_begin())); 299 300 CharUnits maxFieldAlign; 301 302 // First, 'this'. 303 if (block->capturesCXXThis()) { 304 const DeclContext *DC = block->getDeclContext(); 305 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext()) 306 ; 307 QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C); 308 309 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType); 310 std::pair<CharUnits,CharUnits> tinfo 311 = CGM.getContext().getTypeInfoInChars(thisType); 312 maxFieldAlign = std::max(maxFieldAlign, tinfo.second); 313 314 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType)); 315 } 316 317 // Next, all the block captures. 318 for (BlockDecl::capture_const_iterator ci = block->capture_begin(), 319 ce = block->capture_end(); ci != ce; ++ci) { 320 const VarDecl *variable = ci->getVariable(); 321 322 if (ci->isByRef()) { 323 // We have to copy/dispose of the __block reference. 324 info.NeedsCopyDispose = true; 325 326 // Just use void* instead of a pointer to the byref type. 327 QualType byRefPtrTy = C.VoidPtrTy; 328 329 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy); 330 std::pair<CharUnits,CharUnits> tinfo 331 = CGM.getContext().getTypeInfoInChars(byRefPtrTy); 332 maxFieldAlign = std::max(maxFieldAlign, tinfo.second); 333 334 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 335 &*ci, llvmType)); 336 continue; 337 } 338 339 // Otherwise, build a layout chunk with the size and alignment of 340 // the declaration. 341 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) { 342 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant); 343 continue; 344 } 345 346 // Block pointers require copy/dispose. 347 if (variable->getType()->isBlockPointerType()) { 348 info.NeedsCopyDispose = true; 349 350 // So do Objective-C pointers. 351 } else if (variable->getType()->isObjCObjectPointerType() || 352 C.isObjCNSObjectType(variable->getType())) { 353 info.NeedsCopyDispose = true; 354 355 // So do types that require non-trivial copy construction. 356 } else if (ci->hasCopyExpr()) { 357 info.NeedsCopyDispose = true; 358 info.HasCXXObject = true; 359 360 // And so do types with destructors. 361 } else if (CGM.getLangOptions().CPlusPlus) { 362 if (const CXXRecordDecl *record = 363 variable->getType()->getAsCXXRecordDecl()) { 364 if (!record->hasTrivialDestructor()) { 365 info.HasCXXObject = true; 366 info.NeedsCopyDispose = true; 367 } 368 } 369 } 370 371 CharUnits size = C.getTypeSizeInChars(variable->getType()); 372 CharUnits align = C.getDeclAlign(variable); 373 maxFieldAlign = std::max(maxFieldAlign, align); 374 375 const llvm::Type *llvmType = 376 CGM.getTypes().ConvertTypeForMem(variable->getType()); 377 378 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType)); 379 } 380 381 // If that was everything, we're done here. 382 if (layout.empty()) { 383 info.StructureType = 384 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true); 385 info.CanBeGlobal = true; 386 return; 387 } 388 389 // Sort the layout by alignment. We have to use a stable sort here 390 // to get reproducible results. There should probably be an 391 // llvm::array_pod_stable_sort. 392 std::stable_sort(layout.begin(), layout.end()); 393 394 CharUnits &blockSize = info.BlockSize; 395 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign); 396 397 // Assuming that the first byte in the header is maximally aligned, 398 // get the alignment of the first byte following the header. 399 CharUnits endAlign = getLowBit(blockSize); 400 401 // If the end of the header isn't satisfactorily aligned for the 402 // maximum thing, look for things that are okay with the header-end 403 // alignment, and keep appending them until we get something that's 404 // aligned right. This algorithm is only guaranteed optimal if 405 // that condition is satisfied at some point; otherwise we can get 406 // things like: 407 // header // next byte has alignment 4 408 // something_with_size_5; // next byte has alignment 1 409 // something_with_alignment_8; 410 // which has 7 bytes of padding, as opposed to the naive solution 411 // which might have less (?). 412 if (endAlign < maxFieldAlign) { 413 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator 414 li = layout.begin() + 1, le = layout.end(); 415 416 // Look for something that the header end is already 417 // satisfactorily aligned for. 418 for (; li != le && endAlign < li->Alignment; ++li) 419 ; 420 421 // If we found something that's naturally aligned for the end of 422 // the header, keep adding things... 423 if (li != le) { 424 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li; 425 for (; li != le; ++li) { 426 assert(endAlign >= li->Alignment); 427 428 li->setIndex(info, elementTypes.size()); 429 elementTypes.push_back(li->Type); 430 blockSize += li->Size; 431 endAlign = getLowBit(blockSize); 432 433 // ...until we get to the alignment of the maximum field. 434 if (endAlign >= maxFieldAlign) 435 break; 436 } 437 438 // Don't re-append everything we just appended. 439 layout.erase(first, li); 440 } 441 } 442 443 // At this point, we just have to add padding if the end align still 444 // isn't aligned right. 445 if (endAlign < maxFieldAlign) { 446 CharUnits padding = maxFieldAlign - endAlign; 447 448 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty, 449 padding.getQuantity())); 450 blockSize += padding; 451 452 endAlign = getLowBit(blockSize); 453 assert(endAlign >= maxFieldAlign); 454 } 455 456 // Slam everything else on now. This works because they have 457 // strictly decreasing alignment and we expect that size is always a 458 // multiple of alignment. 459 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator 460 li = layout.begin(), le = layout.end(); li != le; ++li) { 461 assert(endAlign >= li->Alignment); 462 li->setIndex(info, elementTypes.size()); 463 elementTypes.push_back(li->Type); 464 blockSize += li->Size; 465 endAlign = getLowBit(blockSize); 466 } 467 468 info.StructureType = 469 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true); 470 } 471 472 /// Emit a block literal expression in the current function. 473 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) { 474 std::string Name = CurFn->getName(); 475 CGBlockInfo blockInfo(blockExpr, Name.c_str()); 476 477 // Compute information about the layout, etc., of this block. 478 computeBlockInfo(CGM, blockInfo); 479 480 // Using that metadata, generate the actual block function. 481 llvm::Constant *blockFn 482 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo, 483 CurFuncDecl, LocalDeclMap); 484 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy); 485 486 // If there is nothing to capture, we can emit this as a global block. 487 if (blockInfo.CanBeGlobal) 488 return buildGlobalBlock(CGM, blockInfo, blockFn); 489 490 // Otherwise, we have to emit this as a local block. 491 492 llvm::Constant *isa = CGM.getNSConcreteStackBlock(); 493 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy); 494 495 // Build the block descriptor. 496 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo); 497 498 const llvm::Type *intTy = ConvertType(getContext().IntTy); 499 500 llvm::AllocaInst *blockAddr = 501 CreateTempAlloca(blockInfo.StructureType, "block"); 502 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity()); 503 504 // Compute the initial on-stack block flags. 505 BlockFlags flags = BLOCK_HAS_SIGNATURE; 506 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE; 507 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ; 508 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET; 509 510 // Initialize the block literal. 511 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa")); 512 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()), 513 Builder.CreateStructGEP(blockAddr, 1, "block.flags")); 514 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0), 515 Builder.CreateStructGEP(blockAddr, 2, "block.reserved")); 516 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3, 517 "block.invoke")); 518 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4, 519 "block.descriptor")); 520 521 // Finally, capture all the values into the block. 522 const BlockDecl *blockDecl = blockInfo.getBlockDecl(); 523 524 // First, 'this'. 525 if (blockDecl->capturesCXXThis()) { 526 llvm::Value *addr = Builder.CreateStructGEP(blockAddr, 527 blockInfo.CXXThisIndex, 528 "block.captured-this.addr"); 529 Builder.CreateStore(LoadCXXThis(), addr); 530 } 531 532 // Next, captured variables. 533 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(), 534 ce = blockDecl->capture_end(); ci != ce; ++ci) { 535 const VarDecl *variable = ci->getVariable(); 536 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 537 538 // Ignore constant captures. 539 if (capture.isConstant()) continue; 540 541 QualType type = variable->getType(); 542 543 // This will be a [[type]]*, except that a byref entry will just be 544 // an i8**. 545 llvm::Value *blockField = 546 Builder.CreateStructGEP(blockAddr, capture.getIndex(), 547 "block.captured"); 548 549 // Compute the address of the thing we're going to move into the 550 // block literal. 551 llvm::Value *src; 552 if (ci->isNested()) { 553 // We need to use the capture from the enclosing block. 554 const CGBlockInfo::Capture &enclosingCapture = 555 BlockInfo->getCapture(variable); 556 557 // This is a [[type]]*, except that a byref entry wil just be an i8**. 558 src = Builder.CreateStructGEP(LoadBlockStruct(), 559 enclosingCapture.getIndex(), 560 "block.capture.addr"); 561 } else { 562 // This is a [[type]]*. 563 src = LocalDeclMap[variable]; 564 } 565 566 // For byrefs, we just write the pointer to the byref struct into 567 // the block field. There's no need to chase the forwarding 568 // pointer at this point, since we're building something that will 569 // live a shorter life than the stack byref anyway. 570 if (ci->isByRef()) { 571 // Get a void* that points to the byref struct. 572 if (ci->isNested()) 573 src = Builder.CreateLoad(src, "byref.capture"); 574 else 575 src = Builder.CreateBitCast(src, VoidPtrTy); 576 577 // Write that void* into the capture field. 578 Builder.CreateStore(src, blockField); 579 580 // If we have a copy constructor, evaluate that into the block field. 581 } else if (const Expr *copyExpr = ci->getCopyExpr()) { 582 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr); 583 584 // If it's a reference variable, copy the reference into the block field. 585 } else if (type->isReferenceType()) { 586 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField); 587 588 // Otherwise, fake up a POD copy into the block field. 589 } else { 590 // We use one of these or the other depending on whether the 591 // reference is nested. 592 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue, 593 SourceLocation()); 594 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type, 595 VK_LValue, SourceLocation(), /*byref*/ false); 596 597 Expr *declRef = 598 (ci->isNested() ? static_cast<Expr*>(&nested) : ¬Nested); 599 600 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue, 601 declRef, VK_RValue); 602 EmitExprAsInit(&l2r, variable, blockField, 603 getContext().getDeclAlign(variable), 604 /*captured by init*/ false); 605 } 606 607 // Push a destructor if necessary. The semantics for when this 608 // actually gets run are really obscure. 609 if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus) 610 PushDestructorCleanup(type, blockField); 611 } 612 613 // Cast to the converted block-pointer type, which happens (somewhat 614 // unfortunately) to be a pointer to function type. 615 llvm::Value *result = 616 Builder.CreateBitCast(blockAddr, 617 ConvertType(blockInfo.getBlockExpr()->getType())); 618 619 return result; 620 } 621 622 623 const llvm::Type *CodeGenModule::getBlockDescriptorType() { 624 if (BlockDescriptorType) 625 return BlockDescriptorType; 626 627 const llvm::Type *UnsignedLongTy = 628 getTypes().ConvertType(getContext().UnsignedLongTy); 629 630 // struct __block_descriptor { 631 // unsigned long reserved; 632 // unsigned long block_size; 633 // 634 // // later, the following will be added 635 // 636 // struct { 637 // void (*copyHelper)(); 638 // void (*copyHelper)(); 639 // } helpers; // !!! optional 640 // 641 // const char *signature; // the block signature 642 // const char *layout; // reserved 643 // }; 644 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(), 645 UnsignedLongTy, 646 UnsignedLongTy, 647 NULL); 648 649 getModule().addTypeName("struct.__block_descriptor", 650 BlockDescriptorType); 651 652 // Now form a pointer to that. 653 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType); 654 return BlockDescriptorType; 655 } 656 657 const llvm::Type *CodeGenModule::getGenericBlockLiteralType() { 658 if (GenericBlockLiteralType) 659 return GenericBlockLiteralType; 660 661 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType(); 662 663 // struct __block_literal_generic { 664 // void *__isa; 665 // int __flags; 666 // int __reserved; 667 // void (*__invoke)(void *); 668 // struct __block_descriptor *__descriptor; 669 // }; 670 GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(), 671 VoidPtrTy, 672 IntTy, 673 IntTy, 674 VoidPtrTy, 675 BlockDescPtrTy, 676 NULL); 677 678 getModule().addTypeName("struct.__block_literal_generic", 679 GenericBlockLiteralType); 680 681 return GenericBlockLiteralType; 682 } 683 684 685 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E, 686 ReturnValueSlot ReturnValue) { 687 const BlockPointerType *BPT = 688 E->getCallee()->getType()->getAs<BlockPointerType>(); 689 690 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 691 692 // Get a pointer to the generic block literal. 693 const llvm::Type *BlockLiteralTy = 694 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType()); 695 696 // Bitcast the callee to a block literal. 697 llvm::Value *BlockLiteral = 698 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal"); 699 700 // Get the function pointer from the literal. 701 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp"); 702 703 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp"); 704 705 // Add the block literal. 706 CallArgList Args; 707 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy); 708 709 QualType FnType = BPT->getPointeeType(); 710 711 // And the rest of the arguments. 712 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), 713 E->arg_begin(), E->arg_end()); 714 715 // Load the function. 716 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp"); 717 718 const FunctionType *FuncTy = FnType->castAs<FunctionType>(); 719 QualType ResultType = FuncTy->getResultType(); 720 721 const CGFunctionInfo &FnInfo = 722 CGM.getTypes().getFunctionInfo(ResultType, Args, 723 FuncTy->getExtInfo()); 724 725 // Cast the function pointer to the right type. 726 const llvm::Type *BlockFTy = 727 CGM.getTypes().GetFunctionType(FnInfo, false); 728 729 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy); 730 Func = Builder.CreateBitCast(Func, BlockFTyPtr); 731 732 // And call the block. 733 return EmitCall(FnInfo, Func, ReturnValue, Args); 734 } 735 736 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable, 737 bool isByRef) { 738 assert(BlockInfo && "evaluating block ref without block information?"); 739 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable); 740 741 // Handle constant captures. 742 if (capture.isConstant()) return LocalDeclMap[variable]; 743 744 llvm::Value *addr = 745 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(), 746 "block.capture.addr"); 747 748 if (isByRef) { 749 // addr should be a void** right now. Load, then cast the result 750 // to byref*. 751 752 addr = Builder.CreateLoad(addr); 753 const llvm::PointerType *byrefPointerType 754 = llvm::PointerType::get(BuildByRefType(variable), 0); 755 addr = Builder.CreateBitCast(addr, byrefPointerType, 756 "byref.addr"); 757 758 // Follow the forwarding pointer. 759 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding"); 760 addr = Builder.CreateLoad(addr, "byref.addr.forwarded"); 761 762 // Cast back to byref* and GEP over to the actual object. 763 addr = Builder.CreateBitCast(addr, byrefPointerType); 764 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable), 765 variable->getNameAsString()); 766 } 767 768 if (variable->getType()->isReferenceType()) 769 addr = Builder.CreateLoad(addr, "ref.tmp"); 770 771 return addr; 772 } 773 774 llvm::Constant * 775 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr, 776 const char *name) { 777 CGBlockInfo blockInfo(blockExpr, name); 778 779 // Compute information about the layout, etc., of this block. 780 computeBlockInfo(*this, blockInfo); 781 782 // Using that metadata, generate the actual block function. 783 llvm::Constant *blockFn; 784 { 785 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap; 786 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(), 787 blockInfo, 788 0, LocalDeclMap); 789 } 790 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy); 791 792 return buildGlobalBlock(*this, blockInfo, blockFn); 793 } 794 795 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM, 796 const CGBlockInfo &blockInfo, 797 llvm::Constant *blockFn) { 798 assert(blockInfo.CanBeGlobal); 799 800 // Generate the constants for the block literal initializer. 801 llvm::Constant *fields[BlockHeaderSize]; 802 803 // isa 804 fields[0] = CGM.getNSConcreteGlobalBlock(); 805 806 // __flags 807 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE; 808 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET; 809 810 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask()); 811 812 // Reserved 813 fields[2] = llvm::Constant::getNullValue(CGM.IntTy); 814 815 // Function 816 fields[3] = blockFn; 817 818 // Descriptor 819 fields[4] = buildBlockDescriptor(CGM, blockInfo); 820 821 llvm::Constant *init = 822 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize, 823 /*packed*/ false); 824 825 llvm::GlobalVariable *literal = 826 new llvm::GlobalVariable(CGM.getModule(), 827 init->getType(), 828 /*constant*/ true, 829 llvm::GlobalVariable::InternalLinkage, 830 init, 831 "__block_literal_global"); 832 literal->setAlignment(blockInfo.BlockAlign.getQuantity()); 833 834 // Return a constant of the appropriately-casted type. 835 const llvm::Type *requiredType = 836 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType()); 837 return llvm::ConstantExpr::getBitCast(literal, requiredType); 838 } 839 840 llvm::Function * 841 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD, 842 const CGBlockInfo &blockInfo, 843 const Decl *outerFnDecl, 844 const DeclMapTy &ldm) { 845 const BlockDecl *blockDecl = blockInfo.getBlockDecl(); 846 847 // Check if we should generate debug info for this block function. 848 if (CGM.getModuleDebugInfo()) 849 DebugInfo = CGM.getModuleDebugInfo(); 850 851 BlockInfo = &blockInfo; 852 853 // Arrange for local static and local extern declarations to appear 854 // to be local to this function as well, in case they're directly 855 // referenced in a block. 856 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) { 857 const VarDecl *var = dyn_cast<VarDecl>(i->first); 858 if (var && !var->hasLocalStorage()) 859 LocalDeclMap[var] = i->second; 860 } 861 862 // Begin building the function declaration. 863 864 // Build the argument list. 865 FunctionArgList args; 866 867 // The first argument is the block pointer. Just take it as a void* 868 // and cast it later. 869 QualType selfTy = getContext().VoidPtrTy; 870 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor"); 871 872 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl), 873 SourceLocation(), II, selfTy); 874 args.push_back(&selfDecl); 875 876 // Now add the rest of the parameters. 877 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(), 878 e = blockDecl->param_end(); i != e; ++i) 879 args.push_back(*i); 880 881 // Create the function declaration. 882 const FunctionProtoType *fnType = 883 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType()); 884 const CGFunctionInfo &fnInfo = 885 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args, 886 fnType->getExtInfo()); 887 if (CGM.ReturnTypeUsesSRet(fnInfo)) 888 blockInfo.UsesStret = true; 889 890 const llvm::FunctionType *fnLLVMType = 891 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic()); 892 893 MangleBuffer name; 894 CGM.getBlockMangledName(GD, name, blockDecl); 895 llvm::Function *fn = 896 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage, 897 name.getString(), &CGM.getModule()); 898 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo); 899 900 // Begin generating the function. 901 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args, 902 blockInfo.getBlockExpr()->getBody()->getLocStart()); 903 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl 904 905 // Okay. Undo some of what StartFunction did. 906 907 // Pull the 'self' reference out of the local decl map. 908 llvm::Value *blockAddr = LocalDeclMap[&selfDecl]; 909 LocalDeclMap.erase(&selfDecl); 910 BlockPointer = Builder.CreateBitCast(blockAddr, 911 blockInfo.StructureType->getPointerTo(), 912 "block"); 913 914 // If we have a C++ 'this' reference, go ahead and force it into 915 // existence now. 916 if (blockDecl->capturesCXXThis()) { 917 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer, 918 blockInfo.CXXThisIndex, 919 "block.captured-this"); 920 CXXThisValue = Builder.CreateLoad(addr, "this"); 921 } 922 923 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap; 924 // appease it. 925 if (const ObjCMethodDecl *method 926 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) { 927 const VarDecl *self = method->getSelfDecl(); 928 929 // There might not be a capture for 'self', but if there is... 930 if (blockInfo.Captures.count(self)) { 931 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self); 932 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer, 933 capture.getIndex(), 934 "block.captured-self"); 935 LocalDeclMap[self] = selfAddr; 936 } 937 } 938 939 // Also force all the constant captures. 940 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(), 941 ce = blockDecl->capture_end(); ci != ce; ++ci) { 942 const VarDecl *variable = ci->getVariable(); 943 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 944 if (!capture.isConstant()) continue; 945 946 unsigned align = getContext().getDeclAlign(variable).getQuantity(); 947 948 llvm::AllocaInst *alloca = 949 CreateMemTemp(variable->getType(), "block.captured-const"); 950 alloca->setAlignment(align); 951 952 Builder.CreateStore(capture.getConstant(), alloca, align); 953 954 LocalDeclMap[variable] = alloca; 955 } 956 957 // Save a spot to insert the debug information for all the BlockDeclRefDecls. 958 llvm::BasicBlock *entry = Builder.GetInsertBlock(); 959 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint(); 960 --entry_ptr; 961 962 EmitStmt(blockDecl->getBody()); 963 964 // Remember where we were... 965 llvm::BasicBlock *resume = Builder.GetInsertBlock(); 966 967 // Go back to the entry. 968 ++entry_ptr; 969 Builder.SetInsertPoint(entry, entry_ptr); 970 971 // Emit debug information for all the BlockDeclRefDecls. 972 // FIXME: also for 'this' 973 if (CGDebugInfo *DI = getDebugInfo()) { 974 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(), 975 ce = blockDecl->capture_end(); ci != ce; ++ci) { 976 const VarDecl *variable = ci->getVariable(); 977 DI->setLocation(variable->getLocation()); 978 979 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 980 if (capture.isConstant()) { 981 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable], 982 Builder); 983 continue; 984 } 985 986 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer, 987 Builder, blockInfo); 988 } 989 } 990 991 // And resume where we left off. 992 if (resume == 0) 993 Builder.ClearInsertionPoint(); 994 else 995 Builder.SetInsertPoint(resume); 996 997 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc()); 998 999 return fn; 1000 } 1001 1002 /* 1003 notes.push_back(HelperInfo()); 1004 HelperInfo ¬e = notes.back(); 1005 note.index = capture.getIndex(); 1006 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type)); 1007 note.cxxbar_import = ci->getCopyExpr(); 1008 1009 if (ci->isByRef()) { 1010 note.flag = BLOCK_FIELD_IS_BYREF; 1011 if (type.isObjCGCWeak()) 1012 note.flag |= BLOCK_FIELD_IS_WEAK; 1013 } else if (type->isBlockPointerType()) { 1014 note.flag = BLOCK_FIELD_IS_BLOCK; 1015 } else { 1016 note.flag = BLOCK_FIELD_IS_OBJECT; 1017 } 1018 */ 1019 1020 1021 1022 1023 1024 llvm::Constant * 1025 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) { 1026 ASTContext &C = getContext(); 1027 1028 FunctionArgList args; 1029 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy); 1030 args.push_back(&dstDecl); 1031 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy); 1032 args.push_back(&srcDecl); 1033 1034 const CGFunctionInfo &FI = 1035 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo()); 1036 1037 // FIXME: it would be nice if these were mergeable with things with 1038 // identical semantics. 1039 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false); 1040 1041 llvm::Function *Fn = 1042 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 1043 "__copy_helper_block_", &CGM.getModule()); 1044 1045 IdentifierInfo *II 1046 = &CGM.getContext().Idents.get("__copy_helper_block_"); 1047 1048 // Check if we should generate debug info for this block helper function. 1049 if (CGM.getModuleDebugInfo()) 1050 DebugInfo = CGM.getModuleDebugInfo(); 1051 1052 FunctionDecl *FD = FunctionDecl::Create(C, 1053 C.getTranslationUnitDecl(), 1054 SourceLocation(), 1055 SourceLocation(), II, C.VoidTy, 0, 1056 SC_Static, 1057 SC_None, 1058 false, 1059 true); 1060 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 1061 1062 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo(); 1063 1064 llvm::Value *src = GetAddrOfLocalVar(&srcDecl); 1065 src = Builder.CreateLoad(src); 1066 src = Builder.CreateBitCast(src, structPtrTy, "block.source"); 1067 1068 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl); 1069 dst = Builder.CreateLoad(dst); 1070 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest"); 1071 1072 const BlockDecl *blockDecl = blockInfo.getBlockDecl(); 1073 1074 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(), 1075 ce = blockDecl->capture_end(); ci != ce; ++ci) { 1076 const VarDecl *variable = ci->getVariable(); 1077 QualType type = variable->getType(); 1078 1079 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 1080 if (capture.isConstant()) continue; 1081 1082 const Expr *copyExpr = ci->getCopyExpr(); 1083 unsigned flags = 0; 1084 1085 if (copyExpr) { 1086 assert(!ci->isByRef()); 1087 // don't bother computing flags 1088 } else if (ci->isByRef()) { 1089 flags = BLOCK_FIELD_IS_BYREF; 1090 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK; 1091 } else if (type->isBlockPointerType()) { 1092 flags = BLOCK_FIELD_IS_BLOCK; 1093 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) { 1094 flags = BLOCK_FIELD_IS_OBJECT; 1095 } 1096 1097 if (!copyExpr && !flags) continue; 1098 1099 unsigned index = capture.getIndex(); 1100 llvm::Value *srcField = Builder.CreateStructGEP(src, index); 1101 llvm::Value *dstField = Builder.CreateStructGEP(dst, index); 1102 1103 // If there's an explicit copy expression, we do that. 1104 if (copyExpr) { 1105 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr); 1106 } else { 1107 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src"); 1108 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy); 1109 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy); 1110 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue, 1111 llvm::ConstantInt::get(Int32Ty, flags)); 1112 } 1113 } 1114 1115 FinishFunction(); 1116 1117 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 1118 } 1119 1120 llvm::Constant * 1121 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) { 1122 ASTContext &C = getContext(); 1123 1124 FunctionArgList args; 1125 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy); 1126 args.push_back(&srcDecl); 1127 1128 const CGFunctionInfo &FI = 1129 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo()); 1130 1131 // FIXME: We'd like to put these into a mergable by content, with 1132 // internal linkage. 1133 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false); 1134 1135 llvm::Function *Fn = 1136 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 1137 "__destroy_helper_block_", &CGM.getModule()); 1138 1139 // Check if we should generate debug info for this block destroy function. 1140 if (CGM.getModuleDebugInfo()) 1141 DebugInfo = CGM.getModuleDebugInfo(); 1142 1143 IdentifierInfo *II 1144 = &CGM.getContext().Idents.get("__destroy_helper_block_"); 1145 1146 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(), 1147 SourceLocation(), 1148 SourceLocation(), II, C.VoidTy, 0, 1149 SC_Static, 1150 SC_None, 1151 false, true); 1152 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 1153 1154 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo(); 1155 1156 llvm::Value *src = GetAddrOfLocalVar(&srcDecl); 1157 src = Builder.CreateLoad(src); 1158 src = Builder.CreateBitCast(src, structPtrTy, "block"); 1159 1160 const BlockDecl *blockDecl = blockInfo.getBlockDecl(); 1161 1162 CodeGenFunction::RunCleanupsScope cleanups(*this); 1163 1164 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(), 1165 ce = blockDecl->capture_end(); ci != ce; ++ci) { 1166 const VarDecl *variable = ci->getVariable(); 1167 QualType type = variable->getType(); 1168 1169 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); 1170 if (capture.isConstant()) continue; 1171 1172 BlockFieldFlags flags; 1173 const CXXDestructorDecl *dtor = 0; 1174 1175 if (ci->isByRef()) { 1176 flags = BLOCK_FIELD_IS_BYREF; 1177 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK; 1178 } else if (type->isBlockPointerType()) { 1179 flags = BLOCK_FIELD_IS_BLOCK; 1180 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) { 1181 flags = BLOCK_FIELD_IS_OBJECT; 1182 } else if (C.getLangOptions().CPlusPlus) { 1183 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) 1184 if (!record->hasTrivialDestructor()) 1185 dtor = record->getDestructor(); 1186 } 1187 1188 if (!dtor && flags.empty()) continue; 1189 1190 unsigned index = capture.getIndex(); 1191 llvm::Value *srcField = Builder.CreateStructGEP(src, index); 1192 1193 // If there's an explicit copy expression, we do that. 1194 if (dtor) { 1195 PushDestructorCleanup(dtor, srcField); 1196 1197 // Otherwise we call _Block_object_dispose. It wouldn't be too 1198 // hard to just emit this as a cleanup if we wanted to make sure 1199 // that things were done in reverse. 1200 } else { 1201 llvm::Value *value = Builder.CreateLoad(srcField); 1202 value = Builder.CreateBitCast(value, VoidPtrTy); 1203 BuildBlockRelease(value, flags); 1204 } 1205 } 1206 1207 cleanups.ForceCleanup(); 1208 1209 FinishFunction(); 1210 1211 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 1212 } 1213 1214 namespace { 1215 1216 /// Emits the copy/dispose helper functions for a __block object of id type. 1217 class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers { 1218 BlockFieldFlags Flags; 1219 1220 public: 1221 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags) 1222 : ByrefHelpers(alignment), Flags(flags) {} 1223 1224 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField, 1225 llvm::Value *srcField) { 1226 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy); 1227 1228 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy); 1229 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField); 1230 1231 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask(); 1232 1233 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags); 1234 llvm::Value *fn = CGF.CGM.getBlockObjectAssign(); 1235 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal); 1236 } 1237 1238 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) { 1239 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0)); 1240 llvm::Value *value = CGF.Builder.CreateLoad(field); 1241 1242 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER); 1243 } 1244 1245 void profileImpl(llvm::FoldingSetNodeID &id) const { 1246 id.AddInteger(Flags.getBitMask()); 1247 } 1248 }; 1249 1250 /// Emits the copy/dispose helpers for a __block variable with a 1251 /// nontrivial copy constructor or destructor. 1252 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers { 1253 QualType VarType; 1254 const Expr *CopyExpr; 1255 1256 public: 1257 CXXByrefHelpers(CharUnits alignment, QualType type, 1258 const Expr *copyExpr) 1259 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {} 1260 1261 bool needsCopy() const { return CopyExpr != 0; } 1262 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField, 1263 llvm::Value *srcField) { 1264 if (!CopyExpr) return; 1265 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr); 1266 } 1267 1268 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) { 1269 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin(); 1270 CGF.PushDestructorCleanup(VarType, field); 1271 CGF.PopCleanupBlocks(cleanupDepth); 1272 } 1273 1274 void profileImpl(llvm::FoldingSetNodeID &id) const { 1275 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr()); 1276 } 1277 }; 1278 } // end anonymous namespace 1279 1280 static llvm::Constant * 1281 generateByrefCopyHelper(CodeGenFunction &CGF, 1282 const llvm::StructType &byrefType, 1283 CodeGenModule::ByrefHelpers &byrefInfo) { 1284 ASTContext &Context = CGF.getContext(); 1285 1286 QualType R = Context.VoidTy; 1287 1288 FunctionArgList args; 1289 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy); 1290 args.push_back(&dst); 1291 1292 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy); 1293 args.push_back(&src); 1294 1295 const CGFunctionInfo &FI = 1296 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo()); 1297 1298 CodeGenTypes &Types = CGF.CGM.getTypes(); 1299 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false); 1300 1301 // FIXME: We'd like to put these into a mergable by content, with 1302 // internal linkage. 1303 llvm::Function *Fn = 1304 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 1305 "__Block_byref_object_copy_", &CGF.CGM.getModule()); 1306 1307 IdentifierInfo *II 1308 = &Context.Idents.get("__Block_byref_object_copy_"); 1309 1310 FunctionDecl *FD = FunctionDecl::Create(Context, 1311 Context.getTranslationUnitDecl(), 1312 SourceLocation(), 1313 SourceLocation(), II, R, 0, 1314 SC_Static, 1315 SC_None, 1316 false, true); 1317 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation()); 1318 1319 if (byrefInfo.needsCopy()) { 1320 const llvm::Type *byrefPtrType = byrefType.getPointerTo(0); 1321 1322 // dst->x 1323 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst); 1324 destField = CGF.Builder.CreateLoad(destField); 1325 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType); 1326 destField = CGF.Builder.CreateStructGEP(destField, 6, "x"); 1327 1328 // src->x 1329 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src); 1330 srcField = CGF.Builder.CreateLoad(srcField); 1331 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType); 1332 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x"); 1333 1334 byrefInfo.emitCopy(CGF, destField, srcField); 1335 } 1336 1337 CGF.FinishFunction(); 1338 1339 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy); 1340 } 1341 1342 /// Build the copy helper for a __block variable. 1343 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM, 1344 const llvm::StructType &byrefType, 1345 CodeGenModule::ByrefHelpers &info) { 1346 CodeGenFunction CGF(CGM); 1347 return generateByrefCopyHelper(CGF, byrefType, info); 1348 } 1349 1350 /// Generate code for a __block variable's dispose helper. 1351 static llvm::Constant * 1352 generateByrefDisposeHelper(CodeGenFunction &CGF, 1353 const llvm::StructType &byrefType, 1354 CodeGenModule::ByrefHelpers &byrefInfo) { 1355 ASTContext &Context = CGF.getContext(); 1356 QualType R = Context.VoidTy; 1357 1358 FunctionArgList args; 1359 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy); 1360 args.push_back(&src); 1361 1362 const CGFunctionInfo &FI = 1363 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo()); 1364 1365 CodeGenTypes &Types = CGF.CGM.getTypes(); 1366 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false); 1367 1368 // FIXME: We'd like to put these into a mergable by content, with 1369 // internal linkage. 1370 llvm::Function *Fn = 1371 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 1372 "__Block_byref_object_dispose_", 1373 &CGF.CGM.getModule()); 1374 1375 IdentifierInfo *II 1376 = &Context.Idents.get("__Block_byref_object_dispose_"); 1377 1378 FunctionDecl *FD = FunctionDecl::Create(Context, 1379 Context.getTranslationUnitDecl(), 1380 SourceLocation(), 1381 SourceLocation(), II, R, 0, 1382 SC_Static, 1383 SC_None, 1384 false, true); 1385 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation()); 1386 1387 if (byrefInfo.needsDispose()) { 1388 llvm::Value *V = CGF.GetAddrOfLocalVar(&src); 1389 V = CGF.Builder.CreateLoad(V); 1390 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0)); 1391 V = CGF.Builder.CreateStructGEP(V, 6, "x"); 1392 1393 byrefInfo.emitDispose(CGF, V); 1394 } 1395 1396 CGF.FinishFunction(); 1397 1398 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy); 1399 } 1400 1401 /// Build the dispose helper for a __block variable. 1402 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM, 1403 const llvm::StructType &byrefType, 1404 CodeGenModule::ByrefHelpers &info) { 1405 CodeGenFunction CGF(CGM); 1406 return generateByrefDisposeHelper(CGF, byrefType, info); 1407 } 1408 1409 /// 1410 template <class T> static T *buildByrefHelpers(CodeGenModule &CGM, 1411 const llvm::StructType &byrefTy, 1412 T &byrefInfo) { 1413 // Increase the field's alignment to be at least pointer alignment, 1414 // since the layout of the byref struct will guarantee at least that. 1415 byrefInfo.Alignment = std::max(byrefInfo.Alignment, 1416 CharUnits::fromQuantity(CGM.PointerAlignInBytes)); 1417 1418 llvm::FoldingSetNodeID id; 1419 byrefInfo.Profile(id); 1420 1421 void *insertPos; 1422 CodeGenModule::ByrefHelpers *node 1423 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos); 1424 if (node) return static_cast<T*>(node); 1425 1426 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo); 1427 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo); 1428 1429 T *copy = new (CGM.getContext()) T(byrefInfo); 1430 CGM.ByrefHelpersCache.InsertNode(copy, insertPos); 1431 return copy; 1432 } 1433 1434 CodeGenModule::ByrefHelpers * 1435 CodeGenFunction::buildByrefHelpers(const llvm::StructType &byrefType, 1436 const AutoVarEmission &emission) { 1437 const VarDecl &var = *emission.Variable; 1438 QualType type = var.getType(); 1439 1440 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) { 1441 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var); 1442 if (!copyExpr && record->hasTrivialDestructor()) return 0; 1443 1444 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr); 1445 return ::buildByrefHelpers(CGM, byrefType, byrefInfo); 1446 } 1447 1448 BlockFieldFlags flags; 1449 if (type->isBlockPointerType()) { 1450 flags |= BLOCK_FIELD_IS_BLOCK; 1451 } else if (CGM.getContext().isObjCNSObjectType(type) || 1452 type->isObjCObjectPointerType()) { 1453 flags |= BLOCK_FIELD_IS_OBJECT; 1454 } else { 1455 return 0; 1456 } 1457 1458 if (type.isObjCGCWeak()) 1459 flags |= BLOCK_FIELD_IS_WEAK; 1460 1461 ObjectByrefHelpers byrefInfo(emission.Alignment, flags); 1462 return ::buildByrefHelpers(CGM, byrefType, byrefInfo); 1463 } 1464 1465 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const { 1466 assert(ByRefValueInfo.count(VD) && "Did not find value!"); 1467 1468 return ByRefValueInfo.find(VD)->second.second; 1469 } 1470 1471 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr, 1472 const VarDecl *V) { 1473 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding"); 1474 Loc = Builder.CreateLoad(Loc); 1475 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V), 1476 V->getNameAsString()); 1477 return Loc; 1478 } 1479 1480 /// BuildByRefType - This routine changes a __block variable declared as T x 1481 /// into: 1482 /// 1483 /// struct { 1484 /// void *__isa; 1485 /// void *__forwarding; 1486 /// int32_t __flags; 1487 /// int32_t __size; 1488 /// void *__copy_helper; // only if needed 1489 /// void *__destroy_helper; // only if needed 1490 /// char padding[X]; // only if needed 1491 /// T x; 1492 /// } x 1493 /// 1494 const llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) { 1495 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D]; 1496 if (Info.first) 1497 return Info.first; 1498 1499 QualType Ty = D->getType(); 1500 1501 llvm::SmallVector<const llvm::Type *, 8> types; 1502 1503 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(getLLVMContext()); 1504 1505 // void *__isa; 1506 types.push_back(Int8PtrTy); 1507 1508 // void *__forwarding; 1509 types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder)); 1510 1511 // int32_t __flags; 1512 types.push_back(Int32Ty); 1513 1514 // int32_t __size; 1515 types.push_back(Int32Ty); 1516 1517 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty); 1518 if (HasCopyAndDispose) { 1519 /// void *__copy_helper; 1520 types.push_back(Int8PtrTy); 1521 1522 /// void *__destroy_helper; 1523 types.push_back(Int8PtrTy); 1524 } 1525 1526 bool Packed = false; 1527 CharUnits Align = getContext().getDeclAlign(D); 1528 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) { 1529 // We have to insert padding. 1530 1531 // The struct above has 2 32-bit integers. 1532 unsigned CurrentOffsetInBytes = 4 * 2; 1533 1534 // And either 2 or 4 pointers. 1535 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) * 1536 CGM.getTargetData().getTypeAllocSize(Int8PtrTy); 1537 1538 // Align the offset. 1539 unsigned AlignedOffsetInBytes = 1540 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity()); 1541 1542 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes; 1543 if (NumPaddingBytes > 0) { 1544 const llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext()); 1545 // FIXME: We need a sema error for alignment larger than the minimum of 1546 // the maximal stack alignment and the alignment of malloc on the system. 1547 if (NumPaddingBytes > 1) 1548 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes); 1549 1550 types.push_back(Ty); 1551 1552 // We want a packed struct. 1553 Packed = true; 1554 } 1555 } 1556 1557 // T x; 1558 types.push_back(ConvertTypeForMem(Ty)); 1559 1560 const llvm::Type *T = llvm::StructType::get(getLLVMContext(), types, Packed); 1561 1562 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T); 1563 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(), 1564 ByRefTypeHolder.get()); 1565 1566 Info.first = ByRefTypeHolder.get(); 1567 1568 Info.second = types.size() - 1; 1569 1570 return Info.first; 1571 } 1572 1573 /// Initialize the structural components of a __block variable, i.e. 1574 /// everything but the actual object. 1575 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) { 1576 // Find the address of the local. 1577 llvm::Value *addr = emission.Address; 1578 1579 // That's an alloca of the byref structure type. 1580 const llvm::StructType *byrefType = cast<llvm::StructType>( 1581 cast<llvm::PointerType>(addr->getType())->getElementType()); 1582 1583 // Build the byref helpers if necessary. This is null if we don't need any. 1584 CodeGenModule::ByrefHelpers *helpers = 1585 buildByrefHelpers(*byrefType, emission); 1586 1587 const VarDecl &D = *emission.Variable; 1588 QualType type = D.getType(); 1589 1590 llvm::Value *V; 1591 1592 // Initialize the 'isa', which is just 0 or 1. 1593 int isa = 0; 1594 if (type.isObjCGCWeak()) 1595 isa = 1; 1596 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa"); 1597 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa")); 1598 1599 // Store the address of the variable into its own forwarding pointer. 1600 Builder.CreateStore(addr, 1601 Builder.CreateStructGEP(addr, 1, "byref.forwarding")); 1602 1603 // Blocks ABI: 1604 // c) the flags field is set to either 0 if no helper functions are 1605 // needed or BLOCK_HAS_COPY_DISPOSE if they are, 1606 BlockFlags flags; 1607 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE; 1608 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()), 1609 Builder.CreateStructGEP(addr, 2, "byref.flags")); 1610 1611 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType); 1612 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity()); 1613 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size")); 1614 1615 if (helpers) { 1616 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4); 1617 Builder.CreateStore(helpers->CopyHelper, copy_helper); 1618 1619 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5); 1620 Builder.CreateStore(helpers->DisposeHelper, destroy_helper); 1621 } 1622 } 1623 1624 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) { 1625 llvm::Value *F = CGM.getBlockObjectDispose(); 1626 llvm::Value *N; 1627 V = Builder.CreateBitCast(V, Int8PtrTy); 1628 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask()); 1629 Builder.CreateCall2(F, V, N); 1630 } 1631 1632 namespace { 1633 struct CallBlockRelease : EHScopeStack::Cleanup { 1634 llvm::Value *Addr; 1635 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {} 1636 1637 void Emit(CodeGenFunction &CGF, bool IsForEH) { 1638 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF); 1639 } 1640 }; 1641 } 1642 1643 /// Enter a cleanup to destroy a __block variable. Note that this 1644 /// cleanup should be a no-op if the variable hasn't left the stack 1645 /// yet; if a cleanup is required for the variable itself, that needs 1646 /// to be done externally. 1647 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) { 1648 // We don't enter this cleanup if we're in pure-GC mode. 1649 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) 1650 return; 1651 1652 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address); 1653 } 1654