CGDecl.cpp revision 8b752f10c394b140f9ef89e049cbad1a7676fc25
1//===--- CGDecl.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 Decl nodes as LLVM code. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CGDebugInfo.h" 15#include "CodeGenFunction.h" 16#include "CodeGenModule.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/CharUnits.h" 19#include "clang/AST/Decl.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/Basic/SourceManager.h" 22#include "clang/Basic/TargetInfo.h" 23#include "clang/CodeGen/CodeGenOptions.h" 24#include "llvm/GlobalVariable.h" 25#include "llvm/Intrinsics.h" 26#include "llvm/Target/TargetData.h" 27#include "llvm/Type.h" 28using namespace clang; 29using namespace CodeGen; 30 31 32void CodeGenFunction::EmitDecl(const Decl &D) { 33 switch (D.getKind()) { 34 default: 35 CGM.ErrorUnsupported(&D, "decl"); 36 return; 37 case Decl::ParmVar: 38 assert(0 && "Parmdecls should not be in declstmts!"); 39 case Decl::Function: // void X(); 40 case Decl::Record: // struct/union/class X; 41 case Decl::Enum: // enum X; 42 case Decl::EnumConstant: // enum ? { X = ? } 43 case Decl::CXXRecord: // struct/union/class X; [C++] 44 case Decl::Using: // using X; [C++] 45 case Decl::UsingShadow: 46 case Decl::UsingDirective: // using namespace X; [C++] 47 case Decl::StaticAssert: // static_assert(X, ""); [C++0x] 48 // None of these decls require codegen support. 49 return; 50 51 case Decl::Var: { 52 const VarDecl &VD = cast<VarDecl>(D); 53 assert(VD.isBlockVarDecl() && 54 "Should not see file-scope variables inside a function!"); 55 return EmitBlockVarDecl(VD); 56 } 57 58 case Decl::Typedef: { // typedef int X; 59 const TypedefDecl &TD = cast<TypedefDecl>(D); 60 QualType Ty = TD.getUnderlyingType(); 61 62 if (Ty->isVariablyModifiedType()) 63 EmitVLASize(Ty); 64 } 65 } 66} 67 68/// EmitBlockVarDecl - This method handles emission of any variable declaration 69/// inside a function, including static vars etc. 70void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) { 71 if (D.hasAttr<AsmLabelAttr>()) 72 CGM.ErrorUnsupported(&D, "__asm__"); 73 74 switch (D.getStorageClass()) { 75 case VarDecl::None: 76 case VarDecl::Auto: 77 case VarDecl::Register: 78 return EmitLocalBlockVarDecl(D); 79 case VarDecl::Static: 80 return EmitStaticBlockVarDecl(D); 81 case VarDecl::Extern: 82 case VarDecl::PrivateExtern: 83 // Don't emit it now, allow it to be emitted lazily on its first use. 84 return; 85 } 86 87 assert(0 && "Unknown storage class"); 88} 89 90static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D, 91 const char *Separator) { 92 CodeGenModule &CGM = CGF.CGM; 93 if (CGF.getContext().getLangOptions().CPlusPlus) 94 return CGM.getMangledName(&D); 95 96 std::string ContextName; 97 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) 98 ContextName = CGM.getMangledName(FD); 99 else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) 100 ContextName = CGF.CurFn->getName(); 101 else 102 // FIXME: What about in a block?? 103 assert(0 && "Unknown context for block var decl"); 104 105 return ContextName + Separator + D.getNameAsString(); 106} 107 108llvm::GlobalVariable * 109CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D, 110 const char *Separator, 111 llvm::GlobalValue::LinkageTypes Linkage) { 112 QualType Ty = D.getType(); 113 assert(Ty->isConstantSizeType() && "VLAs can't be static"); 114 115 std::string Name = GetStaticDeclName(*this, D, Separator); 116 117 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty); 118 llvm::GlobalVariable *GV = 119 new llvm::GlobalVariable(CGM.getModule(), LTy, 120 Ty.isConstant(getContext()), Linkage, 121 CGM.EmitNullConstant(D.getType()), Name, 0, 122 D.isThreadSpecified(), Ty.getAddressSpace()); 123 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 124 return GV; 125} 126 127/// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the 128/// global variable that has already been created for it. If the initializer 129/// has a different type than GV does, this may free GV and return a different 130/// one. Otherwise it just returns GV. 131llvm::GlobalVariable * 132CodeGenFunction::AddInitializerToGlobalBlockVarDecl(const VarDecl &D, 133 llvm::GlobalVariable *GV) { 134 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this); 135 136 // If constant emission failed, then this should be a C++ static 137 // initializer. 138 if (!Init) { 139 if (!getContext().getLangOptions().CPlusPlus) 140 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression"); 141 else { 142 // Since we have a static initializer, this global variable can't 143 // be constant. 144 GV->setConstant(false); 145 146 EmitStaticCXXBlockVarDeclInit(D, GV); 147 } 148 return GV; 149 } 150 151 // The initializer may differ in type from the global. Rewrite 152 // the global to match the initializer. (We have to do this 153 // because some types, like unions, can't be completely represented 154 // in the LLVM type system.) 155 if (GV->getType() != Init->getType()) { 156 llvm::GlobalVariable *OldGV = GV; 157 158 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 159 OldGV->isConstant(), 160 OldGV->getLinkage(), Init, "", 161 0, D.isThreadSpecified(), 162 D.getType().getAddressSpace()); 163 164 // Steal the name of the old global 165 GV->takeName(OldGV); 166 167 // Replace all uses of the old global with the new global 168 llvm::Constant *NewPtrForOldDecl = 169 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 170 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 171 172 // Erase the old global, since it is no longer used. 173 OldGV->eraseFromParent(); 174 } 175 176 GV->setInitializer(Init); 177 return GV; 178} 179 180void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) { 181 llvm::Value *&DMEntry = LocalDeclMap[&D]; 182 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 183 184 llvm::GlobalVariable *GV = 185 CreateStaticBlockVarDecl(D, ".", llvm::GlobalValue::InternalLinkage); 186 187 // Store into LocalDeclMap before generating initializer to handle 188 // circular references. 189 DMEntry = GV; 190 191 // Make sure to evaluate VLA bounds now so that we have them for later. 192 // 193 // FIXME: Can this happen? 194 if (D.getType()->isVariablyModifiedType()) 195 EmitVLASize(D.getType()); 196 197 // If this value has an initializer, emit it. 198 if (D.getInit()) 199 GV = AddInitializerToGlobalBlockVarDecl(D, GV); 200 201 // FIXME: Merge attribute handling. 202 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) { 203 SourceManager &SM = CGM.getContext().getSourceManager(); 204 llvm::Constant *Ann = 205 CGM.EmitAnnotateAttr(GV, AA, 206 SM.getInstantiationLineNumber(D.getLocation())); 207 CGM.AddAnnotation(Ann); 208 } 209 210 if (const SectionAttr *SA = D.getAttr<SectionAttr>()) 211 GV->setSection(SA->getName()); 212 213 if (D.hasAttr<UsedAttr>()) 214 CGM.AddUsedGlobal(GV); 215 216 // We may have to cast the constant because of the initializer 217 // mismatch above. 218 // 219 // FIXME: It is really dangerous to store this in the map; if anyone 220 // RAUW's the GV uses of this constant will be invalid. 221 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType()); 222 const llvm::Type *LPtrTy = 223 llvm::PointerType::get(LTy, D.getType().getAddressSpace()); 224 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy); 225 226 // Emit global variable debug descriptor for static vars. 227 CGDebugInfo *DI = getDebugInfo(); 228 if (DI) { 229 DI->setLocation(D.getLocation()); 230 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D); 231 } 232} 233 234unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const { 235 assert(ByRefValueInfo.count(VD) && "Did not find value!"); 236 237 return ByRefValueInfo.find(VD)->second.second; 238} 239 240/// BuildByRefType - This routine changes a __block variable declared as T x 241/// into: 242/// 243/// struct { 244/// void *__isa; 245/// void *__forwarding; 246/// int32_t __flags; 247/// int32_t __size; 248/// void *__copy_helper; // only if needed 249/// void *__destroy_helper; // only if needed 250/// char padding[X]; // only if needed 251/// T x; 252/// } x 253/// 254const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) { 255 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D]; 256 if (Info.first) 257 return Info.first; 258 259 QualType Ty = D->getType(); 260 261 std::vector<const llvm::Type *> Types; 262 263 const llvm::PointerType *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext); 264 265 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(VMContext); 266 267 // void *__isa; 268 Types.push_back(Int8PtrTy); 269 270 // void *__forwarding; 271 Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder)); 272 273 // int32_t __flags; 274 Types.push_back(llvm::Type::getInt32Ty(VMContext)); 275 276 // int32_t __size; 277 Types.push_back(llvm::Type::getInt32Ty(VMContext)); 278 279 bool HasCopyAndDispose = BlockRequiresCopying(Ty); 280 if (HasCopyAndDispose) { 281 /// void *__copy_helper; 282 Types.push_back(Int8PtrTy); 283 284 /// void *__destroy_helper; 285 Types.push_back(Int8PtrTy); 286 } 287 288 bool Packed = false; 289 CharUnits Align = getContext().getDeclAlign(D); 290 if (Align > CharUnits::fromQuantity(Target.getPointerAlign(0) / 8)) { 291 // We have to insert padding. 292 293 // The struct above has 2 32-bit integers. 294 unsigned CurrentOffsetInBytes = 4 * 2; 295 296 // And either 2 or 4 pointers. 297 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) * 298 CGM.getTargetData().getTypeAllocSize(Int8PtrTy); 299 300 // Align the offset. 301 unsigned AlignedOffsetInBytes = 302 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity()); 303 304 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes; 305 if (NumPaddingBytes > 0) { 306 const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext); 307 // FIXME: We need a sema error for alignment larger than the minimum of 308 // the maximal stack alignmint and the alignment of malloc on the system. 309 if (NumPaddingBytes > 1) 310 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes); 311 312 Types.push_back(Ty); 313 314 // We want a packed struct. 315 Packed = true; 316 } 317 } 318 319 // T x; 320 Types.push_back(ConvertType(Ty)); 321 322 const llvm::Type *T = llvm::StructType::get(VMContext, Types, Packed); 323 324 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T); 325 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(), 326 ByRefTypeHolder.get()); 327 328 Info.first = ByRefTypeHolder.get(); 329 330 Info.second = Types.size() - 1; 331 332 return Info.first; 333} 334 335/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a 336/// variable declaration with auto, register, or no storage class specifier. 337/// These turn into simple stack objects, or GlobalValues depending on target. 338void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { 339 QualType Ty = D.getType(); 340 bool isByRef = D.hasAttr<BlocksAttr>(); 341 bool needsDispose = false; 342 CharUnits Align = CharUnits::Zero(); 343 bool IsSimpleConstantInitializer = false; 344 345 llvm::Value *DeclPtr; 346 if (Ty->isConstantSizeType()) { 347 if (!Target.useGlobalsForAutomaticVariables()) { 348 349 // If this value is an array or struct, is POD, and if the initializer is 350 // a staticly determinable constant, try to optimize it. 351 if (D.getInit() && !isByRef && 352 (Ty->isArrayType() || Ty->isRecordType()) && 353 Ty->isPODType() && 354 D.getInit()->isConstantInitializer(getContext())) { 355 // If this variable is marked 'const', emit the value as a global. 356 if (CGM.getCodeGenOpts().MergeAllConstants && 357 Ty.isConstant(getContext())) { 358 EmitStaticBlockVarDecl(D); 359 return; 360 } 361 362 IsSimpleConstantInitializer = true; 363 } 364 365 // A normal fixed sized variable becomes an alloca in the entry block. 366 const llvm::Type *LTy = ConvertTypeForMem(Ty); 367 if (isByRef) 368 LTy = BuildByRefType(&D); 369 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy); 370 Alloc->setName(D.getNameAsString()); 371 372 Align = getContext().getDeclAlign(&D); 373 if (isByRef) 374 Align = std::max(Align, 375 CharUnits::fromQuantity(Target.getPointerAlign(0) / 8)); 376 Alloc->setAlignment(Align.getQuantity()); 377 DeclPtr = Alloc; 378 } else { 379 // Targets that don't support recursion emit locals as globals. 380 const char *Class = 381 D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto."; 382 DeclPtr = CreateStaticBlockVarDecl(D, Class, 383 llvm::GlobalValue 384 ::InternalLinkage); 385 } 386 387 // FIXME: Can this happen? 388 if (Ty->isVariablyModifiedType()) 389 EmitVLASize(Ty); 390 } else { 391 EnsureInsertPoint(); 392 393 if (!DidCallStackSave) { 394 // Save the stack. 395 const llvm::Type *LTy = llvm::Type::getInt8PtrTy(VMContext); 396 llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack"); 397 398 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 399 llvm::Value *V = Builder.CreateCall(F); 400 401 Builder.CreateStore(V, Stack); 402 403 DidCallStackSave = true; 404 405 { 406 // Push a cleanup block and restore the stack there. 407 DelayedCleanupBlock scope(*this); 408 409 V = Builder.CreateLoad(Stack, "tmp"); 410 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 411 Builder.CreateCall(F, V); 412 } 413 } 414 415 // Get the element type. 416 const llvm::Type *LElemTy = ConvertTypeForMem(Ty); 417 const llvm::Type *LElemPtrTy = 418 llvm::PointerType::get(LElemTy, D.getType().getAddressSpace()); 419 420 llvm::Value *VLASize = EmitVLASize(Ty); 421 422 // Downcast the VLA size expression 423 VLASize = Builder.CreateIntCast(VLASize, llvm::Type::getInt32Ty(VMContext), 424 false, "tmp"); 425 426 // Allocate memory for the array. 427 llvm::AllocaInst *VLA = 428 Builder.CreateAlloca(llvm::Type::getInt8Ty(VMContext), VLASize, "vla"); 429 VLA->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 430 431 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp"); 432 } 433 434 llvm::Value *&DMEntry = LocalDeclMap[&D]; 435 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 436 DMEntry = DeclPtr; 437 438 // Emit debug info for local var declaration. 439 if (CGDebugInfo *DI = getDebugInfo()) { 440 assert(HaveInsertPoint() && "Unexpected unreachable point!"); 441 442 DI->setLocation(D.getLocation()); 443 if (Target.useGlobalsForAutomaticVariables()) { 444 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D); 445 } else 446 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder); 447 } 448 449 // If this local has an initializer, emit it now. 450 const Expr *Init = D.getInit(); 451 452 // If we are at an unreachable point, we don't need to emit the initializer 453 // unless it contains a label. 454 if (!HaveInsertPoint()) { 455 if (!ContainsLabel(Init)) 456 Init = 0; 457 else 458 EnsureInsertPoint(); 459 } 460 461 if (Init) { 462 llvm::Value *Loc = DeclPtr; 463 if (isByRef) 464 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D), 465 D.getNameAsString()); 466 467 bool isVolatile = 468 getContext().getCanonicalType(D.getType()).isVolatileQualified(); 469 470 // If the initializer was a simple constant initializer, we can optimize it 471 // in various ways. 472 if (IsSimpleConstantInitializer) { 473 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(),D.getType(),this); 474 assert(Init != 0 && "Wasn't a simple constant init?"); 475 476 llvm::Value *AlignVal = 477 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 478 Align.getQuantity()); 479 const llvm::Type *IntPtr = 480 llvm::IntegerType::get(VMContext, LLVMPointerWidth); 481 llvm::Value *SizeVal = 482 llvm::ConstantInt::get(IntPtr, 483 getContext().getTypeSizeInChars(Ty).getQuantity()); 484 485 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 486 if (Loc->getType() != BP) 487 Loc = Builder.CreateBitCast(Loc, BP, "tmp"); 488 489 // If the initializer is all zeros, codegen with memset. 490 if (isa<llvm::ConstantAggregateZero>(Init)) { 491 llvm::Value *Zero = 492 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 0); 493 Builder.CreateCall4(CGM.getMemSetFn(), Loc, Zero, SizeVal, AlignVal); 494 } else { 495 // Otherwise, create a temporary global with the initializer then 496 // memcpy from the global to the alloca. 497 std::string Name = GetStaticDeclName(*this, D, "."); 498 llvm::GlobalVariable *GV = 499 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), true, 500 llvm::GlobalValue::InternalLinkage, 501 Init, Name, 0, false, 0); 502 GV->setAlignment(Align.getQuantity()); 503 504 llvm::Value *SrcPtr = GV; 505 if (SrcPtr->getType() != BP) 506 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 507 508 Builder.CreateCall4(CGM.getMemCpyFn(), Loc, SrcPtr, SizeVal, AlignVal); 509 } 510 } else if (Ty->isReferenceType()) { 511 RValue RV = EmitReferenceBindingToExpr(Init, Ty, /*IsInitializer=*/true); 512 EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Ty); 513 } else if (!hasAggregateLLVMType(Init->getType())) { 514 llvm::Value *V = EmitScalarExpr(Init); 515 EmitStoreOfScalar(V, Loc, isVolatile, D.getType()); 516 } else if (Init->getType()->isAnyComplexType()) { 517 EmitComplexExprIntoAddr(Init, Loc, isVolatile); 518 } else { 519 EmitAggExpr(Init, Loc, isVolatile); 520 } 521 } 522 523 if (isByRef) { 524 const llvm::PointerType *PtrToInt8Ty = llvm::Type::getInt8PtrTy(VMContext); 525 526 EnsureInsertPoint(); 527 llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0); 528 llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1); 529 llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2); 530 llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3); 531 llvm::Value *V; 532 int flag = 0; 533 int flags = 0; 534 535 needsDispose = true; 536 537 if (Ty->isBlockPointerType()) { 538 flag |= BLOCK_FIELD_IS_BLOCK; 539 flags |= BLOCK_HAS_COPY_DISPOSE; 540 } else if (BlockRequiresCopying(Ty)) { 541 flag |= BLOCK_FIELD_IS_OBJECT; 542 flags |= BLOCK_HAS_COPY_DISPOSE; 543 } 544 545 // FIXME: Someone double check this. 546 if (Ty.isObjCGCWeak()) 547 flag |= BLOCK_FIELD_IS_WEAK; 548 549 int isa = 0; 550 if (flag&BLOCK_FIELD_IS_WEAK) 551 isa = 1; 552 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), isa); 553 V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa"); 554 Builder.CreateStore(V, isa_field); 555 556 Builder.CreateStore(DeclPtr, forwarding_field); 557 558 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), flags); 559 Builder.CreateStore(V, flags_field); 560 561 const llvm::Type *V1; 562 V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType(); 563 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 564 CGM.GetTargetTypeStoreSize(V1).getQuantity()); 565 Builder.CreateStore(V, size_field); 566 567 if (flags & BLOCK_HAS_COPY_DISPOSE) { 568 BlockHasCopyDispose = true; 569 llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4); 570 Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag, 571 Align.getQuantity()), 572 copy_helper); 573 574 llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5); 575 Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag, 576 Align.getQuantity()), 577 destroy_helper); 578 } 579 } 580 581 // Handle CXX destruction of variables. 582 QualType DtorTy(Ty); 583 while (const ArrayType *Array = getContext().getAsArrayType(DtorTy)) 584 DtorTy = getContext().getBaseElementType(Array); 585 if (const RecordType *RT = DtorTy->getAs<RecordType>()) 586 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 587 if (!ClassDecl->hasTrivialDestructor()) { 588 const CXXDestructorDecl *D = ClassDecl->getDestructor(getContext()); 589 assert(D && "EmitLocalBlockVarDecl - destructor is nul"); 590 591 if (const ConstantArrayType *Array = 592 getContext().getAsConstantArrayType(Ty)) { 593 { 594 DelayedCleanupBlock Scope(*this); 595 QualType BaseElementTy = getContext().getBaseElementType(Array); 596 const llvm::Type *BasePtr = ConvertType(BaseElementTy); 597 BasePtr = llvm::PointerType::getUnqual(BasePtr); 598 llvm::Value *BaseAddrPtr = 599 Builder.CreateBitCast(DeclPtr, BasePtr); 600 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr); 601 602 // Make sure to jump to the exit block. 603 EmitBranch(Scope.getCleanupExitBlock()); 604 } 605 if (Exceptions) { 606 EHCleanupBlock Cleanup(*this); 607 QualType BaseElementTy = getContext().getBaseElementType(Array); 608 const llvm::Type *BasePtr = ConvertType(BaseElementTy); 609 BasePtr = llvm::PointerType::getUnqual(BasePtr); 610 llvm::Value *BaseAddrPtr = 611 Builder.CreateBitCast(DeclPtr, BasePtr); 612 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr); 613 } 614 } else { 615 { 616 DelayedCleanupBlock Scope(*this); 617 EmitCXXDestructorCall(D, Dtor_Complete, DeclPtr); 618 619 // Make sure to jump to the exit block. 620 EmitBranch(Scope.getCleanupExitBlock()); 621 } 622 if (Exceptions) { 623 EHCleanupBlock Cleanup(*this); 624 EmitCXXDestructorCall(D, Dtor_Complete, DeclPtr); 625 } 626 } 627 } 628 } 629 630 // Handle the cleanup attribute 631 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 632 const FunctionDecl *FD = CA->getFunctionDecl(); 633 634 llvm::Constant* F = CGM.GetAddrOfFunction(FD); 635 assert(F && "Could not find function!"); 636 637 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD); 638 639 // In some cases, the type of the function argument will be different from 640 // the type of the pointer. An example of this is 641 // void f(void* arg); 642 // __attribute__((cleanup(f))) void *g; 643 // 644 // To fix this we insert a bitcast here. 645 QualType ArgTy = Info.arg_begin()->type; 646 { 647 DelayedCleanupBlock scope(*this); 648 649 CallArgList Args; 650 Args.push_back(std::make_pair(RValue::get(Builder.CreateBitCast(DeclPtr, 651 ConvertType(ArgTy))), 652 getContext().getPointerType(D.getType()))); 653 EmitCall(Info, F, ReturnValueSlot(), Args); 654 } 655 if (Exceptions) { 656 EHCleanupBlock Cleanup(*this); 657 658 CallArgList Args; 659 Args.push_back(std::make_pair(RValue::get(Builder.CreateBitCast(DeclPtr, 660 ConvertType(ArgTy))), 661 getContext().getPointerType(D.getType()))); 662 EmitCall(Info, F, ReturnValueSlot(), Args); 663 } 664 } 665 666 if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly) { 667 { 668 DelayedCleanupBlock scope(*this); 669 llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding"); 670 V = Builder.CreateLoad(V); 671 BuildBlockRelease(V); 672 } 673 // FIXME: Turn this on and audit the codegen 674 if (0 && Exceptions) { 675 EHCleanupBlock Cleanup(*this); 676 llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding"); 677 V = Builder.CreateLoad(V); 678 BuildBlockRelease(V); 679 } 680 } 681} 682 683/// Emit an alloca (or GlobalValue depending on target) 684/// for the specified parameter and set up LocalDeclMap. 685void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) { 686 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 687 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 688 "Invalid argument to EmitParmDecl"); 689 QualType Ty = D.getType(); 690 CanQualType CTy = getContext().getCanonicalType(Ty); 691 692 llvm::Value *DeclPtr; 693 if (!Ty->isConstantSizeType()) { 694 // Variable sized values always are passed by-reference. 695 DeclPtr = Arg; 696 } else { 697 // A fixed sized single-value variable becomes an alloca in the entry block. 698 const llvm::Type *LTy = ConvertTypeForMem(Ty); 699 if (LTy->isSingleValueType()) { 700 // TODO: Alignment 701 DeclPtr = CreateTempAlloca(LTy); 702 DeclPtr->setName(D.getNameAsString() + llvm::StringRef(".addr")); 703 704 // Store the initial value into the alloca. 705 EmitStoreOfScalar(Arg, DeclPtr, CTy.isVolatileQualified(), Ty); 706 } else { 707 // Otherwise, if this is an aggregate, just use the input pointer. 708 DeclPtr = Arg; 709 } 710 Arg->setName(D.getNameAsString()); 711 } 712 713 llvm::Value *&DMEntry = LocalDeclMap[&D]; 714 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 715 DMEntry = DeclPtr; 716 717 // Emit debug info for param declaration. 718 if (CGDebugInfo *DI = getDebugInfo()) { 719 DI->setLocation(D.getLocation()); 720 DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder); 721 } 722} 723