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