CodeGenModule.cpp revision 206084
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/ErrorHandling.h" 39using namespace clang; 40using namespace CodeGen; 41 42 43CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 44 llvm::Module &M, const llvm::TargetData &TD, 45 Diagnostic &diags) 46 : BlockModule(C, M, TD, Types, *this), Context(C), 47 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 48 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 49 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()), 50 MangleCtx(C), VTables(*this), Runtime(0), 51 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0), 52 VMContext(M.getContext()) { 53 54 if (!Features.ObjC1) 55 Runtime = 0; 56 else if (!Features.NeXTRuntime) 57 Runtime = CreateGNUObjCRuntime(*this); 58 else if (Features.ObjCNonFragileABI) 59 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 60 else 61 Runtime = CreateMacObjCRuntime(*this); 62 63 // If debug info generation is enabled, create the CGDebugInfo object. 64 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0; 65} 66 67CodeGenModule::~CodeGenModule() { 68 delete Runtime; 69 delete DebugInfo; 70} 71 72void CodeGenModule::createObjCRuntime() { 73 if (!Features.NeXTRuntime) 74 Runtime = CreateGNUObjCRuntime(*this); 75 else if (Features.ObjCNonFragileABI) 76 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 77 else 78 Runtime = CreateMacObjCRuntime(*this); 79} 80 81void CodeGenModule::Release() { 82 EmitFundamentalRTTIDescriptors(); 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 // If the value has already been used, add it directly to the 693 // DeferredDeclsToEmit list. 694 MangleBuffer MangledName; 695 getMangledName(MangledName, GD); 696 if (GetGlobalValue(MangledName)) 697 DeferredDeclsToEmit.push_back(GD); 698 else { 699 // Otherwise, remember that we saw a deferred decl with this name. The 700 // first use of the mangled name will cause it to move into 701 // DeferredDeclsToEmit. 702 DeferredDecls[MangledName] = GD; 703 } 704 return; 705 } 706 707 // Otherwise emit the definition. 708 EmitGlobalDefinition(GD); 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 (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 722 EmitCXXConstructor(CD, GD.getCtorType()); 723 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 724 EmitCXXDestructor(DD, GD.getDtorType()); 725 else if (isa<FunctionDecl>(D)) 726 EmitGlobalFunctionDefinition(GD); 727 else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 728 EmitGlobalVarDefinition(VD); 729 else { 730 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 731 } 732} 733 734/// GetOrCreateLLVMFunction - If the specified mangled name is not in the 735/// module, create and return an llvm Function with the specified type. If there 736/// is something in the module with the specified name, return it potentially 737/// bitcasted to the right type. 738/// 739/// If D is non-null, it specifies a decl that correspond to this. This is used 740/// to set the attributes on the function when it is first created. 741llvm::Constant * 742CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName, 743 const llvm::Type *Ty, 744 GlobalDecl D) { 745 // Lookup the entry, lazily creating it if necessary. 746 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 747 if (Entry) { 748 if (WeakRefReferences.count(Entry)) { 749 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 750 if (FD && !FD->hasAttr<WeakAttr>()) 751 Entry->setLinkage(llvm::Function::ExternalLinkage); 752 753 WeakRefReferences.erase(Entry); 754 } 755 756 if (Entry->getType()->getElementType() == Ty) 757 return Entry; 758 759 // Make sure the result is of the correct type. 760 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 761 return llvm::ConstantExpr::getBitCast(Entry, PTy); 762 } 763 764 // This function doesn't have a complete type (for example, the return 765 // type is an incomplete struct). Use a fake type instead, and make 766 // sure not to try to set attributes. 767 bool IsIncompleteFunction = false; 768 if (!isa<llvm::FunctionType>(Ty)) { 769 Ty = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 770 std::vector<const llvm::Type*>(), false); 771 IsIncompleteFunction = true; 772 } 773 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 774 llvm::Function::ExternalLinkage, 775 MangledName, &getModule()); 776 assert(F->getName() == MangledName && "name was uniqued!"); 777 if (D.getDecl()) 778 SetFunctionAttributes(D, F, IsIncompleteFunction); 779 780 // This is the first use or definition of a mangled name. If there is a 781 // deferred decl with this name, remember that we need to emit it at the end 782 // of the file. 783 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 784 if (DDI != DeferredDecls.end()) { 785 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 786 // list, and remove it from DeferredDecls (since we don't need it anymore). 787 DeferredDeclsToEmit.push_back(DDI->second); 788 DeferredDecls.erase(DDI); 789 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) { 790 // If this the first reference to a C++ inline function in a class, queue up 791 // the deferred function body for emission. These are not seen as 792 // top-level declarations. 793 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD)) 794 DeferredDeclsToEmit.push_back(D); 795 // A called constructor which has no definition or declaration need be 796 // synthesized. 797 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 798 if (CD->isImplicit()) { 799 assert(CD->isUsed() && "Sema doesn't consider constructor as used."); 800 DeferredDeclsToEmit.push_back(D); 801 } 802 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) { 803 if (DD->isImplicit()) { 804 assert(DD->isUsed() && "Sema doesn't consider destructor as used."); 805 DeferredDeclsToEmit.push_back(D); 806 } 807 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 808 if (MD->isCopyAssignment() && MD->isImplicit()) { 809 assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used."); 810 DeferredDeclsToEmit.push_back(D); 811 } 812 } 813 } 814 815 return F; 816} 817 818/// GetAddrOfFunction - Return the address of the given function. If Ty is 819/// non-null, then this function will use the specified type if it has to 820/// create it (this occurs when we see a definition of the function). 821llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 822 const llvm::Type *Ty) { 823 // If there was no specific requested type, just convert it now. 824 if (!Ty) 825 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 826 MangleBuffer MangledName; 827 getMangledName(MangledName, GD); 828 return GetOrCreateLLVMFunction(MangledName, Ty, GD); 829} 830 831/// CreateRuntimeFunction - Create a new runtime function with the specified 832/// type and name. 833llvm::Constant * 834CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 835 llvm::StringRef Name) { 836 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl()); 837} 838 839static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) { 840 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 841 return false; 842 if (Context.getLangOptions().CPlusPlus && 843 Context.getBaseElementType(D->getType())->getAs<RecordType>()) { 844 // FIXME: We should do something fancier here! 845 return false; 846 } 847 return true; 848} 849 850/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 851/// create and return an llvm GlobalVariable with the specified type. If there 852/// is something in the module with the specified name, return it potentially 853/// bitcasted to the right type. 854/// 855/// If D is non-null, it specifies a decl that correspond to this. This is used 856/// to set the attributes on the global when it is first created. 857llvm::Constant * 858CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName, 859 const llvm::PointerType *Ty, 860 const VarDecl *D) { 861 // Lookup the entry, lazily creating it if necessary. 862 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 863 if (Entry) { 864 if (WeakRefReferences.count(Entry)) { 865 if (D && !D->hasAttr<WeakAttr>()) 866 Entry->setLinkage(llvm::Function::ExternalLinkage); 867 868 WeakRefReferences.erase(Entry); 869 } 870 871 if (Entry->getType() == Ty) 872 return Entry; 873 874 // Make sure the result is of the correct type. 875 return llvm::ConstantExpr::getBitCast(Entry, Ty); 876 } 877 878 // This is the first use or definition of a mangled name. If there is a 879 // deferred decl with this name, remember that we need to emit it at the end 880 // of the file. 881 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 882 if (DDI != DeferredDecls.end()) { 883 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 884 // list, and remove it from DeferredDecls (since we don't need it anymore). 885 DeferredDeclsToEmit.push_back(DDI->second); 886 DeferredDecls.erase(DDI); 887 } 888 889 llvm::GlobalVariable *GV = 890 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 891 llvm::GlobalValue::ExternalLinkage, 892 0, MangledName, 0, 893 false, Ty->getAddressSpace()); 894 895 // Handle things which are present even on external declarations. 896 if (D) { 897 // FIXME: This code is overly simple and should be merged with other global 898 // handling. 899 GV->setConstant(DeclIsConstantGlobal(Context, D)); 900 901 // FIXME: Merge with other attribute handling code. 902 if (D->getStorageClass() == VarDecl::PrivateExtern) 903 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 904 905 if (D->hasAttr<WeakAttr>() || 906 D->hasAttr<WeakImportAttr>()) 907 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 908 909 GV->setThreadLocal(D->isThreadSpecified()); 910 } 911 912 return GV; 913} 914 915 916/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 917/// given global variable. If Ty is non-null and if the global doesn't exist, 918/// then it will be greated with the specified type instead of whatever the 919/// normal requested type would be. 920llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 921 const llvm::Type *Ty) { 922 assert(D->hasGlobalStorage() && "Not a global variable"); 923 QualType ASTTy = D->getType(); 924 if (Ty == 0) 925 Ty = getTypes().ConvertTypeForMem(ASTTy); 926 927 const llvm::PointerType *PTy = 928 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 929 930 MangleBuffer MangledName; 931 getMangledName(MangledName, D); 932 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 933} 934 935/// CreateRuntimeVariable - Create a new runtime global variable with the 936/// specified type and name. 937llvm::Constant * 938CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 939 llvm::StringRef Name) { 940 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 941} 942 943void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 944 assert(!D->getInit() && "Cannot emit definite definitions here!"); 945 946 if (MayDeferGeneration(D)) { 947 // If we have not seen a reference to this variable yet, place it 948 // into the deferred declarations table to be emitted if needed 949 // later. 950 MangleBuffer MangledName; 951 getMangledName(MangledName, D); 952 if (!GetGlobalValue(MangledName)) { 953 DeferredDecls[MangledName] = D; 954 return; 955 } 956 } 957 958 // The tentative definition is the only definition. 959 EmitGlobalVarDefinition(D); 960} 961 962llvm::GlobalVariable::LinkageTypes 963CodeGenModule::getVtableLinkage(const CXXRecordDecl *RD) { 964 if (RD->isInAnonymousNamespace() || !RD->hasLinkage()) 965 return llvm::GlobalVariable::InternalLinkage; 966 967 if (const CXXMethodDecl *KeyFunction 968 = RD->getASTContext().getKeyFunction(RD)) { 969 // If this class has a key function, use that to determine the linkage of 970 // the vtable. 971 const FunctionDecl *Def = 0; 972 if (KeyFunction->getBody(Def)) 973 KeyFunction = cast<CXXMethodDecl>(Def); 974 975 switch (KeyFunction->getTemplateSpecializationKind()) { 976 case TSK_Undeclared: 977 case TSK_ExplicitSpecialization: 978 if (KeyFunction->isInlined()) 979 return llvm::GlobalVariable::WeakODRLinkage; 980 981 return llvm::GlobalVariable::ExternalLinkage; 982 983 case TSK_ImplicitInstantiation: 984 case TSK_ExplicitInstantiationDefinition: 985 return llvm::GlobalVariable::WeakODRLinkage; 986 987 case TSK_ExplicitInstantiationDeclaration: 988 // FIXME: Use available_externally linkage. However, this currently 989 // breaks LLVM's build due to undefined symbols. 990 // return llvm::GlobalVariable::AvailableExternallyLinkage; 991 return llvm::GlobalVariable::WeakODRLinkage; 992 } 993 } 994 995 switch (RD->getTemplateSpecializationKind()) { 996 case TSK_Undeclared: 997 case TSK_ExplicitSpecialization: 998 case TSK_ImplicitInstantiation: 999 case TSK_ExplicitInstantiationDefinition: 1000 return llvm::GlobalVariable::WeakODRLinkage; 1001 1002 case TSK_ExplicitInstantiationDeclaration: 1003 // FIXME: Use available_externally linkage. However, this currently 1004 // breaks LLVM's build due to undefined symbols. 1005 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1006 return llvm::GlobalVariable::WeakODRLinkage; 1007 } 1008 1009 // Silence GCC warning. 1010 return llvm::GlobalVariable::WeakODRLinkage; 1011} 1012 1013static CodeGenModule::GVALinkage 1014GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) { 1015 // If this is a static data member, compute the kind of template 1016 // specialization. Otherwise, this variable is not part of a 1017 // template. 1018 TemplateSpecializationKind TSK = TSK_Undeclared; 1019 if (VD->isStaticDataMember()) 1020 TSK = VD->getTemplateSpecializationKind(); 1021 1022 Linkage L = VD->getLinkage(); 1023 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus && 1024 VD->getType()->getLinkage() == UniqueExternalLinkage) 1025 L = UniqueExternalLinkage; 1026 1027 switch (L) { 1028 case NoLinkage: 1029 case InternalLinkage: 1030 case UniqueExternalLinkage: 1031 return CodeGenModule::GVA_Internal; 1032 1033 case ExternalLinkage: 1034 switch (TSK) { 1035 case TSK_Undeclared: 1036 case TSK_ExplicitSpecialization: 1037 return CodeGenModule::GVA_StrongExternal; 1038 1039 case TSK_ExplicitInstantiationDeclaration: 1040 llvm_unreachable("Variable should not be instantiated"); 1041 // Fall through to treat this like any other instantiation. 1042 1043 case TSK_ExplicitInstantiationDefinition: 1044 return CodeGenModule::GVA_ExplicitTemplateInstantiation; 1045 1046 case TSK_ImplicitInstantiation: 1047 return CodeGenModule::GVA_TemplateInstantiation; 1048 } 1049 } 1050 1051 return CodeGenModule::GVA_StrongExternal; 1052} 1053 1054CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const { 1055 return CharUnits::fromQuantity( 1056 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth()); 1057} 1058 1059void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1060 llvm::Constant *Init = 0; 1061 QualType ASTTy = D->getType(); 1062 bool NonConstInit = false; 1063 1064 const Expr *InitExpr = D->getAnyInitializer(); 1065 1066 if (!InitExpr) { 1067 // This is a tentative definition; tentative definitions are 1068 // implicitly initialized with { 0 }. 1069 // 1070 // Note that tentative definitions are only emitted at the end of 1071 // a translation unit, so they should never have incomplete 1072 // type. In addition, EmitTentativeDefinition makes sure that we 1073 // never attempt to emit a tentative definition if a real one 1074 // exists. A use may still exists, however, so we still may need 1075 // to do a RAUW. 1076 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1077 Init = EmitNullConstant(D->getType()); 1078 } else { 1079 Init = EmitConstantExpr(InitExpr, D->getType()); 1080 1081 if (!Init) { 1082 QualType T = InitExpr->getType(); 1083 if (getLangOptions().CPlusPlus) { 1084 EmitCXXGlobalVarDeclInitFunc(D); 1085 Init = EmitNullConstant(T); 1086 NonConstInit = true; 1087 } else { 1088 ErrorUnsupported(D, "static initializer"); 1089 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1090 } 1091 } 1092 } 1093 1094 const llvm::Type* InitType = Init->getType(); 1095 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1096 1097 // Strip off a bitcast if we got one back. 1098 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1099 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1100 // all zero index gep. 1101 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1102 Entry = CE->getOperand(0); 1103 } 1104 1105 // Entry is now either a Function or GlobalVariable. 1106 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1107 1108 // We have a definition after a declaration with the wrong type. 1109 // We must make a new GlobalVariable* and update everything that used OldGV 1110 // (a declaration or tentative definition) with the new GlobalVariable* 1111 // (which will be a definition). 1112 // 1113 // This happens if there is a prototype for a global (e.g. 1114 // "extern int x[];") and then a definition of a different type (e.g. 1115 // "int x[10];"). This also happens when an initializer has a different type 1116 // from the type of the global (this happens with unions). 1117 if (GV == 0 || 1118 GV->getType()->getElementType() != InitType || 1119 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1120 1121 // Move the old entry aside so that we'll create a new one. 1122 Entry->setName(llvm::StringRef()); 1123 1124 // Make a new global with the correct type, this is now guaranteed to work. 1125 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1126 1127 // Replace all uses of the old global with the new global 1128 llvm::Constant *NewPtrForOldDecl = 1129 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1130 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1131 1132 // Erase the old global, since it is no longer used. 1133 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1134 } 1135 1136 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1137 SourceManager &SM = Context.getSourceManager(); 1138 AddAnnotation(EmitAnnotateAttr(GV, AA, 1139 SM.getInstantiationLineNumber(D->getLocation()))); 1140 } 1141 1142 GV->setInitializer(Init); 1143 1144 // If it is safe to mark the global 'constant', do so now. 1145 GV->setConstant(false); 1146 if (!NonConstInit && DeclIsConstantGlobal(Context, D)) 1147 GV->setConstant(true); 1148 1149 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1150 1151 // Set the llvm linkage type as appropriate. 1152 GVALinkage Linkage = GetLinkageForVariable(getContext(), D); 1153 if (Linkage == GVA_Internal) 1154 GV->setLinkage(llvm::Function::InternalLinkage); 1155 else if (D->hasAttr<DLLImportAttr>()) 1156 GV->setLinkage(llvm::Function::DLLImportLinkage); 1157 else if (D->hasAttr<DLLExportAttr>()) 1158 GV->setLinkage(llvm::Function::DLLExportLinkage); 1159 else if (D->hasAttr<WeakAttr>()) { 1160 if (GV->isConstant()) 1161 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage); 1162 else 1163 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1164 } else if (Linkage == GVA_TemplateInstantiation || 1165 Linkage == GVA_ExplicitTemplateInstantiation) 1166 // FIXME: It seems like we can provide more specific linkage here 1167 // (LinkOnceODR, WeakODR). 1168 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1169 else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon && 1170 !D->hasExternalStorage() && !D->getInit() && 1171 !D->getAttr<SectionAttr>()) { 1172 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 1173 // common vars aren't constant even if declared const. 1174 GV->setConstant(false); 1175 } else 1176 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 1177 1178 SetCommonAttributes(D, GV); 1179 1180 // Emit global variable debug information. 1181 if (CGDebugInfo *DI = getDebugInfo()) { 1182 DI->setLocation(D->getLocation()); 1183 DI->EmitGlobalVariable(GV, D); 1184 } 1185} 1186 1187/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1188/// implement a function with no prototype, e.g. "int foo() {}". If there are 1189/// existing call uses of the old function in the module, this adjusts them to 1190/// call the new function directly. 1191/// 1192/// This is not just a cleanup: the always_inline pass requires direct calls to 1193/// functions to be able to inline them. If there is a bitcast in the way, it 1194/// won't inline them. Instcombine normally deletes these calls, but it isn't 1195/// run at -O0. 1196static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1197 llvm::Function *NewFn) { 1198 // If we're redefining a global as a function, don't transform it. 1199 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1200 if (OldFn == 0) return; 1201 1202 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1203 llvm::SmallVector<llvm::Value*, 4> ArgList; 1204 1205 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1206 UI != E; ) { 1207 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1208 unsigned OpNo = UI.getOperandNo(); 1209 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++); 1210 if (!CI || OpNo != 0) continue; 1211 1212 // If the return types don't match exactly, and if the call isn't dead, then 1213 // we can't transform this call. 1214 if (CI->getType() != NewRetTy && !CI->use_empty()) 1215 continue; 1216 1217 // If the function was passed too few arguments, don't transform. If extra 1218 // arguments were passed, we silently drop them. If any of the types 1219 // mismatch, we don't transform. 1220 unsigned ArgNo = 0; 1221 bool DontTransform = false; 1222 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1223 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1224 if (CI->getNumOperands()-1 == ArgNo || 1225 CI->getOperand(ArgNo+1)->getType() != AI->getType()) { 1226 DontTransform = true; 1227 break; 1228 } 1229 } 1230 if (DontTransform) 1231 continue; 1232 1233 // Okay, we can transform this. Create the new call instruction and copy 1234 // over the required information. 1235 ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo); 1236 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1237 ArgList.end(), "", CI); 1238 ArgList.clear(); 1239 if (!NewCall->getType()->isVoidTy()) 1240 NewCall->takeName(CI); 1241 NewCall->setAttributes(CI->getAttributes()); 1242 NewCall->setCallingConv(CI->getCallingConv()); 1243 1244 // Finally, remove the old call, replacing any uses with the new one. 1245 if (!CI->use_empty()) 1246 CI->replaceAllUsesWith(NewCall); 1247 1248 // Copy debug location attached to CI. 1249 if (!CI->getDebugLoc().isUnknown()) 1250 NewCall->setDebugLoc(CI->getDebugLoc()); 1251 CI->eraseFromParent(); 1252 } 1253} 1254 1255 1256void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1257 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1258 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD); 1259 getMangleContext().mangleInitDiscriminator(); 1260 // Get or create the prototype for the function. 1261 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1262 1263 // Strip off a bitcast if we got one back. 1264 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1265 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1266 Entry = CE->getOperand(0); 1267 } 1268 1269 1270 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1271 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1272 1273 // If the types mismatch then we have to rewrite the definition. 1274 assert(OldFn->isDeclaration() && 1275 "Shouldn't replace non-declaration"); 1276 1277 // F is the Function* for the one with the wrong type, we must make a new 1278 // Function* and update everything that used F (a declaration) with the new 1279 // Function* (which will be a definition). 1280 // 1281 // This happens if there is a prototype for a function 1282 // (e.g. "int f()") and then a definition of a different type 1283 // (e.g. "int f(int x)"). Move the old function aside so that it 1284 // doesn't interfere with GetAddrOfFunction. 1285 OldFn->setName(llvm::StringRef()); 1286 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1287 1288 // If this is an implementation of a function without a prototype, try to 1289 // replace any existing uses of the function (which may be calls) with uses 1290 // of the new function 1291 if (D->getType()->isFunctionNoProtoType()) { 1292 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1293 OldFn->removeDeadConstantUsers(); 1294 } 1295 1296 // Replace uses of F with the Function we will endow with a body. 1297 if (!Entry->use_empty()) { 1298 llvm::Constant *NewPtrForOldDecl = 1299 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1300 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1301 } 1302 1303 // Ok, delete the old function now, which is dead. 1304 OldFn->eraseFromParent(); 1305 1306 Entry = NewFn; 1307 } 1308 1309 llvm::Function *Fn = cast<llvm::Function>(Entry); 1310 1311 CodeGenFunction(*this).GenerateCode(D, Fn); 1312 1313 SetFunctionDefinitionAttributes(D, Fn); 1314 SetLLVMFunctionAttributesForDefinition(D, Fn); 1315 1316 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1317 AddGlobalCtor(Fn, CA->getPriority()); 1318 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1319 AddGlobalDtor(Fn, DA->getPriority()); 1320} 1321 1322void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1323 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1324 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1325 assert(AA && "Not an alias?"); 1326 1327 MangleBuffer MangledName; 1328 getMangledName(MangledName, GD); 1329 1330 // If there is a definition in the module, then it wins over the alias. 1331 // This is dubious, but allow it to be safe. Just ignore the alias. 1332 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1333 if (Entry && !Entry->isDeclaration()) 1334 return; 1335 1336 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1337 1338 // Create a reference to the named value. This ensures that it is emitted 1339 // if a deferred decl. 1340 llvm::Constant *Aliasee; 1341 if (isa<llvm::FunctionType>(DeclTy)) 1342 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl()); 1343 else 1344 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1345 llvm::PointerType::getUnqual(DeclTy), 0); 1346 1347 // Create the new alias itself, but don't set a name yet. 1348 llvm::GlobalValue *GA = 1349 new llvm::GlobalAlias(Aliasee->getType(), 1350 llvm::Function::ExternalLinkage, 1351 "", Aliasee, &getModule()); 1352 1353 if (Entry) { 1354 assert(Entry->isDeclaration()); 1355 1356 // If there is a declaration in the module, then we had an extern followed 1357 // by the alias, as in: 1358 // extern int test6(); 1359 // ... 1360 // int test6() __attribute__((alias("test7"))); 1361 // 1362 // Remove it and replace uses of it with the alias. 1363 GA->takeName(Entry); 1364 1365 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1366 Entry->getType())); 1367 Entry->eraseFromParent(); 1368 } else { 1369 GA->setName(MangledName.getString()); 1370 } 1371 1372 // Set attributes which are particular to an alias; this is a 1373 // specialization of the attributes which may be set on a global 1374 // variable/function. 1375 if (D->hasAttr<DLLExportAttr>()) { 1376 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1377 // The dllexport attribute is ignored for undefined symbols. 1378 if (FD->getBody()) 1379 GA->setLinkage(llvm::Function::DLLExportLinkage); 1380 } else { 1381 GA->setLinkage(llvm::Function::DLLExportLinkage); 1382 } 1383 } else if (D->hasAttr<WeakAttr>() || 1384 D->hasAttr<WeakRefAttr>() || 1385 D->hasAttr<WeakImportAttr>()) { 1386 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1387 } 1388 1389 SetCommonAttributes(D, GA); 1390} 1391 1392/// getBuiltinLibFunction - Given a builtin id for a function like 1393/// "__builtin_fabsf", return a Function* for "fabsf". 1394llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1395 unsigned BuiltinID) { 1396 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1397 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1398 "isn't a lib fn"); 1399 1400 // Get the name, skip over the __builtin_ prefix (if necessary). 1401 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1402 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1403 Name += 10; 1404 1405 const llvm::FunctionType *Ty = 1406 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType())); 1407 1408 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1409} 1410 1411llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1412 unsigned NumTys) { 1413 return llvm::Intrinsic::getDeclaration(&getModule(), 1414 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1415} 1416 1417llvm::Function *CodeGenModule::getMemCpyFn() { 1418 if (MemCpyFn) return MemCpyFn; 1419 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1420 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1); 1421} 1422 1423llvm::Function *CodeGenModule::getMemMoveFn() { 1424 if (MemMoveFn) return MemMoveFn; 1425 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1426 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1); 1427} 1428 1429llvm::Function *CodeGenModule::getMemSetFn() { 1430 if (MemSetFn) return MemSetFn; 1431 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1432 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1); 1433} 1434 1435static llvm::StringMapEntry<llvm::Constant*> & 1436GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1437 const StringLiteral *Literal, 1438 bool TargetIsLSB, 1439 bool &IsUTF16, 1440 unsigned &StringLength) { 1441 unsigned NumBytes = Literal->getByteLength(); 1442 1443 // Check for simple case. 1444 if (!Literal->containsNonAsciiOrNull()) { 1445 StringLength = NumBytes; 1446 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1447 StringLength)); 1448 } 1449 1450 // Otherwise, convert the UTF8 literals into a byte string. 1451 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1452 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData(); 1453 UTF16 *ToPtr = &ToBuf[0]; 1454 1455 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1456 &ToPtr, ToPtr + NumBytes, 1457 strictConversion); 1458 1459 // Check for conversion failure. 1460 if (Result != conversionOK) { 1461 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove 1462 // this duplicate code. 1463 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed"); 1464 StringLength = NumBytes; 1465 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1466 StringLength)); 1467 } 1468 1469 // ConvertUTF8toUTF16 returns the length in ToPtr. 1470 StringLength = ToPtr - &ToBuf[0]; 1471 1472 // Render the UTF-16 string into a byte array and convert to the target byte 1473 // order. 1474 // 1475 // FIXME: This isn't something we should need to do here. 1476 llvm::SmallString<128> AsBytes; 1477 AsBytes.reserve(StringLength * 2); 1478 for (unsigned i = 0; i != StringLength; ++i) { 1479 unsigned short Val = ToBuf[i]; 1480 if (TargetIsLSB) { 1481 AsBytes.push_back(Val & 0xFF); 1482 AsBytes.push_back(Val >> 8); 1483 } else { 1484 AsBytes.push_back(Val >> 8); 1485 AsBytes.push_back(Val & 0xFF); 1486 } 1487 } 1488 // Append one extra null character, the second is automatically added by our 1489 // caller. 1490 AsBytes.push_back(0); 1491 1492 IsUTF16 = true; 1493 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1494} 1495 1496llvm::Constant * 1497CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1498 unsigned StringLength = 0; 1499 bool isUTF16 = false; 1500 llvm::StringMapEntry<llvm::Constant*> &Entry = 1501 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1502 getTargetData().isLittleEndian(), 1503 isUTF16, StringLength); 1504 1505 if (llvm::Constant *C = Entry.getValue()) 1506 return C; 1507 1508 llvm::Constant *Zero = 1509 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1510 llvm::Constant *Zeros[] = { Zero, Zero }; 1511 1512 // If we don't already have it, get __CFConstantStringClassReference. 1513 if (!CFConstantStringClassRef) { 1514 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1515 Ty = llvm::ArrayType::get(Ty, 0); 1516 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1517 "__CFConstantStringClassReference"); 1518 // Decay array -> ptr 1519 CFConstantStringClassRef = 1520 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1521 } 1522 1523 QualType CFTy = getContext().getCFConstantStringType(); 1524 1525 const llvm::StructType *STy = 1526 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1527 1528 std::vector<llvm::Constant*> Fields(4); 1529 1530 // Class pointer. 1531 Fields[0] = CFConstantStringClassRef; 1532 1533 // Flags. 1534 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1535 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1536 llvm::ConstantInt::get(Ty, 0x07C8); 1537 1538 // String pointer. 1539 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1540 1541 llvm::GlobalValue::LinkageTypes Linkage; 1542 bool isConstant; 1543 if (isUTF16) { 1544 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1545 Linkage = llvm::GlobalValue::InternalLinkage; 1546 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1547 // does make plain ascii ones writable. 1548 isConstant = true; 1549 } else { 1550 Linkage = llvm::GlobalValue::PrivateLinkage; 1551 isConstant = !Features.WritableStrings; 1552 } 1553 1554 llvm::GlobalVariable *GV = 1555 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1556 ".str"); 1557 if (isUTF16) { 1558 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1559 GV->setAlignment(Align.getQuantity()); 1560 } 1561 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1562 1563 // String length. 1564 Ty = getTypes().ConvertType(getContext().LongTy); 1565 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1566 1567 // The struct. 1568 C = llvm::ConstantStruct::get(STy, Fields); 1569 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1570 llvm::GlobalVariable::PrivateLinkage, C, 1571 "_unnamed_cfstring_"); 1572 if (const char *Sect = getContext().Target.getCFStringSection()) 1573 GV->setSection(Sect); 1574 Entry.setValue(GV); 1575 1576 return GV; 1577} 1578 1579/// GetStringForStringLiteral - Return the appropriate bytes for a 1580/// string literal, properly padded to match the literal type. 1581std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1582 const char *StrData = E->getStrData(); 1583 unsigned Len = E->getByteLength(); 1584 1585 const ConstantArrayType *CAT = 1586 getContext().getAsConstantArrayType(E->getType()); 1587 assert(CAT && "String isn't pointer or array!"); 1588 1589 // Resize the string to the right size. 1590 std::string Str(StrData, StrData+Len); 1591 uint64_t RealLen = CAT->getSize().getZExtValue(); 1592 1593 if (E->isWide()) 1594 RealLen *= getContext().Target.getWCharWidth()/8; 1595 1596 Str.resize(RealLen, '\0'); 1597 1598 return Str; 1599} 1600 1601/// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1602/// constant array for the given string literal. 1603llvm::Constant * 1604CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1605 // FIXME: This can be more efficient. 1606 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1607 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S)); 1608 if (S->isWide()) { 1609 llvm::Type *DestTy = 1610 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1611 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1612 } 1613 return C; 1614} 1615 1616/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1617/// array for the given ObjCEncodeExpr node. 1618llvm::Constant * 1619CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1620 std::string Str; 1621 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1622 1623 return GetAddrOfConstantCString(Str); 1624} 1625 1626 1627/// GenerateWritableString -- Creates storage for a string literal. 1628static llvm::Constant *GenerateStringLiteral(const std::string &str, 1629 bool constant, 1630 CodeGenModule &CGM, 1631 const char *GlobalName) { 1632 // Create Constant for this string literal. Don't add a '\0'. 1633 llvm::Constant *C = 1634 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1635 1636 // Create a global variable for this string 1637 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1638 llvm::GlobalValue::PrivateLinkage, 1639 C, GlobalName); 1640} 1641 1642/// GetAddrOfConstantString - Returns a pointer to a character array 1643/// containing the literal. This contents are exactly that of the 1644/// given string, i.e. it will not be null terminated automatically; 1645/// see GetAddrOfConstantCString. Note that whether the result is 1646/// actually a pointer to an LLVM constant depends on 1647/// Feature.WriteableStrings. 1648/// 1649/// The result has pointer to array type. 1650llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1651 const char *GlobalName) { 1652 bool IsConstant = !Features.WritableStrings; 1653 1654 // Get the default prefix if a name wasn't specified. 1655 if (!GlobalName) 1656 GlobalName = ".str"; 1657 1658 // Don't share any string literals if strings aren't constant. 1659 if (!IsConstant) 1660 return GenerateStringLiteral(str, false, *this, GlobalName); 1661 1662 llvm::StringMapEntry<llvm::Constant *> &Entry = 1663 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1664 1665 if (Entry.getValue()) 1666 return Entry.getValue(); 1667 1668 // Create a global variable for this. 1669 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1670 Entry.setValue(C); 1671 return C; 1672} 1673 1674/// GetAddrOfConstantCString - Returns a pointer to a character 1675/// array containing the literal and a terminating '\-' 1676/// character. The result has pointer to array type. 1677llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1678 const char *GlobalName){ 1679 return GetAddrOfConstantString(str + '\0', GlobalName); 1680} 1681 1682/// EmitObjCPropertyImplementations - Emit information for synthesized 1683/// properties for an implementation. 1684void CodeGenModule::EmitObjCPropertyImplementations(const 1685 ObjCImplementationDecl *D) { 1686 for (ObjCImplementationDecl::propimpl_iterator 1687 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1688 ObjCPropertyImplDecl *PID = *i; 1689 1690 // Dynamic is just for type-checking. 1691 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1692 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1693 1694 // Determine which methods need to be implemented, some may have 1695 // been overridden. Note that ::isSynthesized is not the method 1696 // we want, that just indicates if the decl came from a 1697 // property. What we want to know is if the method is defined in 1698 // this implementation. 1699 if (!D->getInstanceMethod(PD->getGetterName())) 1700 CodeGenFunction(*this).GenerateObjCGetter( 1701 const_cast<ObjCImplementationDecl *>(D), PID); 1702 if (!PD->isReadOnly() && 1703 !D->getInstanceMethod(PD->getSetterName())) 1704 CodeGenFunction(*this).GenerateObjCSetter( 1705 const_cast<ObjCImplementationDecl *>(D), PID); 1706 } 1707 } 1708} 1709 1710/// EmitNamespace - Emit all declarations in a namespace. 1711void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1712 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1713 I != E; ++I) 1714 EmitTopLevelDecl(*I); 1715} 1716 1717// EmitLinkageSpec - Emit all declarations in a linkage spec. 1718void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1719 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1720 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1721 ErrorUnsupported(LSD, "linkage spec"); 1722 return; 1723 } 1724 1725 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1726 I != E; ++I) 1727 EmitTopLevelDecl(*I); 1728} 1729 1730/// EmitTopLevelDecl - Emit code for a single top level declaration. 1731void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1732 // If an error has occurred, stop code generation, but continue 1733 // parsing and semantic analysis (to ensure all warnings and errors 1734 // are emitted). 1735 if (Diags.hasErrorOccurred()) 1736 return; 1737 1738 // Ignore dependent declarations. 1739 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1740 return; 1741 1742 switch (D->getKind()) { 1743 case Decl::CXXConversion: 1744 case Decl::CXXMethod: 1745 case Decl::Function: 1746 // Skip function templates 1747 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1748 return; 1749 1750 EmitGlobal(cast<FunctionDecl>(D)); 1751 break; 1752 1753 case Decl::Var: 1754 EmitGlobal(cast<VarDecl>(D)); 1755 break; 1756 1757 // C++ Decls 1758 case Decl::Namespace: 1759 EmitNamespace(cast<NamespaceDecl>(D)); 1760 break; 1761 // No code generation needed. 1762 case Decl::UsingShadow: 1763 case Decl::Using: 1764 case Decl::UsingDirective: 1765 case Decl::ClassTemplate: 1766 case Decl::FunctionTemplate: 1767 case Decl::NamespaceAlias: 1768 break; 1769 case Decl::CXXConstructor: 1770 // Skip function templates 1771 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1772 return; 1773 1774 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 1775 break; 1776 case Decl::CXXDestructor: 1777 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 1778 break; 1779 1780 case Decl::StaticAssert: 1781 // Nothing to do. 1782 break; 1783 1784 // Objective-C Decls 1785 1786 // Forward declarations, no (immediate) code generation. 1787 case Decl::ObjCClass: 1788 case Decl::ObjCForwardProtocol: 1789 case Decl::ObjCCategory: 1790 case Decl::ObjCInterface: 1791 break; 1792 1793 case Decl::ObjCProtocol: 1794 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1795 break; 1796 1797 case Decl::ObjCCategoryImpl: 1798 // Categories have properties but don't support synthesize so we 1799 // can ignore them here. 1800 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1801 break; 1802 1803 case Decl::ObjCImplementation: { 1804 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1805 EmitObjCPropertyImplementations(OMD); 1806 Runtime->GenerateClass(OMD); 1807 break; 1808 } 1809 case Decl::ObjCMethod: { 1810 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1811 // If this is not a prototype, emit the body. 1812 if (OMD->getBody()) 1813 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1814 break; 1815 } 1816 case Decl::ObjCCompatibleAlias: 1817 // compatibility-alias is a directive and has no code gen. 1818 break; 1819 1820 case Decl::LinkageSpec: 1821 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 1822 break; 1823 1824 case Decl::FileScopeAsm: { 1825 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1826 llvm::StringRef AsmString = AD->getAsmString()->getString(); 1827 1828 const std::string &S = getModule().getModuleInlineAsm(); 1829 if (S.empty()) 1830 getModule().setModuleInlineAsm(AsmString); 1831 else 1832 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 1833 break; 1834 } 1835 1836 default: 1837 // Make sure we handled everything we should, every other kind is a 1838 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 1839 // function. Need to recode Decl::Kind to do that easily. 1840 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1841 } 1842} 1843