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