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