CodeGenModule.cpp revision 4357a8291d759f6f9c36d3edeee8476d3eaf0804
1//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 coordinates the per-module state used while generating code. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CodeGenModule.h" 15#include "CGDebugInfo.h" 16#include "CodeGenFunction.h" 17#include "CGCall.h" 18#include "CGObjCRuntime.h" 19#include "Mangle.h" 20#include "TargetInfo.h" 21#include "clang/CodeGen/CodeGenOptions.h" 22#include "clang/AST/ASTContext.h" 23#include "clang/AST/CharUnits.h" 24#include "clang/AST/DeclObjC.h" 25#include "clang/AST/DeclCXX.h" 26#include "clang/AST/RecordLayout.h" 27#include "clang/Basic/Builtins.h" 28#include "clang/Basic/Diagnostic.h" 29#include "clang/Basic/SourceManager.h" 30#include "clang/Basic/TargetInfo.h" 31#include "clang/Basic/ConvertUTF.h" 32#include "llvm/CallingConv.h" 33#include "llvm/Module.h" 34#include "llvm/Intrinsics.h" 35#include "llvm/LLVMContext.h" 36#include "llvm/ADT/Triple.h" 37#include "llvm/Target/TargetData.h" 38#include "llvm/Support/CallSite.h" 39#include "llvm/Support/ErrorHandling.h" 40using namespace clang; 41using namespace CodeGen; 42 43 44CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 45 llvm::Module &M, const llvm::TargetData &TD, 46 Diagnostic &diags) 47 : BlockModule(C, M, TD, Types, *this), Context(C), 48 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 49 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 50 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()), 51 MangleCtx(C, diags), VTables(*this), Runtime(0), 52 CFConstantStringClassRef(0), 53 VMContext(M.getContext()) { 54 55 if (!Features.ObjC1) 56 Runtime = 0; 57 else if (!Features.NeXTRuntime) 58 Runtime = CreateGNUObjCRuntime(*this); 59 else if (Features.ObjCNonFragileABI) 60 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 61 else 62 Runtime = CreateMacObjCRuntime(*this); 63 64 // If debug info generation is enabled, create the CGDebugInfo object. 65 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0; 66} 67 68CodeGenModule::~CodeGenModule() { 69 delete Runtime; 70 delete DebugInfo; 71} 72 73void CodeGenModule::createObjCRuntime() { 74 if (!Features.NeXTRuntime) 75 Runtime = CreateGNUObjCRuntime(*this); 76 else if (Features.ObjCNonFragileABI) 77 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 78 else 79 Runtime = CreateMacObjCRuntime(*this); 80} 81 82void CodeGenModule::Release() { 83 EmitDeferred(); 84 EmitCXXGlobalInitFunc(); 85 EmitCXXGlobalDtorFunc(); 86 if (Runtime) 87 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 88 AddGlobalCtor(ObjCInitFunction); 89 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 90 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 91 EmitAnnotations(); 92 EmitLLVMUsed(); 93} 94 95bool CodeGenModule::isTargetDarwin() const { 96 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin; 97} 98 99/// ErrorUnsupported - Print out an error that codegen doesn't support the 100/// specified stmt yet. 101void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 102 bool OmitOnError) { 103 if (OmitOnError && getDiags().hasErrorOccurred()) 104 return; 105 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 106 "cannot compile this %0 yet"); 107 std::string Msg = Type; 108 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 109 << Msg << S->getSourceRange(); 110} 111 112/// ErrorUnsupported - Print out an error that codegen doesn't support the 113/// specified decl yet. 114void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 115 bool OmitOnError) { 116 if (OmitOnError && getDiags().hasErrorOccurred()) 117 return; 118 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 119 "cannot compile this %0 yet"); 120 std::string Msg = Type; 121 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 122} 123 124LangOptions::VisibilityMode 125CodeGenModule::getDeclVisibilityMode(const Decl *D) const { 126 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 127 if (VD->getStorageClass() == VarDecl::PrivateExtern) 128 return LangOptions::Hidden; 129 130 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) { 131 switch (attr->getVisibility()) { 132 default: assert(0 && "Unknown visibility!"); 133 case VisibilityAttr::DefaultVisibility: 134 return LangOptions::Default; 135 case VisibilityAttr::HiddenVisibility: 136 return LangOptions::Hidden; 137 case VisibilityAttr::ProtectedVisibility: 138 return LangOptions::Protected; 139 } 140 } 141 142 // This decl should have the same visibility as its parent. 143 if (const DeclContext *DC = D->getDeclContext()) 144 return getDeclVisibilityMode(cast<Decl>(DC)); 145 146 return getLangOptions().getVisibilityMode(); 147} 148 149void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 150 const Decl *D) const { 151 // Internal definitions always have default visibility. 152 if (GV->hasLocalLinkage()) { 153 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 154 return; 155 } 156 157 switch (getDeclVisibilityMode(D)) { 158 default: assert(0 && "Unknown visibility!"); 159 case LangOptions::Default: 160 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 161 case LangOptions::Hidden: 162 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 163 case LangOptions::Protected: 164 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 165 } 166} 167 168void CodeGenModule::getMangledName(MangleBuffer &Buffer, GlobalDecl GD) { 169 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 170 171 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 172 return getMangledCXXCtorName(Buffer, D, GD.getCtorType()); 173 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 174 return getMangledCXXDtorName(Buffer, D, GD.getDtorType()); 175 176 return getMangledName(Buffer, ND); 177} 178 179/// \brief Retrieves the mangled name for the given declaration. 180/// 181/// If the given declaration requires a mangled name, returns an 182/// const char* containing the mangled name. Otherwise, returns 183/// the unmangled name. 184/// 185void CodeGenModule::getMangledName(MangleBuffer &Buffer, 186 const NamedDecl *ND) { 187 if (!getMangleContext().shouldMangleDeclName(ND)) { 188 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 189 Buffer.setString(ND->getNameAsCString()); 190 return; 191 } 192 193 getMangleContext().mangleName(ND, Buffer.getBuffer()); 194} 195 196llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) { 197 return getModule().getNamedValue(Name); 198} 199 200/// AddGlobalCtor - Add a function to the list that will be called before 201/// main() runs. 202void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 203 // FIXME: Type coercion of void()* types. 204 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 205} 206 207/// AddGlobalDtor - Add a function to the list that will be called 208/// when the module is unloaded. 209void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 210 // FIXME: Type coercion of void()* types. 211 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 212} 213 214void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 215 // Ctor function type is void()*. 216 llvm::FunctionType* CtorFTy = 217 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 218 std::vector<const llvm::Type*>(), 219 false); 220 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 221 222 // Get the type of a ctor entry, { i32, void ()* }. 223 llvm::StructType* CtorStructTy = 224 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), 225 llvm::PointerType::getUnqual(CtorFTy), NULL); 226 227 // Construct the constructor and destructor arrays. 228 std::vector<llvm::Constant*> Ctors; 229 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 230 std::vector<llvm::Constant*> S; 231 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 232 I->second, false)); 233 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 234 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 235 } 236 237 if (!Ctors.empty()) { 238 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 239 new llvm::GlobalVariable(TheModule, AT, false, 240 llvm::GlobalValue::AppendingLinkage, 241 llvm::ConstantArray::get(AT, Ctors), 242 GlobalName); 243 } 244} 245 246void CodeGenModule::EmitAnnotations() { 247 if (Annotations.empty()) 248 return; 249 250 // Create a new global variable for the ConstantStruct in the Module. 251 llvm::Constant *Array = 252 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 253 Annotations.size()), 254 Annotations); 255 llvm::GlobalValue *gv = 256 new llvm::GlobalVariable(TheModule, Array->getType(), false, 257 llvm::GlobalValue::AppendingLinkage, Array, 258 "llvm.global.annotations"); 259 gv->setSection("llvm.metadata"); 260} 261 262static CodeGenModule::GVALinkage 263GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD, 264 const LangOptions &Features) { 265 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal; 266 267 Linkage L = FD->getLinkage(); 268 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus && 269 FD->getType()->getLinkage() == UniqueExternalLinkage) 270 L = UniqueExternalLinkage; 271 272 switch (L) { 273 case NoLinkage: 274 case InternalLinkage: 275 case UniqueExternalLinkage: 276 return CodeGenModule::GVA_Internal; 277 278 case ExternalLinkage: 279 switch (FD->getTemplateSpecializationKind()) { 280 case TSK_Undeclared: 281 case TSK_ExplicitSpecialization: 282 External = CodeGenModule::GVA_StrongExternal; 283 break; 284 285 case TSK_ExplicitInstantiationDefinition: 286 return CodeGenModule::GVA_ExplicitTemplateInstantiation; 287 288 case TSK_ExplicitInstantiationDeclaration: 289 case TSK_ImplicitInstantiation: 290 External = CodeGenModule::GVA_TemplateInstantiation; 291 break; 292 } 293 } 294 295 if (!FD->isInlined()) 296 return External; 297 298 if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 299 // GNU or C99 inline semantics. Determine whether this symbol should be 300 // externally visible. 301 if (FD->isInlineDefinitionExternallyVisible()) 302 return External; 303 304 // C99 inline semantics, where the symbol is not externally visible. 305 return CodeGenModule::GVA_C99Inline; 306 } 307 308 // C++0x [temp.explicit]p9: 309 // [ Note: The intent is that an inline function that is the subject of 310 // an explicit instantiation declaration will still be implicitly 311 // instantiated when used so that the body can be considered for 312 // inlining, but that no out-of-line copy of the inline function would be 313 // generated in the translation unit. -- end note ] 314 if (FD->getTemplateSpecializationKind() 315 == TSK_ExplicitInstantiationDeclaration) 316 return CodeGenModule::GVA_C99Inline; 317 318 return CodeGenModule::GVA_CXXInline; 319} 320 321llvm::GlobalValue::LinkageTypes 322CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 323 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features); 324 325 if (Linkage == GVA_Internal) { 326 return llvm::Function::InternalLinkage; 327 } else if (D->hasAttr<DLLExportAttr>()) { 328 return llvm::Function::DLLExportLinkage; 329 } else if (D->hasAttr<WeakAttr>()) { 330 return llvm::Function::WeakAnyLinkage; 331 } else if (Linkage == GVA_C99Inline) { 332 // In C99 mode, 'inline' functions are guaranteed to have a strong 333 // definition somewhere else, so we can use available_externally linkage. 334 return llvm::Function::AvailableExternallyLinkage; 335 } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) { 336 // In C++, the compiler has to emit a definition in every translation unit 337 // that references the function. We should use linkonce_odr because 338 // a) if all references in this translation unit are optimized away, we 339 // don't need to codegen it. b) if the function persists, it needs to be 340 // merged with other definitions. c) C++ has the ODR, so we know the 341 // definition is dependable. 342 return llvm::Function::LinkOnceODRLinkage; 343 } else if (Linkage == GVA_ExplicitTemplateInstantiation) { 344 // An explicit instantiation of a template has weak linkage, since 345 // explicit instantiations can occur in multiple translation units 346 // and must all be equivalent. However, we are not allowed to 347 // throw away these explicit instantiations. 348 return llvm::Function::WeakODRLinkage; 349 } else { 350 assert(Linkage == GVA_StrongExternal); 351 // Otherwise, we have strong external linkage. 352 return llvm::Function::ExternalLinkage; 353 } 354} 355 356 357/// SetFunctionDefinitionAttributes - Set attributes for a global. 358/// 359/// FIXME: This is currently only done for aliases and functions, but not for 360/// variables (these details are set in EmitGlobalVarDefinition for variables). 361void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 362 llvm::GlobalValue *GV) { 363 GV->setLinkage(getFunctionLinkage(D)); 364 SetCommonAttributes(D, GV); 365} 366 367void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 368 const CGFunctionInfo &Info, 369 llvm::Function *F) { 370 unsigned CallingConv; 371 AttributeListType AttributeList; 372 ConstructAttributeList(Info, D, AttributeList, CallingConv); 373 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 374 AttributeList.size())); 375 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 376} 377 378void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 379 llvm::Function *F) { 380 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 381 F->addFnAttr(llvm::Attribute::NoUnwind); 382 383 if (D->hasAttr<AlwaysInlineAttr>()) 384 F->addFnAttr(llvm::Attribute::AlwaysInline); 385 386 if (D->hasAttr<NoInlineAttr>()) 387 F->addFnAttr(llvm::Attribute::NoInline); 388 389 if (Features.getStackProtectorMode() == LangOptions::SSPOn) 390 F->addFnAttr(llvm::Attribute::StackProtect); 391 else if (Features.getStackProtectorMode() == LangOptions::SSPReq) 392 F->addFnAttr(llvm::Attribute::StackProtectReq); 393 394 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) { 395 unsigned width = Context.Target.getCharWidth(); 396 F->setAlignment(AA->getAlignment() / width); 397 while ((AA = AA->getNext<AlignedAttr>())) 398 F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width)); 399 } 400 // C++ ABI requires 2-byte alignment for member functions. 401 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 402 F->setAlignment(2); 403} 404 405void CodeGenModule::SetCommonAttributes(const Decl *D, 406 llvm::GlobalValue *GV) { 407 setGlobalVisibility(GV, D); 408 409 if (D->hasAttr<UsedAttr>()) 410 AddUsedGlobal(GV); 411 412 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 413 GV->setSection(SA->getName()); 414 415 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 416} 417 418void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 419 llvm::Function *F, 420 const CGFunctionInfo &FI) { 421 SetLLVMFunctionAttributes(D, FI, F); 422 SetLLVMFunctionAttributesForDefinition(D, F); 423 424 F->setLinkage(llvm::Function::InternalLinkage); 425 426 SetCommonAttributes(D, F); 427} 428 429void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 430 llvm::Function *F, 431 bool IsIncompleteFunction) { 432 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 433 434 if (!IsIncompleteFunction) 435 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F); 436 437 // Only a few attributes are set on declarations; these may later be 438 // overridden by a definition. 439 440 if (FD->hasAttr<DLLImportAttr>()) { 441 F->setLinkage(llvm::Function::DLLImportLinkage); 442 } else if (FD->hasAttr<WeakAttr>() || 443 FD->hasAttr<WeakImportAttr>()) { 444 // "extern_weak" is overloaded in LLVM; we probably should have 445 // separate linkage types for this. 446 F->setLinkage(llvm::Function::ExternalWeakLinkage); 447 } else { 448 F->setLinkage(llvm::Function::ExternalLinkage); 449 } 450 451 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 452 F->setSection(SA->getName()); 453} 454 455void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 456 assert(!GV->isDeclaration() && 457 "Only globals with definition can force usage."); 458 LLVMUsed.push_back(GV); 459} 460 461void CodeGenModule::EmitLLVMUsed() { 462 // Don't create llvm.used if there is no need. 463 if (LLVMUsed.empty()) 464 return; 465 466 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 467 468 // Convert LLVMUsed to what ConstantArray needs. 469 std::vector<llvm::Constant*> UsedArray; 470 UsedArray.resize(LLVMUsed.size()); 471 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 472 UsedArray[i] = 473 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 474 i8PTy); 475 } 476 477 if (UsedArray.empty()) 478 return; 479 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 480 481 llvm::GlobalVariable *GV = 482 new llvm::GlobalVariable(getModule(), ATy, false, 483 llvm::GlobalValue::AppendingLinkage, 484 llvm::ConstantArray::get(ATy, UsedArray), 485 "llvm.used"); 486 487 GV->setSection("llvm.metadata"); 488} 489 490void CodeGenModule::EmitDeferred() { 491 // Emit code for any potentially referenced deferred decls. Since a 492 // previously unused static decl may become used during the generation of code 493 // for a static function, iterate until no changes are made. 494 495 while (!DeferredDeclsToEmit.empty() || !DeferredVtables.empty()) { 496 if (!DeferredVtables.empty()) { 497 const CXXRecordDecl *RD = DeferredVtables.back(); 498 DeferredVtables.pop_back(); 499 getVTables().GenerateClassData(getVtableLinkage(RD), RD); 500 continue; 501 } 502 503 GlobalDecl D = DeferredDeclsToEmit.back(); 504 DeferredDeclsToEmit.pop_back(); 505 506 // Look it up to see if it was defined with a stronger definition (e.g. an 507 // extern inline function with a strong function redefinition). If so, 508 // just ignore the deferred decl. 509 MangleBuffer Name; 510 getMangledName(Name, D); 511 llvm::GlobalValue *CGRef = GetGlobalValue(Name); 512 assert(CGRef && "Deferred decl wasn't referenced?"); 513 514 if (!CGRef->isDeclaration()) 515 continue; 516 517 // Otherwise, emit the definition and move on to the next one. 518 EmitGlobalDefinition(D); 519 } 520} 521 522/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 523/// annotation information for a given GlobalValue. The annotation struct is 524/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 525/// GlobalValue being annotated. The second field is the constant string 526/// created from the AnnotateAttr's annotation. The third field is a constant 527/// string containing the name of the translation unit. The fourth field is 528/// the line number in the file of the annotated value declaration. 529/// 530/// FIXME: this does not unique the annotation string constants, as llvm-gcc 531/// appears to. 532/// 533llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 534 const AnnotateAttr *AA, 535 unsigned LineNo) { 536 llvm::Module *M = &getModule(); 537 538 // get [N x i8] constants for the annotation string, and the filename string 539 // which are the 2nd and 3rd elements of the global annotation structure. 540 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext); 541 llvm::Constant *anno = llvm::ConstantArray::get(VMContext, 542 AA->getAnnotation(), true); 543 llvm::Constant *unit = llvm::ConstantArray::get(VMContext, 544 M->getModuleIdentifier(), 545 true); 546 547 // Get the two global values corresponding to the ConstantArrays we just 548 // created to hold the bytes of the strings. 549 llvm::GlobalValue *annoGV = 550 new llvm::GlobalVariable(*M, anno->getType(), false, 551 llvm::GlobalValue::PrivateLinkage, anno, 552 GV->getName()); 553 // translation unit name string, emitted into the llvm.metadata section. 554 llvm::GlobalValue *unitGV = 555 new llvm::GlobalVariable(*M, unit->getType(), false, 556 llvm::GlobalValue::PrivateLinkage, unit, 557 ".str"); 558 559 // Create the ConstantStruct for the global annotation. 560 llvm::Constant *Fields[4] = { 561 llvm::ConstantExpr::getBitCast(GV, SBP), 562 llvm::ConstantExpr::getBitCast(annoGV, SBP), 563 llvm::ConstantExpr::getBitCast(unitGV, SBP), 564 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo) 565 }; 566 return llvm::ConstantStruct::get(VMContext, Fields, 4, false); 567} 568 569bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 570 // Never defer when EmitAllDecls is specified or the decl has 571 // attribute used. 572 if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>()) 573 return false; 574 575 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 576 // Constructors and destructors should never be deferred. 577 if (FD->hasAttr<ConstructorAttr>() || 578 FD->hasAttr<DestructorAttr>()) 579 return false; 580 581 // The key function for a class must never be deferred. 582 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) { 583 const CXXRecordDecl *RD = MD->getParent(); 584 if (MD->isOutOfLine() && RD->isDynamicClass()) { 585 const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD); 586 if (KeyFunction && 587 KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl()) 588 return false; 589 } 590 } 591 592 GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features); 593 594 // static, static inline, always_inline, and extern inline functions can 595 // always be deferred. Normal inline functions can be deferred in C99/C++. 596 // Implicit template instantiations can also be deferred in C++. 597 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 598 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 599 return true; 600 return false; 601 } 602 603 const VarDecl *VD = cast<VarDecl>(Global); 604 assert(VD->isFileVarDecl() && "Invalid decl"); 605 606 // We never want to defer structs that have non-trivial constructors or 607 // destructors. 608 609 // FIXME: Handle references. 610 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 611 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 612 if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()) 613 return false; 614 } 615 } 616 617 // Static data may be deferred, but out-of-line static data members 618 // cannot be. 619 Linkage L = VD->getLinkage(); 620 if (L == ExternalLinkage && getContext().getLangOptions().CPlusPlus && 621 VD->getType()->getLinkage() == UniqueExternalLinkage) 622 L = UniqueExternalLinkage; 623 624 switch (L) { 625 case NoLinkage: 626 case InternalLinkage: 627 case UniqueExternalLinkage: 628 // Initializer has side effects? 629 if (VD->getInit() && VD->getInit()->HasSideEffects(Context)) 630 return false; 631 return !(VD->isStaticDataMember() && VD->isOutOfLine()); 632 633 case ExternalLinkage: 634 break; 635 } 636 637 return false; 638} 639 640llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 641 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 642 assert(AA && "No alias?"); 643 644 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 645 646 // See if there is already something with the target's name in the module. 647 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 648 649 llvm::Constant *Aliasee; 650 if (isa<llvm::FunctionType>(DeclTy)) 651 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl()); 652 else 653 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 654 llvm::PointerType::getUnqual(DeclTy), 0); 655 if (!Entry) { 656 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 657 F->setLinkage(llvm::Function::ExternalWeakLinkage); 658 WeakRefReferences.insert(F); 659 } 660 661 return Aliasee; 662} 663 664void CodeGenModule::EmitGlobal(GlobalDecl GD) { 665 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 666 667 // Weak references don't produce any output by themselves. 668 if (Global->hasAttr<WeakRefAttr>()) 669 return; 670 671 // If this is an alias definition (which otherwise looks like a declaration) 672 // emit it now. 673 if (Global->hasAttr<AliasAttr>()) 674 return EmitAliasDefinition(GD); 675 676 // Ignore declarations, they will be emitted on their first use. 677 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 678 // Forward declarations are emitted lazily on first use. 679 if (!FD->isThisDeclarationADefinition()) 680 return; 681 } else { 682 const VarDecl *VD = cast<VarDecl>(Global); 683 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 684 685 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 686 return; 687 } 688 689 // Defer code generation when possible if this is a static definition, inline 690 // function etc. These we only want to emit if they are used. 691 if (!MayDeferGeneration(Global)) { 692 // Emit the definition if it can't be deferred. 693 EmitGlobalDefinition(GD); 694 return; 695 } 696 697 // If the value has already been used, add it directly to the 698 // DeferredDeclsToEmit list. 699 MangleBuffer MangledName; 700 getMangledName(MangledName, GD); 701 if (GetGlobalValue(MangledName)) 702 DeferredDeclsToEmit.push_back(GD); 703 else { 704 // Otherwise, remember that we saw a deferred decl with this name. The 705 // first use of the mangled name will cause it to move into 706 // DeferredDeclsToEmit. 707 DeferredDecls[MangledName] = GD; 708 } 709} 710 711void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 712 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 713 714 PrettyStackTraceDecl CrashInfo((ValueDecl *)D, D->getLocation(), 715 Context.getSourceManager(), 716 "Generating code for declaration"); 717 718 if (isa<CXXMethodDecl>(D)) 719 getVTables().EmitVTableRelatedData(GD); 720 721 if (isa<FunctionDecl>(D)) 722 return EmitGlobalFunctionDefinition(GD); 723 724 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 725 return EmitGlobalVarDefinition(VD); 726 727 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 728 return EmitCXXConstructor(CD, GD.getCtorType()); 729 730 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 731 return EmitCXXDestructor(DD, GD.getDtorType()); 732 733 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 734} 735 736/// GetOrCreateLLVMFunction - If the specified mangled name is not in the 737/// module, create and return an llvm Function with the specified type. If there 738/// is something in the module with the specified name, return it potentially 739/// bitcasted to the right type. 740/// 741/// If D is non-null, it specifies a decl that correspond to this. This is used 742/// to set the attributes on the function when it is first created. 743llvm::Constant * 744CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName, 745 const llvm::Type *Ty, 746 GlobalDecl D) { 747 // Lookup the entry, lazily creating it if necessary. 748 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 749 if (Entry) { 750 if (WeakRefReferences.count(Entry)) { 751 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 752 if (FD && !FD->hasAttr<WeakAttr>()) 753 Entry->setLinkage(llvm::Function::ExternalLinkage); 754 755 WeakRefReferences.erase(Entry); 756 } 757 758 if (Entry->getType()->getElementType() == Ty) 759 return Entry; 760 761 // Make sure the result is of the correct type. 762 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 763 return llvm::ConstantExpr::getBitCast(Entry, PTy); 764 } 765 766 // This function doesn't have a complete type (for example, the return 767 // type is an incomplete struct). Use a fake type instead, and make 768 // sure not to try to set attributes. 769 bool IsIncompleteFunction = false; 770 if (!isa<llvm::FunctionType>(Ty)) { 771 Ty = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 772 std::vector<const llvm::Type*>(), false); 773 IsIncompleteFunction = true; 774 } 775 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 776 llvm::Function::ExternalLinkage, 777 MangledName, &getModule()); 778 assert(F->getName() == MangledName && "name was uniqued!"); 779 if (D.getDecl()) 780 SetFunctionAttributes(D, F, IsIncompleteFunction); 781 782 // This is the first use or definition of a mangled name. If there is a 783 // deferred decl with this name, remember that we need to emit it at the end 784 // of the file. 785 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 786 if (DDI != DeferredDecls.end()) { 787 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 788 // list, and remove it from DeferredDecls (since we don't need it anymore). 789 DeferredDeclsToEmit.push_back(DDI->second); 790 DeferredDecls.erase(DDI); 791 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) { 792 // If this the first reference to a C++ inline function in a class, queue up 793 // the deferred function body for emission. These are not seen as 794 // top-level declarations. 795 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD)) 796 DeferredDeclsToEmit.push_back(D); 797 // A called constructor which has no definition or declaration need be 798 // synthesized. 799 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 800 if (CD->isImplicit()) { 801 assert(CD->isUsed() && "Sema doesn't consider constructor as used."); 802 DeferredDeclsToEmit.push_back(D); 803 } 804 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) { 805 if (DD->isImplicit()) { 806 assert(DD->isUsed() && "Sema doesn't consider destructor as used."); 807 DeferredDeclsToEmit.push_back(D); 808 } 809 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 810 if (MD->isCopyAssignment() && MD->isImplicit()) { 811 assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used."); 812 DeferredDeclsToEmit.push_back(D); 813 } 814 } 815 } 816 817 return F; 818} 819 820/// GetAddrOfFunction - Return the address of the given function. If Ty is 821/// non-null, then this function will use the specified type if it has to 822/// create it (this occurs when we see a definition of the function). 823llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 824 const llvm::Type *Ty) { 825 // If there was no specific requested type, just convert it now. 826 if (!Ty) 827 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 828 MangleBuffer MangledName; 829 getMangledName(MangledName, GD); 830 return GetOrCreateLLVMFunction(MangledName, Ty, GD); 831} 832 833/// CreateRuntimeFunction - Create a new runtime function with the specified 834/// type and name. 835llvm::Constant * 836CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 837 llvm::StringRef Name) { 838 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl()); 839} 840 841static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) { 842 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 843 return false; 844 if (Context.getLangOptions().CPlusPlus && 845 Context.getBaseElementType(D->getType())->getAs<RecordType>()) { 846 // FIXME: We should do something fancier here! 847 return false; 848 } 849 return true; 850} 851 852/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 853/// create and return an llvm GlobalVariable with the specified type. If there 854/// is something in the module with the specified name, return it potentially 855/// bitcasted to the right type. 856/// 857/// If D is non-null, it specifies a decl that correspond to this. This is used 858/// to set the attributes on the global when it is first created. 859llvm::Constant * 860CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName, 861 const llvm::PointerType *Ty, 862 const VarDecl *D) { 863 // Lookup the entry, lazily creating it if necessary. 864 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 865 if (Entry) { 866 if (WeakRefReferences.count(Entry)) { 867 if (D && !D->hasAttr<WeakAttr>()) 868 Entry->setLinkage(llvm::Function::ExternalLinkage); 869 870 WeakRefReferences.erase(Entry); 871 } 872 873 if (Entry->getType() == Ty) 874 return Entry; 875 876 // Make sure the result is of the correct type. 877 return llvm::ConstantExpr::getBitCast(Entry, Ty); 878 } 879 880 // This is the first use or definition of a mangled name. If there is a 881 // deferred decl with this name, remember that we need to emit it at the end 882 // of the file. 883 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 884 if (DDI != DeferredDecls.end()) { 885 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 886 // list, and remove it from DeferredDecls (since we don't need it anymore). 887 DeferredDeclsToEmit.push_back(DDI->second); 888 DeferredDecls.erase(DDI); 889 } 890 891 llvm::GlobalVariable *GV = 892 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 893 llvm::GlobalValue::ExternalLinkage, 894 0, MangledName, 0, 895 false, Ty->getAddressSpace()); 896 897 // Handle things which are present even on external declarations. 898 if (D) { 899 // FIXME: This code is overly simple and should be merged with other global 900 // handling. 901 GV->setConstant(DeclIsConstantGlobal(Context, D)); 902 903 // FIXME: Merge with other attribute handling code. 904 if (D->getStorageClass() == VarDecl::PrivateExtern) 905 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 906 907 if (D->hasAttr<WeakAttr>() || 908 D->hasAttr<WeakImportAttr>()) 909 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 910 911 GV->setThreadLocal(D->isThreadSpecified()); 912 } 913 914 return GV; 915} 916 917 918/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 919/// given global variable. If Ty is non-null and if the global doesn't exist, 920/// then it will be greated with the specified type instead of whatever the 921/// normal requested type would be. 922llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 923 const llvm::Type *Ty) { 924 assert(D->hasGlobalStorage() && "Not a global variable"); 925 QualType ASTTy = D->getType(); 926 if (Ty == 0) 927 Ty = getTypes().ConvertTypeForMem(ASTTy); 928 929 const llvm::PointerType *PTy = 930 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 931 932 MangleBuffer MangledName; 933 getMangledName(MangledName, D); 934 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 935} 936 937/// CreateRuntimeVariable - Create a new runtime global variable with the 938/// specified type and name. 939llvm::Constant * 940CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 941 llvm::StringRef Name) { 942 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 943} 944 945void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 946 assert(!D->getInit() && "Cannot emit definite definitions here!"); 947 948 if (MayDeferGeneration(D)) { 949 // If we have not seen a reference to this variable yet, place it 950 // into the deferred declarations table to be emitted if needed 951 // later. 952 MangleBuffer MangledName; 953 getMangledName(MangledName, D); 954 if (!GetGlobalValue(MangledName)) { 955 DeferredDecls[MangledName] = D; 956 return; 957 } 958 } 959 960 // The tentative definition is the only definition. 961 EmitGlobalVarDefinition(D); 962} 963 964llvm::GlobalVariable::LinkageTypes 965CodeGenModule::getVtableLinkage(const CXXRecordDecl *RD) { 966 if (RD->isInAnonymousNamespace() || !RD->hasLinkage()) 967 return llvm::GlobalVariable::InternalLinkage; 968 969 if (const CXXMethodDecl *KeyFunction 970 = RD->getASTContext().getKeyFunction(RD)) { 971 // If this class has a key function, use that to determine the linkage of 972 // the vtable. 973 const FunctionDecl *Def = 0; 974 if (KeyFunction->getBody(Def)) 975 KeyFunction = cast<CXXMethodDecl>(Def); 976 977 switch (KeyFunction->getTemplateSpecializationKind()) { 978 case TSK_Undeclared: 979 case TSK_ExplicitSpecialization: 980 if (KeyFunction->isInlined()) 981 return llvm::GlobalVariable::WeakODRLinkage; 982 983 return llvm::GlobalVariable::ExternalLinkage; 984 985 case TSK_ImplicitInstantiation: 986 case TSK_ExplicitInstantiationDefinition: 987 return llvm::GlobalVariable::WeakODRLinkage; 988 989 case TSK_ExplicitInstantiationDeclaration: 990 // FIXME: Use available_externally linkage. However, this currently 991 // breaks LLVM's build due to undefined symbols. 992 // return llvm::GlobalVariable::AvailableExternallyLinkage; 993 return llvm::GlobalVariable::WeakODRLinkage; 994 } 995 } 996 997 switch (RD->getTemplateSpecializationKind()) { 998 case TSK_Undeclared: 999 case TSK_ExplicitSpecialization: 1000 case TSK_ImplicitInstantiation: 1001 case TSK_ExplicitInstantiationDefinition: 1002 return llvm::GlobalVariable::WeakODRLinkage; 1003 1004 case TSK_ExplicitInstantiationDeclaration: 1005 // FIXME: Use available_externally linkage. However, this currently 1006 // breaks LLVM's build due to undefined symbols. 1007 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1008 return llvm::GlobalVariable::WeakODRLinkage; 1009 } 1010 1011 // Silence GCC warning. 1012 return llvm::GlobalVariable::WeakODRLinkage; 1013} 1014 1015static CodeGenModule::GVALinkage 1016GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) { 1017 // If this is a static data member, compute the kind of template 1018 // specialization. Otherwise, this variable is not part of a 1019 // template. 1020 TemplateSpecializationKind TSK = TSK_Undeclared; 1021 if (VD->isStaticDataMember()) 1022 TSK = VD->getTemplateSpecializationKind(); 1023 1024 Linkage L = VD->getLinkage(); 1025 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus && 1026 VD->getType()->getLinkage() == UniqueExternalLinkage) 1027 L = UniqueExternalLinkage; 1028 1029 switch (L) { 1030 case NoLinkage: 1031 case InternalLinkage: 1032 case UniqueExternalLinkage: 1033 return CodeGenModule::GVA_Internal; 1034 1035 case ExternalLinkage: 1036 switch (TSK) { 1037 case TSK_Undeclared: 1038 case TSK_ExplicitSpecialization: 1039 return CodeGenModule::GVA_StrongExternal; 1040 1041 case TSK_ExplicitInstantiationDeclaration: 1042 llvm_unreachable("Variable should not be instantiated"); 1043 // Fall through to treat this like any other instantiation. 1044 1045 case TSK_ExplicitInstantiationDefinition: 1046 return CodeGenModule::GVA_ExplicitTemplateInstantiation; 1047 1048 case TSK_ImplicitInstantiation: 1049 return CodeGenModule::GVA_TemplateInstantiation; 1050 } 1051 } 1052 1053 return CodeGenModule::GVA_StrongExternal; 1054} 1055 1056CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const { 1057 return CharUnits::fromQuantity( 1058 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth()); 1059} 1060 1061void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1062 llvm::Constant *Init = 0; 1063 QualType ASTTy = D->getType(); 1064 bool NonConstInit = false; 1065 1066 const Expr *InitExpr = D->getAnyInitializer(); 1067 1068 if (!InitExpr) { 1069 // This is a tentative definition; tentative definitions are 1070 // implicitly initialized with { 0 }. 1071 // 1072 // Note that tentative definitions are only emitted at the end of 1073 // a translation unit, so they should never have incomplete 1074 // type. In addition, EmitTentativeDefinition makes sure that we 1075 // never attempt to emit a tentative definition if a real one 1076 // exists. A use may still exists, however, so we still may need 1077 // to do a RAUW. 1078 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1079 Init = EmitNullConstant(D->getType()); 1080 } else { 1081 Init = EmitConstantExpr(InitExpr, D->getType()); 1082 1083 if (!Init) { 1084 QualType T = InitExpr->getType(); 1085 if (getLangOptions().CPlusPlus) { 1086 EmitCXXGlobalVarDeclInitFunc(D); 1087 Init = EmitNullConstant(T); 1088 NonConstInit = true; 1089 } else { 1090 ErrorUnsupported(D, "static initializer"); 1091 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1092 } 1093 } 1094 } 1095 1096 const llvm::Type* InitType = Init->getType(); 1097 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1098 1099 // Strip off a bitcast if we got one back. 1100 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1101 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1102 // all zero index gep. 1103 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1104 Entry = CE->getOperand(0); 1105 } 1106 1107 // Entry is now either a Function or GlobalVariable. 1108 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1109 1110 // We have a definition after a declaration with the wrong type. 1111 // We must make a new GlobalVariable* and update everything that used OldGV 1112 // (a declaration or tentative definition) with the new GlobalVariable* 1113 // (which will be a definition). 1114 // 1115 // This happens if there is a prototype for a global (e.g. 1116 // "extern int x[];") and then a definition of a different type (e.g. 1117 // "int x[10];"). This also happens when an initializer has a different type 1118 // from the type of the global (this happens with unions). 1119 if (GV == 0 || 1120 GV->getType()->getElementType() != InitType || 1121 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1122 1123 // Move the old entry aside so that we'll create a new one. 1124 Entry->setName(llvm::StringRef()); 1125 1126 // Make a new global with the correct type, this is now guaranteed to work. 1127 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1128 1129 // Replace all uses of the old global with the new global 1130 llvm::Constant *NewPtrForOldDecl = 1131 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1132 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1133 1134 // Erase the old global, since it is no longer used. 1135 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1136 } 1137 1138 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1139 SourceManager &SM = Context.getSourceManager(); 1140 AddAnnotation(EmitAnnotateAttr(GV, AA, 1141 SM.getInstantiationLineNumber(D->getLocation()))); 1142 } 1143 1144 GV->setInitializer(Init); 1145 1146 // If it is safe to mark the global 'constant', do so now. 1147 GV->setConstant(false); 1148 if (!NonConstInit && DeclIsConstantGlobal(Context, D)) 1149 GV->setConstant(true); 1150 1151 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1152 1153 // Set the llvm linkage type as appropriate. 1154 GVALinkage Linkage = GetLinkageForVariable(getContext(), D); 1155 if (Linkage == GVA_Internal) 1156 GV->setLinkage(llvm::Function::InternalLinkage); 1157 else if (D->hasAttr<DLLImportAttr>()) 1158 GV->setLinkage(llvm::Function::DLLImportLinkage); 1159 else if (D->hasAttr<DLLExportAttr>()) 1160 GV->setLinkage(llvm::Function::DLLExportLinkage); 1161 else if (D->hasAttr<WeakAttr>()) { 1162 if (GV->isConstant()) 1163 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage); 1164 else 1165 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1166 } else if (Linkage == GVA_TemplateInstantiation || 1167 Linkage == GVA_ExplicitTemplateInstantiation) 1168 // FIXME: It seems like we can provide more specific linkage here 1169 // (LinkOnceODR, WeakODR). 1170 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1171 else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon && 1172 !D->hasExternalStorage() && !D->getInit() && 1173 !D->getAttr<SectionAttr>()) { 1174 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 1175 // common vars aren't constant even if declared const. 1176 GV->setConstant(false); 1177 } else 1178 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 1179 1180 SetCommonAttributes(D, GV); 1181 1182 // Emit global variable debug information. 1183 if (CGDebugInfo *DI = getDebugInfo()) { 1184 DI->setLocation(D->getLocation()); 1185 DI->EmitGlobalVariable(GV, D); 1186 } 1187} 1188 1189/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1190/// implement a function with no prototype, e.g. "int foo() {}". If there are 1191/// existing call uses of the old function in the module, this adjusts them to 1192/// call the new function directly. 1193/// 1194/// This is not just a cleanup: the always_inline pass requires direct calls to 1195/// functions to be able to inline them. If there is a bitcast in the way, it 1196/// won't inline them. Instcombine normally deletes these calls, but it isn't 1197/// run at -O0. 1198static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1199 llvm::Function *NewFn) { 1200 // If we're redefining a global as a function, don't transform it. 1201 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1202 if (OldFn == 0) return; 1203 1204 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1205 llvm::SmallVector<llvm::Value*, 4> ArgList; 1206 1207 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1208 UI != E; ) { 1209 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1210 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 1211 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 1212 llvm::CallSite CS(CI); 1213 if (!CI || !CS.isCallee(I)) continue; 1214 1215 // If the return types don't match exactly, and if the call isn't dead, then 1216 // we can't transform this call. 1217 if (CI->getType() != NewRetTy && !CI->use_empty()) 1218 continue; 1219 1220 // If the function was passed too few arguments, don't transform. If extra 1221 // arguments were passed, we silently drop them. If any of the types 1222 // mismatch, we don't transform. 1223 unsigned ArgNo = 0; 1224 bool DontTransform = false; 1225 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1226 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1227 if (CS.arg_size() == ArgNo || 1228 CS.getArgument(ArgNo)->getType() != AI->getType()) { 1229 DontTransform = true; 1230 break; 1231 } 1232 } 1233 if (DontTransform) 1234 continue; 1235 1236 // Okay, we can transform this. Create the new call instruction and copy 1237 // over the required information. 1238 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 1239 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1240 ArgList.end(), "", CI); 1241 ArgList.clear(); 1242 if (!NewCall->getType()->isVoidTy()) 1243 NewCall->takeName(CI); 1244 NewCall->setAttributes(CI->getAttributes()); 1245 NewCall->setCallingConv(CI->getCallingConv()); 1246 1247 // Finally, remove the old call, replacing any uses with the new one. 1248 if (!CI->use_empty()) 1249 CI->replaceAllUsesWith(NewCall); 1250 1251 // Copy debug location attached to CI. 1252 if (!CI->getDebugLoc().isUnknown()) 1253 NewCall->setDebugLoc(CI->getDebugLoc()); 1254 CI->eraseFromParent(); 1255 } 1256} 1257 1258 1259void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1260 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1261 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD); 1262 getMangleContext().mangleInitDiscriminator(); 1263 // Get or create the prototype for the function. 1264 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1265 1266 // Strip off a bitcast if we got one back. 1267 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1268 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1269 Entry = CE->getOperand(0); 1270 } 1271 1272 1273 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1274 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1275 1276 // If the types mismatch then we have to rewrite the definition. 1277 assert(OldFn->isDeclaration() && 1278 "Shouldn't replace non-declaration"); 1279 1280 // F is the Function* for the one with the wrong type, we must make a new 1281 // Function* and update everything that used F (a declaration) with the new 1282 // Function* (which will be a definition). 1283 // 1284 // This happens if there is a prototype for a function 1285 // (e.g. "int f()") and then a definition of a different type 1286 // (e.g. "int f(int x)"). Move the old function aside so that it 1287 // doesn't interfere with GetAddrOfFunction. 1288 OldFn->setName(llvm::StringRef()); 1289 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1290 1291 // If this is an implementation of a function without a prototype, try to 1292 // replace any existing uses of the function (which may be calls) with uses 1293 // of the new function 1294 if (D->getType()->isFunctionNoProtoType()) { 1295 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1296 OldFn->removeDeadConstantUsers(); 1297 } 1298 1299 // Replace uses of F with the Function we will endow with a body. 1300 if (!Entry->use_empty()) { 1301 llvm::Constant *NewPtrForOldDecl = 1302 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1303 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1304 } 1305 1306 // Ok, delete the old function now, which is dead. 1307 OldFn->eraseFromParent(); 1308 1309 Entry = NewFn; 1310 } 1311 1312 llvm::Function *Fn = cast<llvm::Function>(Entry); 1313 1314 CodeGenFunction(*this).GenerateCode(D, Fn); 1315 1316 SetFunctionDefinitionAttributes(D, Fn); 1317 SetLLVMFunctionAttributesForDefinition(D, Fn); 1318 1319 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1320 AddGlobalCtor(Fn, CA->getPriority()); 1321 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1322 AddGlobalDtor(Fn, DA->getPriority()); 1323} 1324 1325void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1326 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1327 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1328 assert(AA && "Not an alias?"); 1329 1330 MangleBuffer MangledName; 1331 getMangledName(MangledName, GD); 1332 1333 // If there is a definition in the module, then it wins over the alias. 1334 // This is dubious, but allow it to be safe. Just ignore the alias. 1335 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1336 if (Entry && !Entry->isDeclaration()) 1337 return; 1338 1339 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1340 1341 // Create a reference to the named value. This ensures that it is emitted 1342 // if a deferred decl. 1343 llvm::Constant *Aliasee; 1344 if (isa<llvm::FunctionType>(DeclTy)) 1345 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl()); 1346 else 1347 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1348 llvm::PointerType::getUnqual(DeclTy), 0); 1349 1350 // Create the new alias itself, but don't set a name yet. 1351 llvm::GlobalValue *GA = 1352 new llvm::GlobalAlias(Aliasee->getType(), 1353 llvm::Function::ExternalLinkage, 1354 "", Aliasee, &getModule()); 1355 1356 if (Entry) { 1357 assert(Entry->isDeclaration()); 1358 1359 // If there is a declaration in the module, then we had an extern followed 1360 // by the alias, as in: 1361 // extern int test6(); 1362 // ... 1363 // int test6() __attribute__((alias("test7"))); 1364 // 1365 // Remove it and replace uses of it with the alias. 1366 GA->takeName(Entry); 1367 1368 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1369 Entry->getType())); 1370 Entry->eraseFromParent(); 1371 } else { 1372 GA->setName(MangledName.getString()); 1373 } 1374 1375 // Set attributes which are particular to an alias; this is a 1376 // specialization of the attributes which may be set on a global 1377 // variable/function. 1378 if (D->hasAttr<DLLExportAttr>()) { 1379 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1380 // The dllexport attribute is ignored for undefined symbols. 1381 if (FD->getBody()) 1382 GA->setLinkage(llvm::Function::DLLExportLinkage); 1383 } else { 1384 GA->setLinkage(llvm::Function::DLLExportLinkage); 1385 } 1386 } else if (D->hasAttr<WeakAttr>() || 1387 D->hasAttr<WeakRefAttr>() || 1388 D->hasAttr<WeakImportAttr>()) { 1389 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1390 } 1391 1392 SetCommonAttributes(D, GA); 1393} 1394 1395/// getBuiltinLibFunction - Given a builtin id for a function like 1396/// "__builtin_fabsf", return a Function* for "fabsf". 1397llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1398 unsigned BuiltinID) { 1399 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1400 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1401 "isn't a lib fn"); 1402 1403 // Get the name, skip over the __builtin_ prefix (if necessary). 1404 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1405 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1406 Name += 10; 1407 1408 const llvm::FunctionType *Ty = 1409 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType())); 1410 1411 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1412} 1413 1414llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1415 unsigned NumTys) { 1416 return llvm::Intrinsic::getDeclaration(&getModule(), 1417 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1418} 1419 1420 1421llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType, 1422 const llvm::Type *SrcType, 1423 const llvm::Type *SizeType) { 1424 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType }; 1425 return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3); 1426} 1427 1428llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType, 1429 const llvm::Type *SrcType, 1430 const llvm::Type *SizeType) { 1431 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType }; 1432 return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3); 1433} 1434 1435llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType, 1436 const llvm::Type *SizeType) { 1437 const llvm::Type *ArgTypes[2] = { DestType, SizeType }; 1438 return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2); 1439} 1440 1441static llvm::StringMapEntry<llvm::Constant*> & 1442GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1443 const StringLiteral *Literal, 1444 bool TargetIsLSB, 1445 bool &IsUTF16, 1446 unsigned &StringLength) { 1447 unsigned NumBytes = Literal->getByteLength(); 1448 1449 // Check for simple case. 1450 if (!Literal->containsNonAsciiOrNull()) { 1451 StringLength = NumBytes; 1452 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1453 StringLength)); 1454 } 1455 1456 // Otherwise, convert the UTF8 literals into a byte string. 1457 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1458 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData(); 1459 UTF16 *ToPtr = &ToBuf[0]; 1460 1461 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1462 &ToPtr, ToPtr + NumBytes, 1463 strictConversion); 1464 1465 // Check for conversion failure. 1466 if (Result != conversionOK) { 1467 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove 1468 // this duplicate code. 1469 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed"); 1470 StringLength = NumBytes; 1471 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1472 StringLength)); 1473 } 1474 1475 // ConvertUTF8toUTF16 returns the length in ToPtr. 1476 StringLength = ToPtr - &ToBuf[0]; 1477 1478 // Render the UTF-16 string into a byte array and convert to the target byte 1479 // order. 1480 // 1481 // FIXME: This isn't something we should need to do here. 1482 llvm::SmallString<128> AsBytes; 1483 AsBytes.reserve(StringLength * 2); 1484 for (unsigned i = 0; i != StringLength; ++i) { 1485 unsigned short Val = ToBuf[i]; 1486 if (TargetIsLSB) { 1487 AsBytes.push_back(Val & 0xFF); 1488 AsBytes.push_back(Val >> 8); 1489 } else { 1490 AsBytes.push_back(Val >> 8); 1491 AsBytes.push_back(Val & 0xFF); 1492 } 1493 } 1494 // Append one extra null character, the second is automatically added by our 1495 // caller. 1496 AsBytes.push_back(0); 1497 1498 IsUTF16 = true; 1499 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1500} 1501 1502llvm::Constant * 1503CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1504 unsigned StringLength = 0; 1505 bool isUTF16 = false; 1506 llvm::StringMapEntry<llvm::Constant*> &Entry = 1507 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1508 getTargetData().isLittleEndian(), 1509 isUTF16, StringLength); 1510 1511 if (llvm::Constant *C = Entry.getValue()) 1512 return C; 1513 1514 llvm::Constant *Zero = 1515 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1516 llvm::Constant *Zeros[] = { Zero, Zero }; 1517 1518 // If we don't already have it, get __CFConstantStringClassReference. 1519 if (!CFConstantStringClassRef) { 1520 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1521 Ty = llvm::ArrayType::get(Ty, 0); 1522 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1523 "__CFConstantStringClassReference"); 1524 // Decay array -> ptr 1525 CFConstantStringClassRef = 1526 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1527 } 1528 1529 QualType CFTy = getContext().getCFConstantStringType(); 1530 1531 const llvm::StructType *STy = 1532 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1533 1534 std::vector<llvm::Constant*> Fields(4); 1535 1536 // Class pointer. 1537 Fields[0] = CFConstantStringClassRef; 1538 1539 // Flags. 1540 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1541 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1542 llvm::ConstantInt::get(Ty, 0x07C8); 1543 1544 // String pointer. 1545 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1546 1547 llvm::GlobalValue::LinkageTypes Linkage; 1548 bool isConstant; 1549 if (isUTF16) { 1550 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1551 Linkage = llvm::GlobalValue::InternalLinkage; 1552 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1553 // does make plain ascii ones writable. 1554 isConstant = true; 1555 } else { 1556 Linkage = llvm::GlobalValue::PrivateLinkage; 1557 isConstant = !Features.WritableStrings; 1558 } 1559 1560 llvm::GlobalVariable *GV = 1561 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1562 ".str"); 1563 if (isUTF16) { 1564 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1565 GV->setAlignment(Align.getQuantity()); 1566 } 1567 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1568 1569 // String length. 1570 Ty = getTypes().ConvertType(getContext().LongTy); 1571 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1572 1573 // The struct. 1574 C = llvm::ConstantStruct::get(STy, Fields); 1575 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1576 llvm::GlobalVariable::PrivateLinkage, C, 1577 "_unnamed_cfstring_"); 1578 if (const char *Sect = getContext().Target.getCFStringSection()) 1579 GV->setSection(Sect); 1580 Entry.setValue(GV); 1581 1582 return GV; 1583} 1584 1585/// GetStringForStringLiteral - Return the appropriate bytes for a 1586/// string literal, properly padded to match the literal type. 1587std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1588 const char *StrData = E->getStrData(); 1589 unsigned Len = E->getByteLength(); 1590 1591 const ConstantArrayType *CAT = 1592 getContext().getAsConstantArrayType(E->getType()); 1593 assert(CAT && "String isn't pointer or array!"); 1594 1595 // Resize the string to the right size. 1596 std::string Str(StrData, StrData+Len); 1597 uint64_t RealLen = CAT->getSize().getZExtValue(); 1598 1599 if (E->isWide()) 1600 RealLen *= getContext().Target.getWCharWidth()/8; 1601 1602 Str.resize(RealLen, '\0'); 1603 1604 return Str; 1605} 1606 1607/// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1608/// constant array for the given string literal. 1609llvm::Constant * 1610CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1611 // FIXME: This can be more efficient. 1612 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1613 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S)); 1614 if (S->isWide()) { 1615 llvm::Type *DestTy = 1616 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1617 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1618 } 1619 return C; 1620} 1621 1622/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1623/// array for the given ObjCEncodeExpr node. 1624llvm::Constant * 1625CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1626 std::string Str; 1627 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1628 1629 return GetAddrOfConstantCString(Str); 1630} 1631 1632 1633/// GenerateWritableString -- Creates storage for a string literal. 1634static llvm::Constant *GenerateStringLiteral(const std::string &str, 1635 bool constant, 1636 CodeGenModule &CGM, 1637 const char *GlobalName) { 1638 // Create Constant for this string literal. Don't add a '\0'. 1639 llvm::Constant *C = 1640 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1641 1642 // Create a global variable for this string 1643 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1644 llvm::GlobalValue::PrivateLinkage, 1645 C, GlobalName); 1646} 1647 1648/// GetAddrOfConstantString - Returns a pointer to a character array 1649/// containing the literal. This contents are exactly that of the 1650/// given string, i.e. it will not be null terminated automatically; 1651/// see GetAddrOfConstantCString. Note that whether the result is 1652/// actually a pointer to an LLVM constant depends on 1653/// Feature.WriteableStrings. 1654/// 1655/// The result has pointer to array type. 1656llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1657 const char *GlobalName) { 1658 bool IsConstant = !Features.WritableStrings; 1659 1660 // Get the default prefix if a name wasn't specified. 1661 if (!GlobalName) 1662 GlobalName = ".str"; 1663 1664 // Don't share any string literals if strings aren't constant. 1665 if (!IsConstant) 1666 return GenerateStringLiteral(str, false, *this, GlobalName); 1667 1668 llvm::StringMapEntry<llvm::Constant *> &Entry = 1669 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1670 1671 if (Entry.getValue()) 1672 return Entry.getValue(); 1673 1674 // Create a global variable for this. 1675 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1676 Entry.setValue(C); 1677 return C; 1678} 1679 1680/// GetAddrOfConstantCString - Returns a pointer to a character 1681/// array containing the literal and a terminating '\-' 1682/// character. The result has pointer to array type. 1683llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1684 const char *GlobalName){ 1685 return GetAddrOfConstantString(str + '\0', GlobalName); 1686} 1687 1688/// EmitObjCPropertyImplementations - Emit information for synthesized 1689/// properties for an implementation. 1690void CodeGenModule::EmitObjCPropertyImplementations(const 1691 ObjCImplementationDecl *D) { 1692 for (ObjCImplementationDecl::propimpl_iterator 1693 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1694 ObjCPropertyImplDecl *PID = *i; 1695 1696 // Dynamic is just for type-checking. 1697 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1698 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1699 1700 // Determine which methods need to be implemented, some may have 1701 // been overridden. Note that ::isSynthesized is not the method 1702 // we want, that just indicates if the decl came from a 1703 // property. What we want to know is if the method is defined in 1704 // this implementation. 1705 if (!D->getInstanceMethod(PD->getGetterName())) 1706 CodeGenFunction(*this).GenerateObjCGetter( 1707 const_cast<ObjCImplementationDecl *>(D), PID); 1708 if (!PD->isReadOnly() && 1709 !D->getInstanceMethod(PD->getSetterName())) 1710 CodeGenFunction(*this).GenerateObjCSetter( 1711 const_cast<ObjCImplementationDecl *>(D), PID); 1712 } 1713 } 1714} 1715 1716/// EmitNamespace - Emit all declarations in a namespace. 1717void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1718 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1719 I != E; ++I) 1720 EmitTopLevelDecl(*I); 1721} 1722 1723// EmitLinkageSpec - Emit all declarations in a linkage spec. 1724void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1725 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1726 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1727 ErrorUnsupported(LSD, "linkage spec"); 1728 return; 1729 } 1730 1731 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1732 I != E; ++I) 1733 EmitTopLevelDecl(*I); 1734} 1735 1736/// EmitTopLevelDecl - Emit code for a single top level declaration. 1737void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1738 // If an error has occurred, stop code generation, but continue 1739 // parsing and semantic analysis (to ensure all warnings and errors 1740 // are emitted). 1741 if (Diags.hasErrorOccurred()) 1742 return; 1743 1744 // Ignore dependent declarations. 1745 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1746 return; 1747 1748 switch (D->getKind()) { 1749 case Decl::CXXConversion: 1750 case Decl::CXXMethod: 1751 case Decl::Function: 1752 // Skip function templates 1753 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1754 return; 1755 1756 EmitGlobal(cast<FunctionDecl>(D)); 1757 break; 1758 1759 case Decl::Var: 1760 EmitGlobal(cast<VarDecl>(D)); 1761 break; 1762 1763 // C++ Decls 1764 case Decl::Namespace: 1765 EmitNamespace(cast<NamespaceDecl>(D)); 1766 break; 1767 // No code generation needed. 1768 case Decl::UsingShadow: 1769 case Decl::Using: 1770 case Decl::UsingDirective: 1771 case Decl::ClassTemplate: 1772 case Decl::FunctionTemplate: 1773 case Decl::NamespaceAlias: 1774 break; 1775 case Decl::CXXConstructor: 1776 // Skip function templates 1777 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1778 return; 1779 1780 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 1781 break; 1782 case Decl::CXXDestructor: 1783 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 1784 break; 1785 1786 case Decl::StaticAssert: 1787 // Nothing to do. 1788 break; 1789 1790 // Objective-C Decls 1791 1792 // Forward declarations, no (immediate) code generation. 1793 case Decl::ObjCClass: 1794 case Decl::ObjCForwardProtocol: 1795 case Decl::ObjCCategory: 1796 case Decl::ObjCInterface: 1797 break; 1798 1799 case Decl::ObjCProtocol: 1800 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1801 break; 1802 1803 case Decl::ObjCCategoryImpl: 1804 // Categories have properties but don't support synthesize so we 1805 // can ignore them here. 1806 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1807 break; 1808 1809 case Decl::ObjCImplementation: { 1810 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1811 EmitObjCPropertyImplementations(OMD); 1812 Runtime->GenerateClass(OMD); 1813 break; 1814 } 1815 case Decl::ObjCMethod: { 1816 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1817 // If this is not a prototype, emit the body. 1818 if (OMD->getBody()) 1819 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1820 break; 1821 } 1822 case Decl::ObjCCompatibleAlias: 1823 // compatibility-alias is a directive and has no code gen. 1824 break; 1825 1826 case Decl::LinkageSpec: 1827 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 1828 break; 1829 1830 case Decl::FileScopeAsm: { 1831 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1832 llvm::StringRef AsmString = AD->getAsmString()->getString(); 1833 1834 const std::string &S = getModule().getModuleInlineAsm(); 1835 if (S.empty()) 1836 getModule().setModuleInlineAsm(AsmString); 1837 else 1838 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 1839 break; 1840 } 1841 1842 default: 1843 // Make sure we handled everything we should, every other kind is a 1844 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 1845 // function. Need to recode Decl::Kind to do that easily. 1846 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1847 } 1848} 1849