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