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" 28 using namespace clang; 29 using namespace CodeGen; 30 31 32 void 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. 104 void 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 137 static 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 160 llvm::GlobalVariable * 161 CodeGenFunction::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. 183 llvm::GlobalVariable * 184 CodeGenFunction::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 232 void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D, 233 llvm::GlobalValue::LinkageTypes Linkage) { 234 llvm::Value *&DMEntry = LocalDeclMap[&D]; 235 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 236 237 llvm::GlobalVariable *GV = CreateStaticBlockVarDecl(D, ".", Linkage); 238 239 // Store into LocalDeclMap before generating initializer to handle 240 // circular references. 241 DMEntry = GV; 242 if (getContext().getLangOptions().CPlusPlus) 243 CGM.setStaticLocalDeclAddress(&D, GV); 244 245 // We can't have a VLA here, but we can have a pointer to a VLA, 246 // even though that doesn't really make any sense. 247 // Make sure to evaluate VLA bounds now so that we have them for later. 248 if (D.getType()->isVariablyModifiedType()) 249 EmitVLASize(D.getType()); 250 251 // If this value has an initializer, emit it. 252 if (D.getInit()) 253 GV = AddInitializerToGlobalBlockVarDecl(D, GV); 254 255 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 256 257 // FIXME: Merge attribute handling. 258 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) { 259 SourceManager &SM = CGM.getContext().getSourceManager(); 260 llvm::Constant *Ann = 261 CGM.EmitAnnotateAttr(GV, AA, 262 SM.getInstantiationLineNumber(D.getLocation())); 263 CGM.AddAnnotation(Ann); 264 } 265 266 if (const SectionAttr *SA = D.getAttr<SectionAttr>()) 267 GV->setSection(SA->getName()); 268 269 if (D.hasAttr<UsedAttr>()) 270 CGM.AddUsedGlobal(GV); 271 272 // We may have to cast the constant because of the initializer 273 // mismatch above. 274 // 275 // FIXME: It is really dangerous to store this in the map; if anyone 276 // RAUW's the GV uses of this constant will be invalid. 277 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType()); 278 const llvm::Type *LPtrTy = 279 llvm::PointerType::get(LTy, D.getType().getAddressSpace()); 280 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy); 281 282 // Emit global variable debug descriptor for static vars. 283 CGDebugInfo *DI = getDebugInfo(); 284 if (DI) { 285 DI->setLocation(D.getLocation()); 286 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D); 287 } 288 } 289 290 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const { 291 assert(ByRefValueInfo.count(VD) && "Did not find value!"); 292 293 return ByRefValueInfo.find(VD)->second.second; 294 } 295 296 /// BuildByRefType - This routine changes a __block variable declared as T x 297 /// into: 298 /// 299 /// struct { 300 /// void *__isa; 301 /// void *__forwarding; 302 /// int32_t __flags; 303 /// int32_t __size; 304 /// void *__copy_helper; // only if needed 305 /// void *__destroy_helper; // only if needed 306 /// char padding[X]; // only if needed 307 /// T x; 308 /// } x 309 /// 310 const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) { 311 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D]; 312 if (Info.first) 313 return Info.first; 314 315 QualType Ty = D->getType(); 316 317 std::vector<const llvm::Type *> Types; 318 319 const llvm::PointerType *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext); 320 321 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(VMContext); 322 323 // void *__isa; 324 Types.push_back(Int8PtrTy); 325 326 // void *__forwarding; 327 Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder)); 328 329 // int32_t __flags; 330 Types.push_back(llvm::Type::getInt32Ty(VMContext)); 331 332 // int32_t __size; 333 Types.push_back(llvm::Type::getInt32Ty(VMContext)); 334 335 bool HasCopyAndDispose = BlockRequiresCopying(Ty); 336 if (HasCopyAndDispose) { 337 /// void *__copy_helper; 338 Types.push_back(Int8PtrTy); 339 340 /// void *__destroy_helper; 341 Types.push_back(Int8PtrTy); 342 } 343 344 bool Packed = false; 345 CharUnits Align = getContext().getDeclAlign(D); 346 if (Align > CharUnits::fromQuantity(Target.getPointerAlign(0) / 8)) { 347 // We have to insert padding. 348 349 // The struct above has 2 32-bit integers. 350 unsigned CurrentOffsetInBytes = 4 * 2; 351 352 // And either 2 or 4 pointers. 353 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) * 354 CGM.getTargetData().getTypeAllocSize(Int8PtrTy); 355 356 // Align the offset. 357 unsigned AlignedOffsetInBytes = 358 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity()); 359 360 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes; 361 if (NumPaddingBytes > 0) { 362 const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext); 363 // FIXME: We need a sema error for alignment larger than the minimum of 364 // the maximal stack alignmint and the alignment of malloc on the system. 365 if (NumPaddingBytes > 1) 366 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes); 367 368 Types.push_back(Ty); 369 370 // We want a packed struct. 371 Packed = true; 372 } 373 } 374 375 // T x; 376 Types.push_back(ConvertType(Ty)); 377 378 const llvm::Type *T = llvm::StructType::get(VMContext, Types, Packed); 379 380 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T); 381 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(), 382 ByRefTypeHolder.get()); 383 384 Info.first = ByRefTypeHolder.get(); 385 386 Info.second = Types.size() - 1; 387 388 return Info.first; 389 } 390 391 /// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a 392 /// variable declaration with auto, register, or no storage class specifier. 393 /// These turn into simple stack objects, or GlobalValues depending on target. 394 void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { 395 QualType Ty = D.getType(); 396 bool isByRef = D.hasAttr<BlocksAttr>(); 397 bool needsDispose = false; 398 CharUnits Align = CharUnits::Zero(); 399 bool IsSimpleConstantInitializer = false; 400 401 llvm::Value *DeclPtr; 402 if (Ty->isConstantSizeType()) { 403 if (!Target.useGlobalsForAutomaticVariables()) { 404 405 // If this value is an array or struct, is POD, and if the initializer is 406 // a staticly determinable constant, try to optimize it. 407 if (D.getInit() && !isByRef && 408 (Ty->isArrayType() || Ty->isRecordType()) && 409 Ty->isPODType() && 410 D.getInit()->isConstantInitializer(getContext())) { 411 // If this variable is marked 'const', emit the value as a global. 412 if (CGM.getCodeGenOpts().MergeAllConstants && 413 Ty.isConstant(getContext())) { 414 EmitStaticBlockVarDecl(D, llvm::GlobalValue::InternalLinkage); 415 return; 416 } 417 418 IsSimpleConstantInitializer = true; 419 } 420 421 // A normal fixed sized variable becomes an alloca in the entry block. 422 const llvm::Type *LTy = ConvertTypeForMem(Ty); 423 if (isByRef) 424 LTy = BuildByRefType(&D); 425 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy); 426 Alloc->setName(D.getNameAsString()); 427 428 Align = getContext().getDeclAlign(&D); 429 if (isByRef) 430 Align = std::max(Align, 431 CharUnits::fromQuantity(Target.getPointerAlign(0) / 8)); 432 Alloc->setAlignment(Align.getQuantity()); 433 DeclPtr = Alloc; 434 } else { 435 // Targets that don't support recursion emit locals as globals. 436 const char *Class = 437 D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto."; 438 DeclPtr = CreateStaticBlockVarDecl(D, Class, 439 llvm::GlobalValue 440 ::InternalLinkage); 441 } 442 443 // FIXME: Can this happen? 444 if (Ty->isVariablyModifiedType()) 445 EmitVLASize(Ty); 446 } else { 447 EnsureInsertPoint(); 448 449 if (!DidCallStackSave) { 450 // Save the stack. 451 const llvm::Type *LTy = llvm::Type::getInt8PtrTy(VMContext); 452 llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack"); 453 454 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 455 llvm::Value *V = Builder.CreateCall(F); 456 457 Builder.CreateStore(V, Stack); 458 459 DidCallStackSave = true; 460 461 { 462 // Push a cleanup block and restore the stack there. 463 DelayedCleanupBlock scope(*this); 464 465 V = Builder.CreateLoad(Stack, "tmp"); 466 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 467 Builder.CreateCall(F, V); 468 } 469 } 470 471 // Get the element type. 472 const llvm::Type *LElemTy = ConvertTypeForMem(Ty); 473 const llvm::Type *LElemPtrTy = 474 llvm::PointerType::get(LElemTy, D.getType().getAddressSpace()); 475 476 llvm::Value *VLASize = EmitVLASize(Ty); 477 478 // Downcast the VLA size expression 479 VLASize = Builder.CreateIntCast(VLASize, llvm::Type::getInt32Ty(VMContext), 480 false, "tmp"); 481 482 // Allocate memory for the array. 483 llvm::AllocaInst *VLA = 484 Builder.CreateAlloca(llvm::Type::getInt8Ty(VMContext), VLASize, "vla"); 485 VLA->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 486 487 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp"); 488 } 489 490 llvm::Value *&DMEntry = LocalDeclMap[&D]; 491 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 492 DMEntry = DeclPtr; 493 494 // Emit debug info for local var declaration. 495 if (CGDebugInfo *DI = getDebugInfo()) { 496 assert(HaveInsertPoint() && "Unexpected unreachable point!"); 497 498 DI->setLocation(D.getLocation()); 499 if (Target.useGlobalsForAutomaticVariables()) { 500 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D); 501 } else 502 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder); 503 } 504 505 // If this local has an initializer, emit it now. 506 const Expr *Init = D.getInit(); 507 508 // If we are at an unreachable point, we don't need to emit the initializer 509 // unless it contains a label. 510 if (!HaveInsertPoint()) { 511 if (!ContainsLabel(Init)) 512 Init = 0; 513 else 514 EnsureInsertPoint(); 515 } 516 517 if (isByRef) { 518 const llvm::PointerType *PtrToInt8Ty = llvm::Type::getInt8PtrTy(VMContext); 519 520 EnsureInsertPoint(); 521 llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0); 522 llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1); 523 llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2); 524 llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3); 525 llvm::Value *V; 526 int flag = 0; 527 int flags = 0; 528 529 needsDispose = true; 530 531 if (Ty->isBlockPointerType()) { 532 flag |= BLOCK_FIELD_IS_BLOCK; 533 flags |= BLOCK_HAS_COPY_DISPOSE; 534 } else if (BlockRequiresCopying(Ty)) { 535 flag |= BLOCK_FIELD_IS_OBJECT; 536 flags |= BLOCK_HAS_COPY_DISPOSE; 537 } 538 539 // FIXME: Someone double check this. 540 if (Ty.isObjCGCWeak()) 541 flag |= BLOCK_FIELD_IS_WEAK; 542 543 int isa = 0; 544 if (flag&BLOCK_FIELD_IS_WEAK) 545 isa = 1; 546 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), isa); 547 V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa"); 548 Builder.CreateStore(V, isa_field); 549 550 Builder.CreateStore(DeclPtr, forwarding_field); 551 552 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), flags); 553 Builder.CreateStore(V, flags_field); 554 555 const llvm::Type *V1; 556 V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType(); 557 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 558 CGM.GetTargetTypeStoreSize(V1).getQuantity()); 559 Builder.CreateStore(V, size_field); 560 561 if (flags & BLOCK_HAS_COPY_DISPOSE) { 562 BlockHasCopyDispose = true; 563 llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4); 564 Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag, 565 Align.getQuantity()), 566 copy_helper); 567 568 llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5); 569 Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag, 570 Align.getQuantity()), 571 destroy_helper); 572 } 573 } 574 575 if (Init) { 576 llvm::Value *Loc = DeclPtr; 577 if (isByRef) 578 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D), 579 D.getNameAsString()); 580 581 bool isVolatile = 582 getContext().getCanonicalType(D.getType()).isVolatileQualified(); 583 584 // If the initializer was a simple constant initializer, we can optimize it 585 // in various ways. 586 if (IsSimpleConstantInitializer) { 587 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(),D.getType(),this); 588 assert(Init != 0 && "Wasn't a simple constant init?"); 589 590 llvm::Value *AlignVal = 591 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 592 Align.getQuantity()); 593 const llvm::Type *IntPtr = 594 llvm::IntegerType::get(VMContext, LLVMPointerWidth); 595 llvm::Value *SizeVal = 596 llvm::ConstantInt::get(IntPtr, 597 getContext().getTypeSizeInChars(Ty).getQuantity()); 598 599 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 600 if (Loc->getType() != BP) 601 Loc = Builder.CreateBitCast(Loc, BP, "tmp"); 602 603 llvm::Value *NotVolatile = 604 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), 0); 605 606 // If the initializer is all zeros, codegen with memset. 607 if (isa<llvm::ConstantAggregateZero>(Init)) { 608 llvm::Value *Zero = 609 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 0); 610 Builder.CreateCall5(CGM.getMemSetFn(Loc->getType(), SizeVal->getType()), 611 Loc, Zero, SizeVal, AlignVal, NotVolatile); 612 } else { 613 // Otherwise, create a temporary global with the initializer then 614 // memcpy from the global to the alloca. 615 std::string Name = GetStaticDeclName(*this, D, "."); 616 llvm::GlobalVariable *GV = 617 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), true, 618 llvm::GlobalValue::InternalLinkage, 619 Init, Name, 0, false, 0); 620 GV->setAlignment(Align.getQuantity()); 621 622 llvm::Value *SrcPtr = GV; 623 if (SrcPtr->getType() != BP) 624 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 625 626 Builder.CreateCall5(CGM.getMemCpyFn(Loc->getType(), SrcPtr->getType(), 627 SizeVal->getType()), 628 Loc, SrcPtr, SizeVal, AlignVal, NotVolatile); 629 } 630 } else if (Ty->isReferenceType()) { 631 RValue RV = EmitReferenceBindingToExpr(Init, /*IsInitializer=*/true); 632 EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Ty); 633 } else if (!hasAggregateLLVMType(Init->getType())) { 634 llvm::Value *V = EmitScalarExpr(Init); 635 EmitStoreOfScalar(V, Loc, isVolatile, D.getType()); 636 } else if (Init->getType()->isAnyComplexType()) { 637 EmitComplexExprIntoAddr(Init, Loc, isVolatile); 638 } else { 639 EmitAggExpr(Init, Loc, isVolatile); 640 } 641 } 642 643 // Handle CXX destruction of variables. 644 QualType DtorTy(Ty); 645 while (const ArrayType *Array = getContext().getAsArrayType(DtorTy)) 646 DtorTy = getContext().getBaseElementType(Array); 647 if (const RecordType *RT = DtorTy->getAs<RecordType>()) 648 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 649 llvm::Value *Loc = DeclPtr; 650 if (isByRef) 651 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D), 652 D.getNameAsString()); 653 654 if (!ClassDecl->hasTrivialDestructor()) { 655 const CXXDestructorDecl *D = ClassDecl->getDestructor(getContext()); 656 assert(D && "EmitLocalBlockVarDecl - destructor is nul"); 657 658 if (const ConstantArrayType *Array = 659 getContext().getAsConstantArrayType(Ty)) { 660 { 661 DelayedCleanupBlock Scope(*this); 662 QualType BaseElementTy = getContext().getBaseElementType(Array); 663 const llvm::Type *BasePtr = ConvertType(BaseElementTy); 664 BasePtr = llvm::PointerType::getUnqual(BasePtr); 665 llvm::Value *BaseAddrPtr = 666 Builder.CreateBitCast(Loc, BasePtr); 667 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr); 668 669 // Make sure to jump to the exit block. 670 EmitBranch(Scope.getCleanupExitBlock()); 671 } 672 if (Exceptions) { 673 EHCleanupBlock Cleanup(*this); 674 QualType BaseElementTy = getContext().getBaseElementType(Array); 675 const llvm::Type *BasePtr = ConvertType(BaseElementTy); 676 BasePtr = llvm::PointerType::getUnqual(BasePtr); 677 llvm::Value *BaseAddrPtr = 678 Builder.CreateBitCast(Loc, BasePtr); 679 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr); 680 } 681 } else { 682 { 683 DelayedCleanupBlock Scope(*this); 684 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, 685 Loc); 686 687 // Make sure to jump to the exit block. 688 EmitBranch(Scope.getCleanupExitBlock()); 689 } 690 if (Exceptions) { 691 EHCleanupBlock Cleanup(*this); 692 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, 693 Loc); 694 } 695 } 696 } 697 } 698 699 // Handle the cleanup attribute 700 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 701 const FunctionDecl *FD = CA->getFunctionDecl(); 702 703 llvm::Constant* F = CGM.GetAddrOfFunction(FD); 704 assert(F && "Could not find function!"); 705 706 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD); 707 708 // In some cases, the type of the function argument will be different from 709 // the type of the pointer. An example of this is 710 // void f(void* arg); 711 // __attribute__((cleanup(f))) void *g; 712 // 713 // To fix this we insert a bitcast here. 714 QualType ArgTy = Info.arg_begin()->type; 715 { 716 DelayedCleanupBlock scope(*this); 717 718 CallArgList Args; 719 Args.push_back(std::make_pair(RValue::get(Builder.CreateBitCast(DeclPtr, 720 ConvertType(ArgTy))), 721 getContext().getPointerType(D.getType()))); 722 EmitCall(Info, F, ReturnValueSlot(), Args); 723 } 724 if (Exceptions) { 725 EHCleanupBlock Cleanup(*this); 726 727 CallArgList Args; 728 Args.push_back(std::make_pair(RValue::get(Builder.CreateBitCast(DeclPtr, 729 ConvertType(ArgTy))), 730 getContext().getPointerType(D.getType()))); 731 EmitCall(Info, F, ReturnValueSlot(), Args); 732 } 733 } 734 735 if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly) { 736 { 737 DelayedCleanupBlock scope(*this); 738 llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding"); 739 V = Builder.CreateLoad(V); 740 BuildBlockRelease(V); 741 } 742 // FIXME: Turn this on and audit the codegen 743 if (0 && Exceptions) { 744 EHCleanupBlock Cleanup(*this); 745 llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding"); 746 V = Builder.CreateLoad(V); 747 BuildBlockRelease(V); 748 } 749 } 750 } 751 752 /// Emit an alloca (or GlobalValue depending on target) 753 /// for the specified parameter and set up LocalDeclMap. 754 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) { 755 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 756 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 757 "Invalid argument to EmitParmDecl"); 758 QualType Ty = D.getType(); 759 CanQualType CTy = getContext().getCanonicalType(Ty); 760 761 llvm::Value *DeclPtr; 762 // If this is an aggregate or variable sized value, reuse the input pointer. 763 if (!Ty->isConstantSizeType() || 764 CodeGenFunction::hasAggregateLLVMType(Ty)) { 765 DeclPtr = Arg; 766 } else { 767 // Otherwise, create a temporary to hold the value. 768 DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr"); 769 770 // Store the initial value into the alloca. 771 EmitStoreOfScalar(Arg, DeclPtr, CTy.isVolatileQualified(), Ty); 772 } 773 Arg->setName(D.getName()); 774 775 llvm::Value *&DMEntry = LocalDeclMap[&D]; 776 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 777 DMEntry = DeclPtr; 778 779 // Emit debug info for param declaration. 780 if (CGDebugInfo *DI = getDebugInfo()) { 781 DI->setLocation(D.getLocation()); 782 DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder); 783 } 784 } 785