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