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 "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGCall.h" 18 #include "CGDebugInfo.h" 19 #include "CGObjCRuntime.h" 20 #include "CGOpenCLRuntime.h" 21 #include "CodeGenFunction.h" 22 #include "CodeGenTBAA.h" 23 #include "TargetInfo.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/CharUnits.h" 26 #include "clang/AST/DeclCXX.h" 27 #include "clang/AST/DeclObjC.h" 28 #include "clang/AST/DeclTemplate.h" 29 #include "clang/AST/Mangle.h" 30 #include "clang/AST/RecordLayout.h" 31 #include "clang/AST/RecursiveASTVisitor.h" 32 #include "clang/Basic/Builtins.h" 33 #include "clang/Basic/CharInfo.h" 34 #include "clang/Basic/Diagnostic.h" 35 #include "clang/Basic/Module.h" 36 #include "clang/Basic/SourceManager.h" 37 #include "clang/Basic/TargetInfo.h" 38 #include "clang/Basic/Version.h" 39 #include "clang/Frontend/CodeGenOptions.h" 40 #include "clang/Sema/SemaDiagnostic.h" 41 #include "llvm/ADT/APSInt.h" 42 #include "llvm/ADT/Triple.h" 43 #include "llvm/IR/CallingConv.h" 44 #include "llvm/IR/DataLayout.h" 45 #include "llvm/IR/Intrinsics.h" 46 #include "llvm/IR/LLVMContext.h" 47 #include "llvm/IR/Module.h" 48 #include "llvm/Support/CallSite.h" 49 #include "llvm/Support/ConvertUTF.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Target/Mangler.h" 52 53 using namespace clang; 54 using namespace CodeGen; 55 56 static const char AnnotationSection[] = "llvm.metadata"; 57 58 static CGCXXABI &createCXXABI(CodeGenModule &CGM) { 59 switch (CGM.getTarget().getCXXABI().getKind()) { 60 case TargetCXXABI::GenericAArch64: 61 case TargetCXXABI::GenericARM: 62 case TargetCXXABI::iOS: 63 case TargetCXXABI::GenericItanium: 64 return *CreateItaniumCXXABI(CGM); 65 case TargetCXXABI::Microsoft: 66 return *CreateMicrosoftCXXABI(CGM); 67 } 68 69 llvm_unreachable("invalid C++ ABI kind"); 70 } 71 72 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 73 llvm::Module &M, const llvm::DataLayout &TD, 74 DiagnosticsEngine &diags) 75 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M), 76 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()), 77 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0), 78 TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0), 79 OpenCLRuntime(0), CUDARuntime(0), DebugInfo(0), ARCData(0), 80 NoObjCARCExceptionsMetadata(0), RRData(0), CFConstantStringClassRef(0), 81 ConstantStringClassRef(0), NSConstantStringType(0), 82 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0), 83 BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0), 84 LifetimeStartFn(0), LifetimeEndFn(0), 85 SanitizerBlacklist( 86 llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)), 87 SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled 88 : LangOpts.Sanitize) { 89 90 // Initialize the type cache. 91 llvm::LLVMContext &LLVMContext = M.getContext(); 92 VoidTy = llvm::Type::getVoidTy(LLVMContext); 93 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 94 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 95 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 96 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 97 FloatTy = llvm::Type::getFloatTy(LLVMContext); 98 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 99 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 100 PointerAlignInBytes = 101 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 102 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 103 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 104 Int8PtrTy = Int8Ty->getPointerTo(0); 105 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 106 107 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 108 109 if (LangOpts.ObjC1) 110 createObjCRuntime(); 111 if (LangOpts.OpenCL) 112 createOpenCLRuntime(); 113 if (LangOpts.CUDA) 114 createCUDARuntime(); 115 116 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 117 if (SanOpts.Thread || 118 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 119 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 120 ABI.getMangleContext()); 121 122 // If debug info or coverage generation is enabled, create the CGDebugInfo 123 // object. 124 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo || 125 CodeGenOpts.EmitGcovArcs || 126 CodeGenOpts.EmitGcovNotes) 127 DebugInfo = new CGDebugInfo(*this); 128 129 Block.GlobalUniqueCount = 0; 130 131 if (C.getLangOpts().ObjCAutoRefCount) 132 ARCData = new ARCEntrypoints(); 133 RRData = new RREntrypoints(); 134 } 135 136 CodeGenModule::~CodeGenModule() { 137 delete ObjCRuntime; 138 delete OpenCLRuntime; 139 delete CUDARuntime; 140 delete TheTargetCodeGenInfo; 141 delete &ABI; 142 delete TBAA; 143 delete DebugInfo; 144 delete ARCData; 145 delete RRData; 146 } 147 148 void CodeGenModule::createObjCRuntime() { 149 // This is just isGNUFamily(), but we want to force implementors of 150 // new ABIs to decide how best to do this. 151 switch (LangOpts.ObjCRuntime.getKind()) { 152 case ObjCRuntime::GNUstep: 153 case ObjCRuntime::GCC: 154 case ObjCRuntime::ObjFW: 155 ObjCRuntime = CreateGNUObjCRuntime(*this); 156 return; 157 158 case ObjCRuntime::FragileMacOSX: 159 case ObjCRuntime::MacOSX: 160 case ObjCRuntime::iOS: 161 ObjCRuntime = CreateMacObjCRuntime(*this); 162 return; 163 } 164 llvm_unreachable("bad runtime kind"); 165 } 166 167 void CodeGenModule::createOpenCLRuntime() { 168 OpenCLRuntime = new CGOpenCLRuntime(*this); 169 } 170 171 void CodeGenModule::createCUDARuntime() { 172 CUDARuntime = CreateNVCUDARuntime(*this); 173 } 174 175 void CodeGenModule::applyReplacements() { 176 for (ReplacementsTy::iterator I = Replacements.begin(), 177 E = Replacements.end(); 178 I != E; ++I) { 179 StringRef MangledName = I->first(); 180 llvm::Constant *Replacement = I->second; 181 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 182 if (!Entry) 183 continue; 184 Entry->replaceAllUsesWith(Replacement); 185 Entry->eraseFromParent(); 186 } 187 } 188 189 void CodeGenModule::checkAliases() { 190 bool Error = false; 191 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 192 E = Aliases.end(); I != E; ++I) { 193 const GlobalDecl &GD = *I; 194 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 195 const AliasAttr *AA = D->getAttr<AliasAttr>(); 196 StringRef MangledName = getMangledName(GD); 197 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 198 llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry); 199 llvm::GlobalValue *GV = Alias->getAliasedGlobal(); 200 if (GV->isDeclaration()) { 201 Error = true; 202 getDiags().Report(AA->getLocation(), diag::err_alias_to_undefined); 203 } else if (!Alias->resolveAliasedGlobal(/*stopOnWeak*/ false)) { 204 Error = true; 205 getDiags().Report(AA->getLocation(), diag::err_cyclic_alias); 206 } 207 } 208 if (!Error) 209 return; 210 211 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 212 E = Aliases.end(); I != E; ++I) { 213 const GlobalDecl &GD = *I; 214 StringRef MangledName = getMangledName(GD); 215 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 216 llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry); 217 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 218 Alias->eraseFromParent(); 219 } 220 } 221 222 void CodeGenModule::Release() { 223 EmitDeferred(); 224 applyReplacements(); 225 checkAliases(); 226 EmitCXXGlobalInitFunc(); 227 EmitCXXGlobalDtorFunc(); 228 EmitCXXThreadLocalInitFunc(); 229 if (ObjCRuntime) 230 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 231 AddGlobalCtor(ObjCInitFunction); 232 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 233 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 234 EmitGlobalAnnotations(); 235 EmitStaticExternCAliases(); 236 EmitLLVMUsed(); 237 238 if (CodeGenOpts.Autolink && 239 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 240 EmitModuleLinkOptions(); 241 } 242 if (CodeGenOpts.DwarfVersion) 243 // We actually want the latest version when there are conflicts. 244 // We can change from Warning to Latest if such mode is supported. 245 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 246 CodeGenOpts.DwarfVersion); 247 248 SimplifyPersonality(); 249 250 if (getCodeGenOpts().EmitDeclMetadata) 251 EmitDeclMetadata(); 252 253 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 254 EmitCoverageFile(); 255 256 if (DebugInfo) 257 DebugInfo->finalize(); 258 259 EmitVersionIdentMetadata(); 260 } 261 262 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 263 // Make sure that this type is translated. 264 Types.UpdateCompletedType(TD); 265 } 266 267 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 268 if (!TBAA) 269 return 0; 270 return TBAA->getTBAAInfo(QTy); 271 } 272 273 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 274 if (!TBAA) 275 return 0; 276 return TBAA->getTBAAInfoForVTablePtr(); 277 } 278 279 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 280 if (!TBAA) 281 return 0; 282 return TBAA->getTBAAStructInfo(QTy); 283 } 284 285 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) { 286 if (!TBAA) 287 return 0; 288 return TBAA->getTBAAStructTypeInfo(QTy); 289 } 290 291 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 292 llvm::MDNode *AccessN, 293 uint64_t O) { 294 if (!TBAA) 295 return 0; 296 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 297 } 298 299 /// Decorate the instruction with a TBAA tag. For both scalar TBAA 300 /// and struct-path aware TBAA, the tag has the same format: 301 /// base type, access type and offset. 302 /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 303 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 304 llvm::MDNode *TBAAInfo, 305 bool ConvertTypeToTag) { 306 if (ConvertTypeToTag && TBAA) 307 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 308 TBAA->getTBAAScalarTagInfo(TBAAInfo)); 309 else 310 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 311 } 312 313 void CodeGenModule::Error(SourceLocation loc, StringRef error) { 314 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error); 315 getDiags().Report(Context.getFullLoc(loc), diagID); 316 } 317 318 /// ErrorUnsupported - Print out an error that codegen doesn't support the 319 /// specified stmt yet. 320 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 321 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 322 "cannot compile this %0 yet"); 323 std::string Msg = Type; 324 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 325 << Msg << S->getSourceRange(); 326 } 327 328 /// ErrorUnsupported - Print out an error that codegen doesn't support the 329 /// specified decl yet. 330 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 331 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 332 "cannot compile this %0 yet"); 333 std::string Msg = Type; 334 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 335 } 336 337 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 338 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 339 } 340 341 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 342 const NamedDecl *D) const { 343 // Internal definitions always have default visibility. 344 if (GV->hasLocalLinkage()) { 345 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 346 return; 347 } 348 349 // Set visibility for definitions. 350 LinkageInfo LV = D->getLinkageAndVisibility(); 351 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 352 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 353 } 354 355 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 356 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 357 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 358 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 359 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 360 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 361 } 362 363 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 364 CodeGenOptions::TLSModel M) { 365 switch (M) { 366 case CodeGenOptions::GeneralDynamicTLSModel: 367 return llvm::GlobalVariable::GeneralDynamicTLSModel; 368 case CodeGenOptions::LocalDynamicTLSModel: 369 return llvm::GlobalVariable::LocalDynamicTLSModel; 370 case CodeGenOptions::InitialExecTLSModel: 371 return llvm::GlobalVariable::InitialExecTLSModel; 372 case CodeGenOptions::LocalExecTLSModel: 373 return llvm::GlobalVariable::LocalExecTLSModel; 374 } 375 llvm_unreachable("Invalid TLS model!"); 376 } 377 378 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV, 379 const VarDecl &D) const { 380 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 381 382 llvm::GlobalVariable::ThreadLocalMode TLM; 383 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 384 385 // Override the TLS model if it is explicitly specified. 386 if (D.hasAttr<TLSModelAttr>()) { 387 const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>(); 388 TLM = GetLLVMTLSModel(Attr->getModel()); 389 } 390 391 GV->setThreadLocalMode(TLM); 392 } 393 394 /// Set the symbol visibility of type information (vtable and RTTI) 395 /// associated with the given type. 396 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 397 const CXXRecordDecl *RD, 398 TypeVisibilityKind TVK) const { 399 setGlobalVisibility(GV, RD); 400 401 if (!CodeGenOpts.HiddenWeakVTables) 402 return; 403 404 // We never want to drop the visibility for RTTI names. 405 if (TVK == TVK_ForRTTIName) 406 return; 407 408 // We want to drop the visibility to hidden for weak type symbols. 409 // This isn't possible if there might be unresolved references 410 // elsewhere that rely on this symbol being visible. 411 412 // This should be kept roughly in sync with setThunkVisibility 413 // in CGVTables.cpp. 414 415 // Preconditions. 416 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage || 417 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 418 return; 419 420 // Don't override an explicit visibility attribute. 421 if (RD->getExplicitVisibility(NamedDecl::VisibilityForType)) 422 return; 423 424 switch (RD->getTemplateSpecializationKind()) { 425 // We have to disable the optimization if this is an EI definition 426 // because there might be EI declarations in other shared objects. 427 case TSK_ExplicitInstantiationDefinition: 428 case TSK_ExplicitInstantiationDeclaration: 429 return; 430 431 // Every use of a non-template class's type information has to emit it. 432 case TSK_Undeclared: 433 break; 434 435 // In theory, implicit instantiations can ignore the possibility of 436 // an explicit instantiation declaration because there necessarily 437 // must be an EI definition somewhere with default visibility. In 438 // practice, it's possible to have an explicit instantiation for 439 // an arbitrary template class, and linkers aren't necessarily able 440 // to deal with mixed-visibility symbols. 441 case TSK_ExplicitSpecialization: 442 case TSK_ImplicitInstantiation: 443 return; 444 } 445 446 // If there's a key function, there may be translation units 447 // that don't have the key function's definition. But ignore 448 // this if we're emitting RTTI under -fno-rtti. 449 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) { 450 // FIXME: what should we do if we "lose" the key function during 451 // the emission of the file? 452 if (Context.getCurrentKeyFunction(RD)) 453 return; 454 } 455 456 // Otherwise, drop the visibility to hidden. 457 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 458 GV->setUnnamedAddr(true); 459 } 460 461 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 462 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 463 464 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 465 if (!Str.empty()) 466 return Str; 467 468 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 469 IdentifierInfo *II = ND->getIdentifier(); 470 assert(II && "Attempt to mangle unnamed decl."); 471 472 Str = II->getName(); 473 return Str; 474 } 475 476 SmallString<256> Buffer; 477 llvm::raw_svector_ostream Out(Buffer); 478 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 479 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 480 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 481 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 482 else 483 getCXXABI().getMangleContext().mangleName(ND, Out); 484 485 // Allocate space for the mangled name. 486 Out.flush(); 487 size_t Length = Buffer.size(); 488 char *Name = MangledNamesAllocator.Allocate<char>(Length); 489 std::copy(Buffer.begin(), Buffer.end(), Name); 490 491 Str = StringRef(Name, Length); 492 493 return Str; 494 } 495 496 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 497 const BlockDecl *BD) { 498 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 499 const Decl *D = GD.getDecl(); 500 llvm::raw_svector_ostream Out(Buffer.getBuffer()); 501 if (D == 0) 502 MangleCtx.mangleGlobalBlock(BD, 503 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 504 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 505 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 506 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 507 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 508 else 509 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 510 } 511 512 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 513 return getModule().getNamedValue(Name); 514 } 515 516 /// AddGlobalCtor - Add a function to the list that will be called before 517 /// main() runs. 518 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 519 // FIXME: Type coercion of void()* types. 520 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 521 } 522 523 /// AddGlobalDtor - Add a function to the list that will be called 524 /// when the module is unloaded. 525 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 526 // FIXME: Type coercion of void()* types. 527 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 528 } 529 530 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 531 // Ctor function type is void()*. 532 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 533 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 534 535 // Get the type of a ctor entry, { i32, void ()* }. 536 llvm::StructType *CtorStructTy = 537 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL); 538 539 // Construct the constructor and destructor arrays. 540 SmallVector<llvm::Constant*, 8> Ctors; 541 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 542 llvm::Constant *S[] = { 543 llvm::ConstantInt::get(Int32Ty, I->second, false), 544 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy) 545 }; 546 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 547 } 548 549 if (!Ctors.empty()) { 550 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 551 new llvm::GlobalVariable(TheModule, AT, false, 552 llvm::GlobalValue::AppendingLinkage, 553 llvm::ConstantArray::get(AT, Ctors), 554 GlobalName); 555 } 556 } 557 558 llvm::GlobalValue::LinkageTypes 559 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 560 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 561 562 if (isa<CXXDestructorDecl>(D) && 563 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 564 GD.getDtorType())) 565 return llvm::Function::LinkOnceODRLinkage; 566 567 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 568 569 if (Linkage == GVA_Internal) 570 return llvm::Function::InternalLinkage; 571 572 if (D->hasAttr<DLLExportAttr>()) 573 return llvm::Function::DLLExportLinkage; 574 575 if (D->hasAttr<WeakAttr>()) 576 return llvm::Function::WeakAnyLinkage; 577 578 // In C99 mode, 'inline' functions are guaranteed to have a strong 579 // definition somewhere else, so we can use available_externally linkage. 580 if (Linkage == GVA_C99Inline) 581 return llvm::Function::AvailableExternallyLinkage; 582 583 // Note that Apple's kernel linker doesn't support symbol 584 // coalescing, so we need to avoid linkonce and weak linkages there. 585 // Normally, this means we just map to internal, but for explicit 586 // instantiations we'll map to external. 587 588 // In C++, the compiler has to emit a definition in every translation unit 589 // that references the function. We should use linkonce_odr because 590 // a) if all references in this translation unit are optimized away, we 591 // don't need to codegen it. b) if the function persists, it needs to be 592 // merged with other definitions. c) C++ has the ODR, so we know the 593 // definition is dependable. 594 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 595 return !Context.getLangOpts().AppleKext 596 ? llvm::Function::LinkOnceODRLinkage 597 : llvm::Function::InternalLinkage; 598 599 // An explicit instantiation of a template has weak linkage, since 600 // explicit instantiations can occur in multiple translation units 601 // and must all be equivalent. However, we are not allowed to 602 // throw away these explicit instantiations. 603 if (Linkage == GVA_ExplicitTemplateInstantiation) 604 return !Context.getLangOpts().AppleKext 605 ? llvm::Function::WeakODRLinkage 606 : llvm::Function::ExternalLinkage; 607 608 // Otherwise, we have strong external linkage. 609 assert(Linkage == GVA_StrongExternal); 610 return llvm::Function::ExternalLinkage; 611 } 612 613 614 /// SetFunctionDefinitionAttributes - Set attributes for a global. 615 /// 616 /// FIXME: This is currently only done for aliases and functions, but not for 617 /// variables (these details are set in EmitGlobalVarDefinition for variables). 618 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 619 llvm::GlobalValue *GV) { 620 SetCommonAttributes(D, GV); 621 } 622 623 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 624 const CGFunctionInfo &Info, 625 llvm::Function *F) { 626 unsigned CallingConv; 627 AttributeListType AttributeList; 628 ConstructAttributeList(Info, D, AttributeList, CallingConv, false); 629 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 630 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 631 } 632 633 /// Determines whether the language options require us to model 634 /// unwind exceptions. We treat -fexceptions as mandating this 635 /// except under the fragile ObjC ABI with only ObjC exceptions 636 /// enabled. This means, for example, that C with -fexceptions 637 /// enables this. 638 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 639 // If exceptions are completely disabled, obviously this is false. 640 if (!LangOpts.Exceptions) return false; 641 642 // If C++ exceptions are enabled, this is true. 643 if (LangOpts.CXXExceptions) return true; 644 645 // If ObjC exceptions are enabled, this depends on the ABI. 646 if (LangOpts.ObjCExceptions) { 647 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 648 } 649 650 return true; 651 } 652 653 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 654 llvm::Function *F) { 655 llvm::AttrBuilder B; 656 657 if (CodeGenOpts.UnwindTables) 658 B.addAttribute(llvm::Attribute::UWTable); 659 660 if (!hasUnwindExceptions(LangOpts)) 661 B.addAttribute(llvm::Attribute::NoUnwind); 662 663 if (D->hasAttr<NakedAttr>()) { 664 // Naked implies noinline: we should not be inlining such functions. 665 B.addAttribute(llvm::Attribute::Naked); 666 B.addAttribute(llvm::Attribute::NoInline); 667 } else if (D->hasAttr<NoInlineAttr>()) { 668 B.addAttribute(llvm::Attribute::NoInline); 669 } else if ((D->hasAttr<AlwaysInlineAttr>() || 670 D->hasAttr<ForceInlineAttr>()) && 671 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 672 llvm::Attribute::NoInline)) { 673 // (noinline wins over always_inline, and we can't specify both in IR) 674 B.addAttribute(llvm::Attribute::AlwaysInline); 675 } 676 677 if (D->hasAttr<ColdAttr>()) { 678 B.addAttribute(llvm::Attribute::OptimizeForSize); 679 B.addAttribute(llvm::Attribute::Cold); 680 } 681 682 if (D->hasAttr<MinSizeAttr>()) 683 B.addAttribute(llvm::Attribute::MinSize); 684 685 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 686 B.addAttribute(llvm::Attribute::StackProtect); 687 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 688 B.addAttribute(llvm::Attribute::StackProtectReq); 689 690 // Add sanitizer attributes if function is not blacklisted. 691 if (!SanitizerBlacklist->isIn(*F)) { 692 // When AddressSanitizer is enabled, set SanitizeAddress attribute 693 // unless __attribute__((no_sanitize_address)) is used. 694 if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>()) 695 B.addAttribute(llvm::Attribute::SanitizeAddress); 696 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread)) 697 if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) { 698 B.addAttribute(llvm::Attribute::SanitizeThread); 699 } 700 // Same for MemorySanitizer and __attribute__((no_sanitize_memory)) 701 if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>()) 702 B.addAttribute(llvm::Attribute::SanitizeMemory); 703 } 704 705 F->addAttributes(llvm::AttributeSet::FunctionIndex, 706 llvm::AttributeSet::get( 707 F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 708 709 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 710 F->setUnnamedAddr(true); 711 else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 712 if (MD->isVirtual()) 713 F->setUnnamedAddr(true); 714 715 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 716 if (alignment) 717 F->setAlignment(alignment); 718 719 // C++ ABI requires 2-byte alignment for member functions. 720 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 721 F->setAlignment(2); 722 } 723 724 void CodeGenModule::SetCommonAttributes(const Decl *D, 725 llvm::GlobalValue *GV) { 726 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 727 setGlobalVisibility(GV, ND); 728 else 729 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 730 731 if (D->hasAttr<UsedAttr>()) 732 AddUsedGlobal(GV); 733 734 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 735 GV->setSection(SA->getName()); 736 737 // Alias cannot have attributes. Filter them here. 738 if (!isa<llvm::GlobalAlias>(GV)) 739 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 740 } 741 742 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 743 llvm::Function *F, 744 const CGFunctionInfo &FI) { 745 SetLLVMFunctionAttributes(D, FI, F); 746 SetLLVMFunctionAttributesForDefinition(D, F); 747 748 F->setLinkage(llvm::Function::InternalLinkage); 749 750 SetCommonAttributes(D, F); 751 } 752 753 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 754 llvm::Function *F, 755 bool IsIncompleteFunction) { 756 if (unsigned IID = F->getIntrinsicID()) { 757 // If this is an intrinsic function, set the function's attributes 758 // to the intrinsic's attributes. 759 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), 760 (llvm::Intrinsic::ID)IID)); 761 return; 762 } 763 764 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 765 766 if (!IsIncompleteFunction) 767 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 768 769 if (getCXXABI().HasThisReturn(GD)) { 770 assert(!F->arg_empty() && 771 F->arg_begin()->getType() 772 ->canLosslesslyBitCastTo(F->getReturnType()) && 773 "unexpected this return"); 774 F->addAttribute(1, llvm::Attribute::Returned); 775 } 776 777 // Only a few attributes are set on declarations; these may later be 778 // overridden by a definition. 779 780 if (FD->hasAttr<DLLImportAttr>()) { 781 F->setLinkage(llvm::Function::DLLImportLinkage); 782 } else if (FD->hasAttr<WeakAttr>() || 783 FD->isWeakImported()) { 784 // "extern_weak" is overloaded in LLVM; we probably should have 785 // separate linkage types for this. 786 F->setLinkage(llvm::Function::ExternalWeakLinkage); 787 } else { 788 F->setLinkage(llvm::Function::ExternalLinkage); 789 790 LinkageInfo LV = FD->getLinkageAndVisibility(); 791 if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) { 792 F->setVisibility(GetLLVMVisibility(LV.getVisibility())); 793 } 794 } 795 796 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 797 F->setSection(SA->getName()); 798 799 // A replaceable global allocation function does not act like a builtin by 800 // default, only if it is invoked by a new-expression or delete-expression. 801 if (FD->isReplaceableGlobalAllocationFunction()) 802 F->addAttribute(llvm::AttributeSet::FunctionIndex, 803 llvm::Attribute::NoBuiltin); 804 } 805 806 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 807 assert(!GV->isDeclaration() && 808 "Only globals with definition can force usage."); 809 LLVMUsed.push_back(GV); 810 } 811 812 void CodeGenModule::EmitLLVMUsed() { 813 // Don't create llvm.used if there is no need. 814 if (LLVMUsed.empty()) 815 return; 816 817 // Convert LLVMUsed to what ConstantArray needs. 818 SmallVector<llvm::Constant*, 8> UsedArray; 819 UsedArray.resize(LLVMUsed.size()); 820 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 821 UsedArray[i] = 822 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 823 Int8PtrTy); 824 } 825 826 if (UsedArray.empty()) 827 return; 828 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size()); 829 830 llvm::GlobalVariable *GV = 831 new llvm::GlobalVariable(getModule(), ATy, false, 832 llvm::GlobalValue::AppendingLinkage, 833 llvm::ConstantArray::get(ATy, UsedArray), 834 "llvm.used"); 835 836 GV->setSection("llvm.metadata"); 837 } 838 839 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 840 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 841 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 842 } 843 844 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 845 llvm::SmallString<32> Opt; 846 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 847 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 848 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 849 } 850 851 void CodeGenModule::AddDependentLib(StringRef Lib) { 852 llvm::SmallString<24> Opt; 853 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 854 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 855 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 856 } 857 858 /// \brief Add link options implied by the given module, including modules 859 /// it depends on, using a postorder walk. 860 static void addLinkOptionsPostorder(CodeGenModule &CGM, 861 Module *Mod, 862 SmallVectorImpl<llvm::Value *> &Metadata, 863 llvm::SmallPtrSet<Module *, 16> &Visited) { 864 // Import this module's parent. 865 if (Mod->Parent && Visited.insert(Mod->Parent)) { 866 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 867 } 868 869 // Import this module's dependencies. 870 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 871 if (Visited.insert(Mod->Imports[I-1])) 872 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 873 } 874 875 // Add linker options to link against the libraries/frameworks 876 // described by this module. 877 llvm::LLVMContext &Context = CGM.getLLVMContext(); 878 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 879 // Link against a framework. Frameworks are currently Darwin only, so we 880 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 881 if (Mod->LinkLibraries[I-1].IsFramework) { 882 llvm::Value *Args[2] = { 883 llvm::MDString::get(Context, "-framework"), 884 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library) 885 }; 886 887 Metadata.push_back(llvm::MDNode::get(Context, Args)); 888 continue; 889 } 890 891 // Link against a library. 892 llvm::SmallString<24> Opt; 893 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 894 Mod->LinkLibraries[I-1].Library, Opt); 895 llvm::Value *OptString = llvm::MDString::get(Context, Opt); 896 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 897 } 898 } 899 900 void CodeGenModule::EmitModuleLinkOptions() { 901 // Collect the set of all of the modules we want to visit to emit link 902 // options, which is essentially the imported modules and all of their 903 // non-explicit child modules. 904 llvm::SetVector<clang::Module *> LinkModules; 905 llvm::SmallPtrSet<clang::Module *, 16> Visited; 906 SmallVector<clang::Module *, 16> Stack; 907 908 // Seed the stack with imported modules. 909 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(), 910 MEnd = ImportedModules.end(); 911 M != MEnd; ++M) { 912 if (Visited.insert(*M)) 913 Stack.push_back(*M); 914 } 915 916 // Find all of the modules to import, making a little effort to prune 917 // non-leaf modules. 918 while (!Stack.empty()) { 919 clang::Module *Mod = Stack.pop_back_val(); 920 921 bool AnyChildren = false; 922 923 // Visit the submodules of this module. 924 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 925 SubEnd = Mod->submodule_end(); 926 Sub != SubEnd; ++Sub) { 927 // Skip explicit children; they need to be explicitly imported to be 928 // linked against. 929 if ((*Sub)->IsExplicit) 930 continue; 931 932 if (Visited.insert(*Sub)) { 933 Stack.push_back(*Sub); 934 AnyChildren = true; 935 } 936 } 937 938 // We didn't find any children, so add this module to the list of 939 // modules to link against. 940 if (!AnyChildren) { 941 LinkModules.insert(Mod); 942 } 943 } 944 945 // Add link options for all of the imported modules in reverse topological 946 // order. We don't do anything to try to order import link flags with respect 947 // to linker options inserted by things like #pragma comment(). 948 SmallVector<llvm::Value *, 16> MetadataArgs; 949 Visited.clear(); 950 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(), 951 MEnd = LinkModules.end(); 952 M != MEnd; ++M) { 953 if (Visited.insert(*M)) 954 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited); 955 } 956 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 957 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 958 959 // Add the linker options metadata flag. 960 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 961 llvm::MDNode::get(getLLVMContext(), 962 LinkerOptionsMetadata)); 963 } 964 965 void CodeGenModule::EmitDeferred() { 966 // Emit code for any potentially referenced deferred decls. Since a 967 // previously unused static decl may become used during the generation of code 968 // for a static function, iterate until no changes are made. 969 970 while (true) { 971 if (!DeferredVTables.empty()) { 972 EmitDeferredVTables(); 973 974 // Emitting a v-table doesn't directly cause more v-tables to 975 // become deferred, although it can cause functions to be 976 // emitted that then need those v-tables. 977 assert(DeferredVTables.empty()); 978 } 979 980 // Stop if we're out of both deferred v-tables and deferred declarations. 981 if (DeferredDeclsToEmit.empty()) break; 982 983 GlobalDecl D = DeferredDeclsToEmit.back(); 984 DeferredDeclsToEmit.pop_back(); 985 986 // Check to see if we've already emitted this. This is necessary 987 // for a couple of reasons: first, decls can end up in the 988 // deferred-decls queue multiple times, and second, decls can end 989 // up with definitions in unusual ways (e.g. by an extern inline 990 // function acquiring a strong function redefinition). Just 991 // ignore these cases. 992 // 993 // TODO: That said, looking this up multiple times is very wasteful. 994 StringRef Name = getMangledName(D); 995 llvm::GlobalValue *CGRef = GetGlobalValue(Name); 996 assert(CGRef && "Deferred decl wasn't referenced?"); 997 998 if (!CGRef->isDeclaration()) 999 continue; 1000 1001 // GlobalAlias::isDeclaration() defers to the aliasee, but for our 1002 // purposes an alias counts as a definition. 1003 if (isa<llvm::GlobalAlias>(CGRef)) 1004 continue; 1005 1006 // Otherwise, emit the definition and move on to the next one. 1007 EmitGlobalDefinition(D); 1008 } 1009 } 1010 1011 void CodeGenModule::EmitGlobalAnnotations() { 1012 if (Annotations.empty()) 1013 return; 1014 1015 // Create a new global variable for the ConstantStruct in the Module. 1016 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1017 Annotations[0]->getType(), Annotations.size()), Annotations); 1018 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), 1019 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array, 1020 "llvm.global.annotations"); 1021 gv->setSection(AnnotationSection); 1022 } 1023 1024 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1025 llvm::Constant *&AStr = AnnotationStrings[Str]; 1026 if (AStr) 1027 return AStr; 1028 1029 // Not found yet, create a new global. 1030 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1031 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(), 1032 true, llvm::GlobalValue::PrivateLinkage, s, ".str"); 1033 gv->setSection(AnnotationSection); 1034 gv->setUnnamedAddr(true); 1035 AStr = gv; 1036 return gv; 1037 } 1038 1039 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1040 SourceManager &SM = getContext().getSourceManager(); 1041 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1042 if (PLoc.isValid()) 1043 return EmitAnnotationString(PLoc.getFilename()); 1044 return EmitAnnotationString(SM.getBufferName(Loc)); 1045 } 1046 1047 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1048 SourceManager &SM = getContext().getSourceManager(); 1049 PresumedLoc PLoc = SM.getPresumedLoc(L); 1050 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1051 SM.getExpansionLineNumber(L); 1052 return llvm::ConstantInt::get(Int32Ty, LineNo); 1053 } 1054 1055 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1056 const AnnotateAttr *AA, 1057 SourceLocation L) { 1058 // Get the globals for file name, annotation, and the line number. 1059 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1060 *UnitGV = EmitAnnotationUnit(L), 1061 *LineNoCst = EmitAnnotationLineNo(L); 1062 1063 // Create the ConstantStruct for the global annotation. 1064 llvm::Constant *Fields[4] = { 1065 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1066 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1067 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1068 LineNoCst 1069 }; 1070 return llvm::ConstantStruct::getAnon(Fields); 1071 } 1072 1073 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1074 llvm::GlobalValue *GV) { 1075 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1076 // Get the struct elements for these annotations. 1077 for (specific_attr_iterator<AnnotateAttr> 1078 ai = D->specific_attr_begin<AnnotateAttr>(), 1079 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) 1080 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation())); 1081 } 1082 1083 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 1084 // Never defer when EmitAllDecls is specified. 1085 if (LangOpts.EmitAllDecls) 1086 return false; 1087 1088 return !getContext().DeclMustBeEmitted(Global); 1089 } 1090 1091 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor( 1092 const CXXUuidofExpr* E) { 1093 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1094 // well-formed. 1095 StringRef Uuid = E->getUuidAsStringRef(Context); 1096 std::string Name = "_GUID_" + Uuid.lower(); 1097 std::replace(Name.begin(), Name.end(), '-', '_'); 1098 1099 // Look for an existing global. 1100 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1101 return GV; 1102 1103 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType()); 1104 assert(Init && "failed to initialize as constant"); 1105 1106 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 1107 getModule(), Init->getType(), 1108 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 1109 return GV; 1110 } 1111 1112 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1113 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1114 assert(AA && "No alias?"); 1115 1116 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1117 1118 // See if there is already something with the target's name in the module. 1119 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1120 if (Entry) { 1121 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1122 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1123 } 1124 1125 llvm::Constant *Aliasee; 1126 if (isa<llvm::FunctionType>(DeclTy)) 1127 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1128 GlobalDecl(cast<FunctionDecl>(VD)), 1129 /*ForVTable=*/false); 1130 else 1131 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1132 llvm::PointerType::getUnqual(DeclTy), 0); 1133 1134 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 1135 F->setLinkage(llvm::Function::ExternalWeakLinkage); 1136 WeakRefReferences.insert(F); 1137 1138 return Aliasee; 1139 } 1140 1141 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 1142 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 1143 1144 // Weak references don't produce any output by themselves. 1145 if (Global->hasAttr<WeakRefAttr>()) 1146 return; 1147 1148 // If this is an alias definition (which otherwise looks like a declaration) 1149 // emit it now. 1150 if (Global->hasAttr<AliasAttr>()) 1151 return EmitAliasDefinition(GD); 1152 1153 // If this is CUDA, be selective about which declarations we emit. 1154 if (LangOpts.CUDA) { 1155 if (CodeGenOpts.CUDAIsDevice) { 1156 if (!Global->hasAttr<CUDADeviceAttr>() && 1157 !Global->hasAttr<CUDAGlobalAttr>() && 1158 !Global->hasAttr<CUDAConstantAttr>() && 1159 !Global->hasAttr<CUDASharedAttr>()) 1160 return; 1161 } else { 1162 if (!Global->hasAttr<CUDAHostAttr>() && ( 1163 Global->hasAttr<CUDADeviceAttr>() || 1164 Global->hasAttr<CUDAConstantAttr>() || 1165 Global->hasAttr<CUDASharedAttr>())) 1166 return; 1167 } 1168 } 1169 1170 // Ignore declarations, they will be emitted on their first use. 1171 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 1172 // Forward declarations are emitted lazily on first use. 1173 if (!FD->doesThisDeclarationHaveABody()) { 1174 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1175 return; 1176 1177 const FunctionDecl *InlineDefinition = 0; 1178 FD->getBody(InlineDefinition); 1179 1180 StringRef MangledName = getMangledName(GD); 1181 DeferredDecls.erase(MangledName); 1182 EmitGlobalDefinition(InlineDefinition); 1183 return; 1184 } 1185 } else { 1186 const VarDecl *VD = cast<VarDecl>(Global); 1187 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1188 1189 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 1190 return; 1191 } 1192 1193 // Defer code generation when possible if this is a static definition, inline 1194 // function etc. These we only want to emit if they are used. 1195 if (!MayDeferGeneration(Global)) { 1196 // Emit the definition if it can't be deferred. 1197 EmitGlobalDefinition(GD); 1198 return; 1199 } 1200 1201 // If we're deferring emission of a C++ variable with an 1202 // initializer, remember the order in which it appeared in the file. 1203 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1204 cast<VarDecl>(Global)->hasInit()) { 1205 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 1206 CXXGlobalInits.push_back(0); 1207 } 1208 1209 // If the value has already been used, add it directly to the 1210 // DeferredDeclsToEmit list. 1211 StringRef MangledName = getMangledName(GD); 1212 if (GetGlobalValue(MangledName)) 1213 DeferredDeclsToEmit.push_back(GD); 1214 else { 1215 // Otherwise, remember that we saw a deferred decl with this name. The 1216 // first use of the mangled name will cause it to move into 1217 // DeferredDeclsToEmit. 1218 DeferredDecls[MangledName] = GD; 1219 } 1220 } 1221 1222 namespace { 1223 struct FunctionIsDirectlyRecursive : 1224 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1225 const StringRef Name; 1226 const Builtin::Context &BI; 1227 bool Result; 1228 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1229 Name(N), BI(C), Result(false) { 1230 } 1231 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1232 1233 bool TraverseCallExpr(CallExpr *E) { 1234 const FunctionDecl *FD = E->getDirectCallee(); 1235 if (!FD) 1236 return true; 1237 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1238 if (Attr && Name == Attr->getLabel()) { 1239 Result = true; 1240 return false; 1241 } 1242 unsigned BuiltinID = FD->getBuiltinID(); 1243 if (!BuiltinID) 1244 return true; 1245 StringRef BuiltinName = BI.GetName(BuiltinID); 1246 if (BuiltinName.startswith("__builtin_") && 1247 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1248 Result = true; 1249 return false; 1250 } 1251 return true; 1252 } 1253 }; 1254 } 1255 1256 // isTriviallyRecursive - Check if this function calls another 1257 // decl that, because of the asm attribute or the other decl being a builtin, 1258 // ends up pointing to itself. 1259 bool 1260 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1261 StringRef Name; 1262 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1263 // asm labels are a special kind of mangling we have to support. 1264 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1265 if (!Attr) 1266 return false; 1267 Name = Attr->getLabel(); 1268 } else { 1269 Name = FD->getName(); 1270 } 1271 1272 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1273 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1274 return Walker.Result; 1275 } 1276 1277 bool 1278 CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1279 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1280 return true; 1281 const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl()); 1282 if (CodeGenOpts.OptimizationLevel == 0 && 1283 !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>()) 1284 return false; 1285 // PR9614. Avoid cases where the source code is lying to us. An available 1286 // externally function should have an equivalent function somewhere else, 1287 // but a function that calls itself is clearly not equivalent to the real 1288 // implementation. 1289 // This happens in glibc's btowc and in some configure checks. 1290 return !isTriviallyRecursive(F); 1291 } 1292 1293 /// If the type for the method's class was generated by 1294 /// CGDebugInfo::createContextChain(), the cache contains only a 1295 /// limited DIType without any declarations. Since EmitFunctionStart() 1296 /// needs to find the canonical declaration for each method, we need 1297 /// to construct the complete type prior to emitting the method. 1298 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1299 if (!D->isInstance()) 1300 return; 1301 1302 if (CGDebugInfo *DI = getModuleDebugInfo()) 1303 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 1304 const PointerType *ThisPtr = 1305 cast<PointerType>(D->getThisType(getContext())); 1306 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1307 } 1308 } 1309 1310 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 1311 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1312 1313 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1314 Context.getSourceManager(), 1315 "Generating code for declaration"); 1316 1317 if (isa<FunctionDecl>(D)) { 1318 // At -O0, don't generate IR for functions with available_externally 1319 // linkage. 1320 if (!shouldEmitFunction(GD)) 1321 return; 1322 1323 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 1324 CompleteDIClassType(Method); 1325 // Make sure to emit the definition(s) before we emit the thunks. 1326 // This is necessary for the generation of certain thunks. 1327 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 1328 EmitCXXConstructor(CD, GD.getCtorType()); 1329 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method)) 1330 EmitCXXDestructor(DD, GD.getDtorType()); 1331 else 1332 EmitGlobalFunctionDefinition(GD); 1333 1334 if (Method->isVirtual()) 1335 getVTables().EmitThunks(GD); 1336 1337 return; 1338 } 1339 1340 return EmitGlobalFunctionDefinition(GD); 1341 } 1342 1343 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1344 return EmitGlobalVarDefinition(VD); 1345 1346 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1347 } 1348 1349 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1350 /// module, create and return an llvm Function with the specified type. If there 1351 /// is something in the module with the specified name, return it potentially 1352 /// bitcasted to the right type. 1353 /// 1354 /// If D is non-null, it specifies a decl that correspond to this. This is used 1355 /// to set the attributes on the function when it is first created. 1356 llvm::Constant * 1357 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 1358 llvm::Type *Ty, 1359 GlobalDecl GD, bool ForVTable, 1360 llvm::AttributeSet ExtraAttrs) { 1361 const Decl *D = GD.getDecl(); 1362 1363 // Lookup the entry, lazily creating it if necessary. 1364 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1365 if (Entry) { 1366 if (WeakRefReferences.erase(Entry)) { 1367 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1368 if (FD && !FD->hasAttr<WeakAttr>()) 1369 Entry->setLinkage(llvm::Function::ExternalLinkage); 1370 } 1371 1372 if (Entry->getType()->getElementType() == Ty) 1373 return Entry; 1374 1375 // Make sure the result is of the correct type. 1376 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1377 } 1378 1379 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 1380 // each other bottoming out with the base dtor. Therefore we emit non-base 1381 // dtors on usage, even if there is no dtor definition in the TU. 1382 if (D && isa<CXXDestructorDecl>(D) && 1383 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 1384 GD.getDtorType())) 1385 DeferredDeclsToEmit.push_back(GD); 1386 1387 // This function doesn't have a complete type (for example, the return 1388 // type is an incomplete struct). Use a fake type instead, and make 1389 // sure not to try to set attributes. 1390 bool IsIncompleteFunction = false; 1391 1392 llvm::FunctionType *FTy; 1393 if (isa<llvm::FunctionType>(Ty)) { 1394 FTy = cast<llvm::FunctionType>(Ty); 1395 } else { 1396 FTy = llvm::FunctionType::get(VoidTy, false); 1397 IsIncompleteFunction = true; 1398 } 1399 1400 llvm::Function *F = llvm::Function::Create(FTy, 1401 llvm::Function::ExternalLinkage, 1402 MangledName, &getModule()); 1403 assert(F->getName() == MangledName && "name was uniqued!"); 1404 if (D) 1405 SetFunctionAttributes(GD, F, IsIncompleteFunction); 1406 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1407 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1408 F->addAttributes(llvm::AttributeSet::FunctionIndex, 1409 llvm::AttributeSet::get(VMContext, 1410 llvm::AttributeSet::FunctionIndex, 1411 B)); 1412 } 1413 1414 // This is the first use or definition of a mangled name. If there is a 1415 // deferred decl with this name, remember that we need to emit it at the end 1416 // of the file. 1417 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1418 if (DDI != DeferredDecls.end()) { 1419 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1420 // list, and remove it from DeferredDecls (since we don't need it anymore). 1421 DeferredDeclsToEmit.push_back(DDI->second); 1422 DeferredDecls.erase(DDI); 1423 1424 // Otherwise, if this is a sized deallocation function, emit a weak definition 1425 // for it at the end of the translation unit. 1426 } else if (D && cast<FunctionDecl>(D) 1427 ->getCorrespondingUnsizedGlobalDeallocationFunction()) { 1428 DeferredDeclsToEmit.push_back(GD); 1429 1430 // Otherwise, there are cases we have to worry about where we're 1431 // using a declaration for which we must emit a definition but where 1432 // we might not find a top-level definition: 1433 // - member functions defined inline in their classes 1434 // - friend functions defined inline in some class 1435 // - special member functions with implicit definitions 1436 // If we ever change our AST traversal to walk into class methods, 1437 // this will be unnecessary. 1438 // 1439 // We also don't emit a definition for a function if it's going to be an entry 1440 // in a vtable, unless it's already marked as used. 1441 } else if (getLangOpts().CPlusPlus && D) { 1442 // Look for a declaration that's lexically in a record. 1443 const FunctionDecl *FD = cast<FunctionDecl>(D); 1444 FD = FD->getMostRecentDecl(); 1445 do { 1446 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1447 if (FD->isImplicit() && !ForVTable) { 1448 assert(FD->isUsed() && "Sema didn't mark implicit function as used!"); 1449 DeferredDeclsToEmit.push_back(GD.getWithDecl(FD)); 1450 break; 1451 } else if (FD->doesThisDeclarationHaveABody()) { 1452 DeferredDeclsToEmit.push_back(GD.getWithDecl(FD)); 1453 break; 1454 } 1455 } 1456 FD = FD->getPreviousDecl(); 1457 } while (FD); 1458 } 1459 1460 // Make sure the result is of the requested type. 1461 if (!IsIncompleteFunction) { 1462 assert(F->getType()->getElementType() == Ty); 1463 return F; 1464 } 1465 1466 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1467 return llvm::ConstantExpr::getBitCast(F, PTy); 1468 } 1469 1470 /// GetAddrOfFunction - Return the address of the given function. If Ty is 1471 /// non-null, then this function will use the specified type if it has to 1472 /// create it (this occurs when we see a definition of the function). 1473 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1474 llvm::Type *Ty, 1475 bool ForVTable) { 1476 // If there was no specific requested type, just convert it now. 1477 if (!Ty) 1478 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1479 1480 StringRef MangledName = getMangledName(GD); 1481 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable); 1482 } 1483 1484 /// CreateRuntimeFunction - Create a new runtime function with the specified 1485 /// type and name. 1486 llvm::Constant * 1487 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1488 StringRef Name, 1489 llvm::AttributeSet ExtraAttrs) { 1490 llvm::Constant *C 1491 = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1492 ExtraAttrs); 1493 if (llvm::Function *F = dyn_cast<llvm::Function>(C)) 1494 if (F->empty()) 1495 F->setCallingConv(getRuntimeCC()); 1496 return C; 1497 } 1498 1499 /// isTypeConstant - Determine whether an object of this type can be emitted 1500 /// as a constant. 1501 /// 1502 /// If ExcludeCtor is true, the duration when the object's constructor runs 1503 /// will not be considered. The caller will need to verify that the object is 1504 /// not written to during its construction. 1505 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1506 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1507 return false; 1508 1509 if (Context.getLangOpts().CPlusPlus) { 1510 if (const CXXRecordDecl *Record 1511 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1512 return ExcludeCtor && !Record->hasMutableFields() && 1513 Record->hasTrivialDestructor(); 1514 } 1515 1516 return true; 1517 } 1518 1519 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1520 /// create and return an llvm GlobalVariable with the specified type. If there 1521 /// is something in the module with the specified name, return it potentially 1522 /// bitcasted to the right type. 1523 /// 1524 /// If D is non-null, it specifies a decl that correspond to this. This is used 1525 /// to set the attributes on the global when it is first created. 1526 llvm::Constant * 1527 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1528 llvm::PointerType *Ty, 1529 const VarDecl *D, 1530 bool UnnamedAddr) { 1531 // Lookup the entry, lazily creating it if necessary. 1532 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1533 if (Entry) { 1534 if (WeakRefReferences.erase(Entry)) { 1535 if (D && !D->hasAttr<WeakAttr>()) 1536 Entry->setLinkage(llvm::Function::ExternalLinkage); 1537 } 1538 1539 if (UnnamedAddr) 1540 Entry->setUnnamedAddr(true); 1541 1542 if (Entry->getType() == Ty) 1543 return Entry; 1544 1545 // Make sure the result is of the correct type. 1546 return llvm::ConstantExpr::getBitCast(Entry, Ty); 1547 } 1548 1549 // This is the first use or definition of a mangled name. If there is a 1550 // deferred decl with this name, remember that we need to emit it at the end 1551 // of the file. 1552 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1553 if (DDI != DeferredDecls.end()) { 1554 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1555 // list, and remove it from DeferredDecls (since we don't need it anymore). 1556 DeferredDeclsToEmit.push_back(DDI->second); 1557 DeferredDecls.erase(DDI); 1558 } 1559 1560 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 1561 llvm::GlobalVariable *GV = 1562 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 1563 llvm::GlobalValue::ExternalLinkage, 1564 0, MangledName, 0, 1565 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 1566 1567 // Handle things which are present even on external declarations. 1568 if (D) { 1569 // FIXME: This code is overly simple and should be merged with other global 1570 // handling. 1571 GV->setConstant(isTypeConstant(D->getType(), false)); 1572 1573 // Set linkage and visibility in case we never see a definition. 1574 LinkageInfo LV = D->getLinkageAndVisibility(); 1575 if (LV.getLinkage() != ExternalLinkage) { 1576 // Don't set internal linkage on declarations. 1577 } else { 1578 if (D->hasAttr<DLLImportAttr>()) 1579 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage); 1580 else if (D->hasAttr<WeakAttr>() || D->isWeakImported()) 1581 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1582 1583 // Set visibility on a declaration only if it's explicit. 1584 if (LV.isVisibilityExplicit()) 1585 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 1586 } 1587 1588 if (D->getTLSKind()) { 1589 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 1590 CXXThreadLocals.push_back(std::make_pair(D, GV)); 1591 setTLSMode(GV, *D); 1592 } 1593 } 1594 1595 if (AddrSpace != Ty->getAddressSpace()) 1596 return llvm::ConstantExpr::getBitCast(GV, Ty); 1597 else 1598 return GV; 1599 } 1600 1601 1602 llvm::GlobalVariable * 1603 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 1604 llvm::Type *Ty, 1605 llvm::GlobalValue::LinkageTypes Linkage) { 1606 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1607 llvm::GlobalVariable *OldGV = 0; 1608 1609 1610 if (GV) { 1611 // Check if the variable has the right type. 1612 if (GV->getType()->getElementType() == Ty) 1613 return GV; 1614 1615 // Because C++ name mangling, the only way we can end up with an already 1616 // existing global with the same name is if it has been declared extern "C". 1617 assert(GV->isDeclaration() && "Declaration has wrong type!"); 1618 OldGV = GV; 1619 } 1620 1621 // Create a new variable. 1622 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1623 Linkage, 0, Name); 1624 1625 if (OldGV) { 1626 // Replace occurrences of the old variable if needed. 1627 GV->takeName(OldGV); 1628 1629 if (!OldGV->use_empty()) { 1630 llvm::Constant *NewPtrForOldDecl = 1631 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1632 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1633 } 1634 1635 OldGV->eraseFromParent(); 1636 } 1637 1638 return GV; 1639 } 1640 1641 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1642 /// given global variable. If Ty is non-null and if the global doesn't exist, 1643 /// then it will be created with the specified type instead of whatever the 1644 /// normal requested type would be. 1645 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1646 llvm::Type *Ty) { 1647 assert(D->hasGlobalStorage() && "Not a global variable"); 1648 QualType ASTTy = D->getType(); 1649 if (Ty == 0) 1650 Ty = getTypes().ConvertTypeForMem(ASTTy); 1651 1652 llvm::PointerType *PTy = 1653 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1654 1655 StringRef MangledName = getMangledName(D); 1656 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1657 } 1658 1659 /// CreateRuntimeVariable - Create a new runtime global variable with the 1660 /// specified type and name. 1661 llvm::Constant * 1662 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 1663 StringRef Name) { 1664 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 1665 true); 1666 } 1667 1668 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1669 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1670 1671 if (MayDeferGeneration(D)) { 1672 // If we have not seen a reference to this variable yet, place it 1673 // into the deferred declarations table to be emitted if needed 1674 // later. 1675 StringRef MangledName = getMangledName(D); 1676 if (!GetGlobalValue(MangledName)) { 1677 DeferredDecls[MangledName] = D; 1678 return; 1679 } 1680 } 1681 1682 // The tentative definition is the only definition. 1683 EmitGlobalVarDefinition(D); 1684 } 1685 1686 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 1687 return Context.toCharUnitsFromBits( 1688 TheDataLayout.getTypeStoreSizeInBits(Ty)); 1689 } 1690 1691 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 1692 unsigned AddrSpace) { 1693 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) { 1694 if (D->hasAttr<CUDAConstantAttr>()) 1695 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 1696 else if (D->hasAttr<CUDASharedAttr>()) 1697 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 1698 else 1699 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 1700 } 1701 1702 return AddrSpace; 1703 } 1704 1705 template<typename SomeDecl> 1706 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 1707 llvm::GlobalValue *GV) { 1708 if (!getLangOpts().CPlusPlus) 1709 return; 1710 1711 // Must have 'used' attribute, or else inline assembly can't rely on 1712 // the name existing. 1713 if (!D->template hasAttr<UsedAttr>()) 1714 return; 1715 1716 // Must have internal linkage and an ordinary name. 1717 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 1718 return; 1719 1720 // Must be in an extern "C" context. Entities declared directly within 1721 // a record are not extern "C" even if the record is in such a context. 1722 const SomeDecl *First = D->getFirstDecl(); 1723 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 1724 return; 1725 1726 // OK, this is an internal linkage entity inside an extern "C" linkage 1727 // specification. Make a note of that so we can give it the "expected" 1728 // mangled name if nothing else is using that name. 1729 std::pair<StaticExternCMap::iterator, bool> R = 1730 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 1731 1732 // If we have multiple internal linkage entities with the same name 1733 // in extern "C" regions, none of them gets that name. 1734 if (!R.second) 1735 R.first->second = 0; 1736 } 1737 1738 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1739 llvm::Constant *Init = 0; 1740 QualType ASTTy = D->getType(); 1741 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1742 bool NeedsGlobalCtor = false; 1743 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 1744 1745 const VarDecl *InitDecl; 1746 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 1747 1748 if (!InitExpr) { 1749 // This is a tentative definition; tentative definitions are 1750 // implicitly initialized with { 0 }. 1751 // 1752 // Note that tentative definitions are only emitted at the end of 1753 // a translation unit, so they should never have incomplete 1754 // type. In addition, EmitTentativeDefinition makes sure that we 1755 // never attempt to emit a tentative definition if a real one 1756 // exists. A use may still exists, however, so we still may need 1757 // to do a RAUW. 1758 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1759 Init = EmitNullConstant(D->getType()); 1760 } else { 1761 initializedGlobalDecl = GlobalDecl(D); 1762 Init = EmitConstantInit(*InitDecl); 1763 1764 if (!Init) { 1765 QualType T = InitExpr->getType(); 1766 if (D->getType()->isReferenceType()) 1767 T = D->getType(); 1768 1769 if (getLangOpts().CPlusPlus) { 1770 Init = EmitNullConstant(T); 1771 NeedsGlobalCtor = true; 1772 } else { 1773 ErrorUnsupported(D, "static initializer"); 1774 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1775 } 1776 } else { 1777 // We don't need an initializer, so remove the entry for the delayed 1778 // initializer position (just in case this entry was delayed) if we 1779 // also don't need to register a destructor. 1780 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 1781 DelayedCXXInitPosition.erase(D); 1782 } 1783 } 1784 1785 llvm::Type* InitType = Init->getType(); 1786 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1787 1788 // Strip off a bitcast if we got one back. 1789 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1790 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1791 // all zero index gep. 1792 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1793 Entry = CE->getOperand(0); 1794 } 1795 1796 // Entry is now either a Function or GlobalVariable. 1797 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1798 1799 // We have a definition after a declaration with the wrong type. 1800 // We must make a new GlobalVariable* and update everything that used OldGV 1801 // (a declaration or tentative definition) with the new GlobalVariable* 1802 // (which will be a definition). 1803 // 1804 // This happens if there is a prototype for a global (e.g. 1805 // "extern int x[];") and then a definition of a different type (e.g. 1806 // "int x[10];"). This also happens when an initializer has a different type 1807 // from the type of the global (this happens with unions). 1808 if (GV == 0 || 1809 GV->getType()->getElementType() != InitType || 1810 GV->getType()->getAddressSpace() != 1811 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 1812 1813 // Move the old entry aside so that we'll create a new one. 1814 Entry->setName(StringRef()); 1815 1816 // Make a new global with the correct type, this is now guaranteed to work. 1817 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1818 1819 // Replace all uses of the old global with the new global 1820 llvm::Constant *NewPtrForOldDecl = 1821 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1822 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1823 1824 // Erase the old global, since it is no longer used. 1825 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1826 } 1827 1828 MaybeHandleStaticInExternC(D, GV); 1829 1830 if (D->hasAttr<AnnotateAttr>()) 1831 AddGlobalAnnotations(D, GV); 1832 1833 GV->setInitializer(Init); 1834 1835 // If it is safe to mark the global 'constant', do so now. 1836 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 1837 isTypeConstant(D->getType(), true)); 1838 1839 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1840 1841 // Set the llvm linkage type as appropriate. 1842 llvm::GlobalValue::LinkageTypes Linkage = 1843 GetLLVMLinkageVarDefinition(D, GV->isConstant()); 1844 GV->setLinkage(Linkage); 1845 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1846 // common vars aren't constant even if declared const. 1847 GV->setConstant(false); 1848 1849 SetCommonAttributes(D, GV); 1850 1851 // Emit the initializer function if necessary. 1852 if (NeedsGlobalCtor || NeedsGlobalDtor) 1853 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 1854 1855 // If we are compiling with ASan, add metadata indicating dynamically 1856 // initialized globals. 1857 if (SanOpts.Address && NeedsGlobalCtor) { 1858 llvm::Module &M = getModule(); 1859 1860 llvm::NamedMDNode *DynamicInitializers = 1861 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals"); 1862 llvm::Value *GlobalToAdd[] = { GV }; 1863 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd); 1864 DynamicInitializers->addOperand(ThisGlobal); 1865 } 1866 1867 // Emit global variable debug information. 1868 if (CGDebugInfo *DI = getModuleDebugInfo()) 1869 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1870 DI->EmitGlobalVariable(GV, D); 1871 } 1872 1873 llvm::GlobalValue::LinkageTypes 1874 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) { 1875 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1876 if (Linkage == GVA_Internal) 1877 return llvm::Function::InternalLinkage; 1878 else if (D->hasAttr<DLLImportAttr>()) 1879 return llvm::Function::DLLImportLinkage; 1880 else if (D->hasAttr<DLLExportAttr>()) 1881 return llvm::Function::DLLExportLinkage; 1882 else if (D->hasAttr<SelectAnyAttr>()) { 1883 // selectany symbols are externally visible, so use weak instead of 1884 // linkonce. MSVC optimizes away references to const selectany globals, so 1885 // all definitions should be the same and ODR linkage should be used. 1886 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 1887 return llvm::GlobalVariable::WeakODRLinkage; 1888 } else if (D->hasAttr<WeakAttr>()) { 1889 if (isConstant) 1890 return llvm::GlobalVariable::WeakODRLinkage; 1891 else 1892 return llvm::GlobalVariable::WeakAnyLinkage; 1893 } else if (Linkage == GVA_TemplateInstantiation || 1894 Linkage == GVA_ExplicitTemplateInstantiation) 1895 return llvm::GlobalVariable::WeakODRLinkage; 1896 else if (!getLangOpts().CPlusPlus && 1897 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 1898 D->getAttr<CommonAttr>()) && 1899 !D->hasExternalStorage() && !D->getInit() && 1900 !D->getAttr<SectionAttr>() && !D->getTLSKind() && 1901 !D->getAttr<WeakImportAttr>()) { 1902 // Thread local vars aren't considered common linkage. 1903 return llvm::GlobalVariable::CommonLinkage; 1904 } else if (D->getTLSKind() == VarDecl::TLS_Dynamic && 1905 getTarget().getTriple().isMacOSX()) 1906 // On Darwin, the backing variable for a C++11 thread_local variable always 1907 // has internal linkage; all accesses should just be calls to the 1908 // Itanium-specified entry point, which has the normal linkage of the 1909 // variable. 1910 return llvm::GlobalValue::InternalLinkage; 1911 return llvm::GlobalVariable::ExternalLinkage; 1912 } 1913 1914 /// Replace the uses of a function that was declared with a non-proto type. 1915 /// We want to silently drop extra arguments from call sites 1916 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 1917 llvm::Function *newFn) { 1918 // Fast path. 1919 if (old->use_empty()) return; 1920 1921 llvm::Type *newRetTy = newFn->getReturnType(); 1922 SmallVector<llvm::Value*, 4> newArgs; 1923 1924 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 1925 ui != ue; ) { 1926 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 1927 llvm::User *user = *use; 1928 1929 // Recognize and replace uses of bitcasts. Most calls to 1930 // unprototyped functions will use bitcasts. 1931 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 1932 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 1933 replaceUsesOfNonProtoConstant(bitcast, newFn); 1934 continue; 1935 } 1936 1937 // Recognize calls to the function. 1938 llvm::CallSite callSite(user); 1939 if (!callSite) continue; 1940 if (!callSite.isCallee(use)) continue; 1941 1942 // If the return types don't match exactly, then we can't 1943 // transform this call unless it's dead. 1944 if (callSite->getType() != newRetTy && !callSite->use_empty()) 1945 continue; 1946 1947 // Get the call site's attribute list. 1948 SmallVector<llvm::AttributeSet, 8> newAttrs; 1949 llvm::AttributeSet oldAttrs = callSite.getAttributes(); 1950 1951 // Collect any return attributes from the call. 1952 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 1953 newAttrs.push_back( 1954 llvm::AttributeSet::get(newFn->getContext(), 1955 oldAttrs.getRetAttributes())); 1956 1957 // If the function was passed too few arguments, don't transform. 1958 unsigned newNumArgs = newFn->arg_size(); 1959 if (callSite.arg_size() < newNumArgs) continue; 1960 1961 // If extra arguments were passed, we silently drop them. 1962 // If any of the types mismatch, we don't transform. 1963 unsigned argNo = 0; 1964 bool dontTransform = false; 1965 for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 1966 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 1967 if (callSite.getArgument(argNo)->getType() != ai->getType()) { 1968 dontTransform = true; 1969 break; 1970 } 1971 1972 // Add any parameter attributes. 1973 if (oldAttrs.hasAttributes(argNo + 1)) 1974 newAttrs. 1975 push_back(llvm:: 1976 AttributeSet::get(newFn->getContext(), 1977 oldAttrs.getParamAttributes(argNo + 1))); 1978 } 1979 if (dontTransform) 1980 continue; 1981 1982 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 1983 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 1984 oldAttrs.getFnAttributes())); 1985 1986 // Okay, we can transform this. Create the new call instruction and copy 1987 // over the required information. 1988 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 1989 1990 llvm::CallSite newCall; 1991 if (callSite.isCall()) { 1992 newCall = llvm::CallInst::Create(newFn, newArgs, "", 1993 callSite.getInstruction()); 1994 } else { 1995 llvm::InvokeInst *oldInvoke = 1996 cast<llvm::InvokeInst>(callSite.getInstruction()); 1997 newCall = llvm::InvokeInst::Create(newFn, 1998 oldInvoke->getNormalDest(), 1999 oldInvoke->getUnwindDest(), 2000 newArgs, "", 2001 callSite.getInstruction()); 2002 } 2003 newArgs.clear(); // for the next iteration 2004 2005 if (!newCall->getType()->isVoidTy()) 2006 newCall->takeName(callSite.getInstruction()); 2007 newCall.setAttributes( 2008 llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2009 newCall.setCallingConv(callSite.getCallingConv()); 2010 2011 // Finally, remove the old call, replacing any uses with the new one. 2012 if (!callSite->use_empty()) 2013 callSite->replaceAllUsesWith(newCall.getInstruction()); 2014 2015 // Copy debug location attached to CI. 2016 if (!callSite->getDebugLoc().isUnknown()) 2017 newCall->setDebugLoc(callSite->getDebugLoc()); 2018 callSite->eraseFromParent(); 2019 } 2020 } 2021 2022 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2023 /// implement a function with no prototype, e.g. "int foo() {}". If there are 2024 /// existing call uses of the old function in the module, this adjusts them to 2025 /// call the new function directly. 2026 /// 2027 /// This is not just a cleanup: the always_inline pass requires direct calls to 2028 /// functions to be able to inline them. If there is a bitcast in the way, it 2029 /// won't inline them. Instcombine normally deletes these calls, but it isn't 2030 /// run at -O0. 2031 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2032 llvm::Function *NewFn) { 2033 // If we're redefining a global as a function, don't transform it. 2034 if (!isa<llvm::Function>(Old)) return; 2035 2036 replaceUsesOfNonProtoConstant(Old, NewFn); 2037 } 2038 2039 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2040 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2041 // If we have a definition, this might be a deferred decl. If the 2042 // instantiation is explicit, make sure we emit it at the end. 2043 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2044 GetAddrOfGlobalVar(VD); 2045 2046 EmitTopLevelDecl(VD); 2047 } 2048 2049 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 2050 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 2051 2052 // Compute the function info and LLVM type. 2053 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2054 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2055 2056 // Get or create the prototype for the function. 2057 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 2058 2059 // Strip off a bitcast if we got one back. 2060 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2061 assert(CE->getOpcode() == llvm::Instruction::BitCast); 2062 Entry = CE->getOperand(0); 2063 } 2064 2065 2066 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 2067 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 2068 2069 // If the types mismatch then we have to rewrite the definition. 2070 assert(OldFn->isDeclaration() && 2071 "Shouldn't replace non-declaration"); 2072 2073 // F is the Function* for the one with the wrong type, we must make a new 2074 // Function* and update everything that used F (a declaration) with the new 2075 // Function* (which will be a definition). 2076 // 2077 // This happens if there is a prototype for a function 2078 // (e.g. "int f()") and then a definition of a different type 2079 // (e.g. "int f(int x)"). Move the old function aside so that it 2080 // doesn't interfere with GetAddrOfFunction. 2081 OldFn->setName(StringRef()); 2082 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 2083 2084 // This might be an implementation of a function without a 2085 // prototype, in which case, try to do special replacement of 2086 // calls which match the new prototype. The really key thing here 2087 // is that we also potentially drop arguments from the call site 2088 // so as to make a direct call, which makes the inliner happier 2089 // and suppresses a number of optimizer warnings (!) about 2090 // dropping arguments. 2091 if (!OldFn->use_empty()) { 2092 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 2093 OldFn->removeDeadConstantUsers(); 2094 } 2095 2096 // Replace uses of F with the Function we will endow with a body. 2097 if (!Entry->use_empty()) { 2098 llvm::Constant *NewPtrForOldDecl = 2099 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 2100 Entry->replaceAllUsesWith(NewPtrForOldDecl); 2101 } 2102 2103 // Ok, delete the old function now, which is dead. 2104 OldFn->eraseFromParent(); 2105 2106 Entry = NewFn; 2107 } 2108 2109 // We need to set linkage and visibility on the function before 2110 // generating code for it because various parts of IR generation 2111 // want to propagate this information down (e.g. to local static 2112 // declarations). 2113 llvm::Function *Fn = cast<llvm::Function>(Entry); 2114 setFunctionLinkage(GD, Fn); 2115 2116 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 2117 setGlobalVisibility(Fn, D); 2118 2119 MaybeHandleStaticInExternC(D, Fn); 2120 2121 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2122 2123 SetFunctionDefinitionAttributes(D, Fn); 2124 SetLLVMFunctionAttributesForDefinition(D, Fn); 2125 2126 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2127 AddGlobalCtor(Fn, CA->getPriority()); 2128 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2129 AddGlobalDtor(Fn, DA->getPriority()); 2130 if (D->hasAttr<AnnotateAttr>()) 2131 AddGlobalAnnotations(D, Fn); 2132 } 2133 2134 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 2135 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 2136 const AliasAttr *AA = D->getAttr<AliasAttr>(); 2137 assert(AA && "Not an alias?"); 2138 2139 StringRef MangledName = getMangledName(GD); 2140 2141 // If there is a definition in the module, then it wins over the alias. 2142 // This is dubious, but allow it to be safe. Just ignore the alias. 2143 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2144 if (Entry && !Entry->isDeclaration()) 2145 return; 2146 2147 Aliases.push_back(GD); 2148 2149 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2150 2151 // Create a reference to the named value. This ensures that it is emitted 2152 // if a deferred decl. 2153 llvm::Constant *Aliasee; 2154 if (isa<llvm::FunctionType>(DeclTy)) 2155 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 2156 /*ForVTable=*/false); 2157 else 2158 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2159 llvm::PointerType::getUnqual(DeclTy), 0); 2160 2161 // Create the new alias itself, but don't set a name yet. 2162 llvm::GlobalValue *GA = 2163 new llvm::GlobalAlias(Aliasee->getType(), 2164 llvm::Function::ExternalLinkage, 2165 "", Aliasee, &getModule()); 2166 2167 if (Entry) { 2168 assert(Entry->isDeclaration()); 2169 2170 // If there is a declaration in the module, then we had an extern followed 2171 // by the alias, as in: 2172 // extern int test6(); 2173 // ... 2174 // int test6() __attribute__((alias("test7"))); 2175 // 2176 // Remove it and replace uses of it with the alias. 2177 GA->takeName(Entry); 2178 2179 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2180 Entry->getType())); 2181 Entry->eraseFromParent(); 2182 } else { 2183 GA->setName(MangledName); 2184 } 2185 2186 // Set attributes which are particular to an alias; this is a 2187 // specialization of the attributes which may be set on a global 2188 // variable/function. 2189 if (D->hasAttr<DLLExportAttr>()) { 2190 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2191 // The dllexport attribute is ignored for undefined symbols. 2192 if (FD->hasBody()) 2193 GA->setLinkage(llvm::Function::DLLExportLinkage); 2194 } else { 2195 GA->setLinkage(llvm::Function::DLLExportLinkage); 2196 } 2197 } else if (D->hasAttr<WeakAttr>() || 2198 D->hasAttr<WeakRefAttr>() || 2199 D->isWeakImported()) { 2200 GA->setLinkage(llvm::Function::WeakAnyLinkage); 2201 } 2202 2203 SetCommonAttributes(D, GA); 2204 } 2205 2206 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 2207 ArrayRef<llvm::Type*> Tys) { 2208 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 2209 Tys); 2210 } 2211 2212 static llvm::StringMapEntry<llvm::Constant*> & 2213 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2214 const StringLiteral *Literal, 2215 bool TargetIsLSB, 2216 bool &IsUTF16, 2217 unsigned &StringLength) { 2218 StringRef String = Literal->getString(); 2219 unsigned NumBytes = String.size(); 2220 2221 // Check for simple case. 2222 if (!Literal->containsNonAsciiOrNull()) { 2223 StringLength = NumBytes; 2224 return Map.GetOrCreateValue(String); 2225 } 2226 2227 // Otherwise, convert the UTF8 literals into a string of shorts. 2228 IsUTF16 = true; 2229 2230 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 2231 const UTF8 *FromPtr = (const UTF8 *)String.data(); 2232 UTF16 *ToPtr = &ToBuf[0]; 2233 2234 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2235 &ToPtr, ToPtr + NumBytes, 2236 strictConversion); 2237 2238 // ConvertUTF8toUTF16 returns the length in ToPtr. 2239 StringLength = ToPtr - &ToBuf[0]; 2240 2241 // Add an explicit null. 2242 *ToPtr = 0; 2243 return Map. 2244 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()), 2245 (StringLength + 1) * 2)); 2246 } 2247 2248 static llvm::StringMapEntry<llvm::Constant*> & 2249 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2250 const StringLiteral *Literal, 2251 unsigned &StringLength) { 2252 StringRef String = Literal->getString(); 2253 StringLength = String.size(); 2254 return Map.GetOrCreateValue(String); 2255 } 2256 2257 llvm::Constant * 2258 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2259 unsigned StringLength = 0; 2260 bool isUTF16 = false; 2261 llvm::StringMapEntry<llvm::Constant*> &Entry = 2262 GetConstantCFStringEntry(CFConstantStringMap, Literal, 2263 getDataLayout().isLittleEndian(), 2264 isUTF16, StringLength); 2265 2266 if (llvm::Constant *C = Entry.getValue()) 2267 return C; 2268 2269 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2270 llvm::Constant *Zeros[] = { Zero, Zero }; 2271 llvm::Value *V; 2272 2273 // If we don't already have it, get __CFConstantStringClassReference. 2274 if (!CFConstantStringClassRef) { 2275 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2276 Ty = llvm::ArrayType::get(Ty, 0); 2277 llvm::Constant *GV = CreateRuntimeVariable(Ty, 2278 "__CFConstantStringClassReference"); 2279 // Decay array -> ptr 2280 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2281 CFConstantStringClassRef = V; 2282 } 2283 else 2284 V = CFConstantStringClassRef; 2285 2286 QualType CFTy = getContext().getCFConstantStringType(); 2287 2288 llvm::StructType *STy = 2289 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2290 2291 llvm::Constant *Fields[4]; 2292 2293 // Class pointer. 2294 Fields[0] = cast<llvm::ConstantExpr>(V); 2295 2296 // Flags. 2297 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2298 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2299 llvm::ConstantInt::get(Ty, 0x07C8); 2300 2301 // String pointer. 2302 llvm::Constant *C = 0; 2303 if (isUTF16) { 2304 ArrayRef<uint16_t> Arr = 2305 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>( 2306 const_cast<char *>(Entry.getKey().data())), 2307 Entry.getKey().size() / 2); 2308 C = llvm::ConstantDataArray::get(VMContext, Arr); 2309 } else { 2310 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2311 } 2312 2313 llvm::GlobalValue::LinkageTypes Linkage; 2314 if (isUTF16) 2315 // FIXME: why do utf strings get "_" labels instead of "L" labels? 2316 Linkage = llvm::GlobalValue::InternalLinkage; 2317 else 2318 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error 2319 // when using private linkage. It is not clear if this is a bug in ld 2320 // or a reasonable new restriction. 2321 Linkage = llvm::GlobalValue::LinkerPrivateLinkage; 2322 2323 // Note: -fwritable-strings doesn't make the backing store strings of 2324 // CFStrings writable. (See <rdar://problem/10657500>) 2325 llvm::GlobalVariable *GV = 2326 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 2327 Linkage, C, ".str"); 2328 GV->setUnnamedAddr(true); 2329 // Don't enforce the target's minimum global alignment, since the only use 2330 // of the string is via this class initializer. 2331 if (isUTF16) { 2332 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2333 GV->setAlignment(Align.getQuantity()); 2334 } else { 2335 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2336 GV->setAlignment(Align.getQuantity()); 2337 } 2338 2339 // String. 2340 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2341 2342 if (isUTF16) 2343 // Cast the UTF16 string to the correct type. 2344 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2345 2346 // String length. 2347 Ty = getTypes().ConvertType(getContext().LongTy); 2348 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2349 2350 // The struct. 2351 C = llvm::ConstantStruct::get(STy, Fields); 2352 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2353 llvm::GlobalVariable::PrivateLinkage, C, 2354 "_unnamed_cfstring_"); 2355 if (const char *Sect = getTarget().getCFStringSection()) 2356 GV->setSection(Sect); 2357 Entry.setValue(GV); 2358 2359 return GV; 2360 } 2361 2362 static RecordDecl * 2363 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 2364 DeclContext *DC, IdentifierInfo *Id) { 2365 SourceLocation Loc; 2366 if (Ctx.getLangOpts().CPlusPlus) 2367 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 2368 else 2369 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 2370 } 2371 2372 llvm::Constant * 2373 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2374 unsigned StringLength = 0; 2375 llvm::StringMapEntry<llvm::Constant*> &Entry = 2376 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2377 2378 if (llvm::Constant *C = Entry.getValue()) 2379 return C; 2380 2381 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2382 llvm::Constant *Zeros[] = { Zero, Zero }; 2383 llvm::Value *V; 2384 // If we don't already have it, get _NSConstantStringClassReference. 2385 if (!ConstantStringClassRef) { 2386 std::string StringClass(getLangOpts().ObjCConstantStringClass); 2387 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2388 llvm::Constant *GV; 2389 if (LangOpts.ObjCRuntime.isNonFragile()) { 2390 std::string str = 2391 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2392 : "OBJC_CLASS_$_" + StringClass; 2393 GV = getObjCRuntime().GetClassGlobal(str); 2394 // Make sure the result is of the correct type. 2395 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2396 V = llvm::ConstantExpr::getBitCast(GV, PTy); 2397 ConstantStringClassRef = V; 2398 } else { 2399 std::string str = 2400 StringClass.empty() ? "_NSConstantStringClassReference" 2401 : "_" + StringClass + "ClassReference"; 2402 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2403 GV = CreateRuntimeVariable(PTy, str); 2404 // Decay array -> ptr 2405 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2406 ConstantStringClassRef = V; 2407 } 2408 } 2409 else 2410 V = ConstantStringClassRef; 2411 2412 if (!NSConstantStringType) { 2413 // Construct the type for a constant NSString. 2414 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 2415 Context.getTranslationUnitDecl(), 2416 &Context.Idents.get("__builtin_NSString")); 2417 D->startDefinition(); 2418 2419 QualType FieldTypes[3]; 2420 2421 // const int *isa; 2422 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 2423 // const char *str; 2424 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 2425 // unsigned int length; 2426 FieldTypes[2] = Context.UnsignedIntTy; 2427 2428 // Create fields 2429 for (unsigned i = 0; i < 3; ++i) { 2430 FieldDecl *Field = FieldDecl::Create(Context, D, 2431 SourceLocation(), 2432 SourceLocation(), 0, 2433 FieldTypes[i], /*TInfo=*/0, 2434 /*BitWidth=*/0, 2435 /*Mutable=*/false, 2436 ICIS_NoInit); 2437 Field->setAccess(AS_public); 2438 D->addDecl(Field); 2439 } 2440 2441 D->completeDefinition(); 2442 QualType NSTy = Context.getTagDeclType(D); 2443 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 2444 } 2445 2446 llvm::Constant *Fields[3]; 2447 2448 // Class pointer. 2449 Fields[0] = cast<llvm::ConstantExpr>(V); 2450 2451 // String pointer. 2452 llvm::Constant *C = 2453 llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2454 2455 llvm::GlobalValue::LinkageTypes Linkage; 2456 bool isConstant; 2457 Linkage = llvm::GlobalValue::PrivateLinkage; 2458 isConstant = !LangOpts.WritableStrings; 2459 2460 llvm::GlobalVariable *GV = 2461 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 2462 ".str"); 2463 GV->setUnnamedAddr(true); 2464 // Don't enforce the target's minimum global alignment, since the only use 2465 // of the string is via this class initializer. 2466 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2467 GV->setAlignment(Align.getQuantity()); 2468 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2469 2470 // String length. 2471 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2472 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 2473 2474 // The struct. 2475 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 2476 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2477 llvm::GlobalVariable::PrivateLinkage, C, 2478 "_unnamed_nsstring_"); 2479 // FIXME. Fix section. 2480 if (const char *Sect = 2481 LangOpts.ObjCRuntime.isNonFragile() 2482 ? getTarget().getNSStringNonFragileABISection() 2483 : getTarget().getNSStringSection()) 2484 GV->setSection(Sect); 2485 Entry.setValue(GV); 2486 2487 return GV; 2488 } 2489 2490 QualType CodeGenModule::getObjCFastEnumerationStateType() { 2491 if (ObjCFastEnumerationStateType.isNull()) { 2492 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 2493 Context.getTranslationUnitDecl(), 2494 &Context.Idents.get("__objcFastEnumerationState")); 2495 D->startDefinition(); 2496 2497 QualType FieldTypes[] = { 2498 Context.UnsignedLongTy, 2499 Context.getPointerType(Context.getObjCIdType()), 2500 Context.getPointerType(Context.UnsignedLongTy), 2501 Context.getConstantArrayType(Context.UnsignedLongTy, 2502 llvm::APInt(32, 5), ArrayType::Normal, 0) 2503 }; 2504 2505 for (size_t i = 0; i < 4; ++i) { 2506 FieldDecl *Field = FieldDecl::Create(Context, 2507 D, 2508 SourceLocation(), 2509 SourceLocation(), 0, 2510 FieldTypes[i], /*TInfo=*/0, 2511 /*BitWidth=*/0, 2512 /*Mutable=*/false, 2513 ICIS_NoInit); 2514 Field->setAccess(AS_public); 2515 D->addDecl(Field); 2516 } 2517 2518 D->completeDefinition(); 2519 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 2520 } 2521 2522 return ObjCFastEnumerationStateType; 2523 } 2524 2525 llvm::Constant * 2526 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 2527 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 2528 2529 // Don't emit it as the address of the string, emit the string data itself 2530 // as an inline array. 2531 if (E->getCharByteWidth() == 1) { 2532 SmallString<64> Str(E->getString()); 2533 2534 // Resize the string to the right size, which is indicated by its type. 2535 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 2536 Str.resize(CAT->getSize().getZExtValue()); 2537 return llvm::ConstantDataArray::getString(VMContext, Str, false); 2538 } 2539 2540 llvm::ArrayType *AType = 2541 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 2542 llvm::Type *ElemTy = AType->getElementType(); 2543 unsigned NumElements = AType->getNumElements(); 2544 2545 // Wide strings have either 2-byte or 4-byte elements. 2546 if (ElemTy->getPrimitiveSizeInBits() == 16) { 2547 SmallVector<uint16_t, 32> Elements; 2548 Elements.reserve(NumElements); 2549 2550 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2551 Elements.push_back(E->getCodeUnit(i)); 2552 Elements.resize(NumElements); 2553 return llvm::ConstantDataArray::get(VMContext, Elements); 2554 } 2555 2556 assert(ElemTy->getPrimitiveSizeInBits() == 32); 2557 SmallVector<uint32_t, 32> Elements; 2558 Elements.reserve(NumElements); 2559 2560 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2561 Elements.push_back(E->getCodeUnit(i)); 2562 Elements.resize(NumElements); 2563 return llvm::ConstantDataArray::get(VMContext, Elements); 2564 } 2565 2566 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 2567 /// constant array for the given string literal. 2568 llvm::Constant * 2569 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 2570 CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType()); 2571 if (S->isAscii() || S->isUTF8()) { 2572 SmallString<64> Str(S->getString()); 2573 2574 // Resize the string to the right size, which is indicated by its type. 2575 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType()); 2576 Str.resize(CAT->getSize().getZExtValue()); 2577 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity()); 2578 } 2579 2580 // FIXME: the following does not memoize wide strings. 2581 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 2582 llvm::GlobalVariable *GV = 2583 new llvm::GlobalVariable(getModule(),C->getType(), 2584 !LangOpts.WritableStrings, 2585 llvm::GlobalValue::PrivateLinkage, 2586 C,".str"); 2587 2588 GV->setAlignment(Align.getQuantity()); 2589 GV->setUnnamedAddr(true); 2590 return GV; 2591 } 2592 2593 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2594 /// array for the given ObjCEncodeExpr node. 2595 llvm::Constant * 2596 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2597 std::string Str; 2598 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2599 2600 return GetAddrOfConstantCString(Str); 2601 } 2602 2603 2604 /// GenerateWritableString -- Creates storage for a string literal. 2605 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 2606 bool constant, 2607 CodeGenModule &CGM, 2608 const char *GlobalName, 2609 unsigned Alignment) { 2610 // Create Constant for this string literal. Don't add a '\0'. 2611 llvm::Constant *C = 2612 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false); 2613 2614 // Create a global variable for this string 2615 llvm::GlobalVariable *GV = 2616 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 2617 llvm::GlobalValue::PrivateLinkage, 2618 C, GlobalName); 2619 GV->setAlignment(Alignment); 2620 GV->setUnnamedAddr(true); 2621 return GV; 2622 } 2623 2624 /// GetAddrOfConstantString - Returns a pointer to a character array 2625 /// containing the literal. This contents are exactly that of the 2626 /// given string, i.e. it will not be null terminated automatically; 2627 /// see GetAddrOfConstantCString. Note that whether the result is 2628 /// actually a pointer to an LLVM constant depends on 2629 /// Feature.WriteableStrings. 2630 /// 2631 /// The result has pointer to array type. 2632 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 2633 const char *GlobalName, 2634 unsigned Alignment) { 2635 // Get the default prefix if a name wasn't specified. 2636 if (!GlobalName) 2637 GlobalName = ".str"; 2638 2639 if (Alignment == 0) 2640 Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy) 2641 .getQuantity(); 2642 2643 // Don't share any string literals if strings aren't constant. 2644 if (LangOpts.WritableStrings) 2645 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2646 2647 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2648 ConstantStringMap.GetOrCreateValue(Str); 2649 2650 if (llvm::GlobalVariable *GV = Entry.getValue()) { 2651 if (Alignment > GV->getAlignment()) { 2652 GV->setAlignment(Alignment); 2653 } 2654 return GV; 2655 } 2656 2657 // Create a global variable for this. 2658 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, 2659 Alignment); 2660 Entry.setValue(GV); 2661 return GV; 2662 } 2663 2664 /// GetAddrOfConstantCString - Returns a pointer to a character 2665 /// array containing the literal and a terminating '\0' 2666 /// character. The result has pointer to array type. 2667 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 2668 const char *GlobalName, 2669 unsigned Alignment) { 2670 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2671 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2672 } 2673 2674 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary( 2675 const MaterializeTemporaryExpr *E, const Expr *Init) { 2676 assert((E->getStorageDuration() == SD_Static || 2677 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 2678 const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl()); 2679 2680 // If we're not materializing a subobject of the temporary, keep the 2681 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 2682 QualType MaterializedType = Init->getType(); 2683 if (Init == E->GetTemporaryExpr()) 2684 MaterializedType = E->getType(); 2685 2686 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E]; 2687 if (Slot) 2688 return Slot; 2689 2690 // FIXME: If an externally-visible declaration extends multiple temporaries, 2691 // we need to give each temporary the same name in every translation unit (and 2692 // we also need to make the temporaries externally-visible). 2693 SmallString<256> Name; 2694 llvm::raw_svector_ostream Out(Name); 2695 getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out); 2696 Out.flush(); 2697 2698 APValue *Value = 0; 2699 if (E->getStorageDuration() == SD_Static) { 2700 // We might have a cached constant initializer for this temporary. Note 2701 // that this might have a different value from the value computed by 2702 // evaluating the initializer if the surrounding constant expression 2703 // modifies the temporary. 2704 Value = getContext().getMaterializedTemporaryValue(E, false); 2705 if (Value && Value->isUninit()) 2706 Value = 0; 2707 } 2708 2709 // Try evaluating it now, it might have a constant initializer. 2710 Expr::EvalResult EvalResult; 2711 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 2712 !EvalResult.hasSideEffects()) 2713 Value = &EvalResult.Val; 2714 2715 llvm::Constant *InitialValue = 0; 2716 bool Constant = false; 2717 llvm::Type *Type; 2718 if (Value) { 2719 // The temporary has a constant initializer, use it. 2720 InitialValue = EmitConstantValue(*Value, MaterializedType, 0); 2721 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 2722 Type = InitialValue->getType(); 2723 } else { 2724 // No initializer, the initialization will be provided when we 2725 // initialize the declaration which performed lifetime extension. 2726 Type = getTypes().ConvertTypeForMem(MaterializedType); 2727 } 2728 2729 // Create a global variable for this lifetime-extended temporary. 2730 llvm::GlobalVariable *GV = 2731 new llvm::GlobalVariable(getModule(), Type, Constant, 2732 llvm::GlobalValue::PrivateLinkage, 2733 InitialValue, Name.c_str()); 2734 GV->setAlignment( 2735 getContext().getTypeAlignInChars(MaterializedType).getQuantity()); 2736 if (VD->getTLSKind()) 2737 setTLSMode(GV, *VD); 2738 Slot = GV; 2739 return GV; 2740 } 2741 2742 /// EmitObjCPropertyImplementations - Emit information for synthesized 2743 /// properties for an implementation. 2744 void CodeGenModule::EmitObjCPropertyImplementations(const 2745 ObjCImplementationDecl *D) { 2746 for (ObjCImplementationDecl::propimpl_iterator 2747 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 2748 ObjCPropertyImplDecl *PID = *i; 2749 2750 // Dynamic is just for type-checking. 2751 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2752 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2753 2754 // Determine which methods need to be implemented, some may have 2755 // been overridden. Note that ::isPropertyAccessor is not the method 2756 // we want, that just indicates if the decl came from a 2757 // property. What we want to know is if the method is defined in 2758 // this implementation. 2759 if (!D->getInstanceMethod(PD->getGetterName())) 2760 CodeGenFunction(*this).GenerateObjCGetter( 2761 const_cast<ObjCImplementationDecl *>(D), PID); 2762 if (!PD->isReadOnly() && 2763 !D->getInstanceMethod(PD->getSetterName())) 2764 CodeGenFunction(*this).GenerateObjCSetter( 2765 const_cast<ObjCImplementationDecl *>(D), PID); 2766 } 2767 } 2768 } 2769 2770 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 2771 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2772 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2773 ivar; ivar = ivar->getNextIvar()) 2774 if (ivar->getType().isDestructedType()) 2775 return true; 2776 2777 return false; 2778 } 2779 2780 /// EmitObjCIvarInitializations - Emit information for ivar initialization 2781 /// for an implementation. 2782 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2783 // We might need a .cxx_destruct even if we don't have any ivar initializers. 2784 if (needsDestructMethod(D)) { 2785 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2786 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2787 ObjCMethodDecl *DTORMethod = 2788 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2789 cxxSelector, getContext().VoidTy, 0, D, 2790 /*isInstance=*/true, /*isVariadic=*/false, 2791 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 2792 /*isDefined=*/false, ObjCMethodDecl::Required); 2793 D->addInstanceMethod(DTORMethod); 2794 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2795 D->setHasDestructors(true); 2796 } 2797 2798 // If the implementation doesn't have any ivar initializers, we don't need 2799 // a .cxx_construct. 2800 if (D->getNumIvarInitializers() == 0) 2801 return; 2802 2803 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2804 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2805 // The constructor returns 'self'. 2806 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2807 D->getLocation(), 2808 D->getLocation(), 2809 cxxSelector, 2810 getContext().getObjCIdType(), 0, 2811 D, /*isInstance=*/true, 2812 /*isVariadic=*/false, 2813 /*isPropertyAccessor=*/true, 2814 /*isImplicitlyDeclared=*/true, 2815 /*isDefined=*/false, 2816 ObjCMethodDecl::Required); 2817 D->addInstanceMethod(CTORMethod); 2818 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2819 D->setHasNonZeroConstructors(true); 2820 } 2821 2822 /// EmitNamespace - Emit all declarations in a namespace. 2823 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2824 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 2825 I != E; ++I) { 2826 if (const VarDecl *VD = dyn_cast<VarDecl>(*I)) 2827 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 2828 VD->getTemplateSpecializationKind() != TSK_Undeclared) 2829 continue; 2830 EmitTopLevelDecl(*I); 2831 } 2832 } 2833 2834 // EmitLinkageSpec - Emit all declarations in a linkage spec. 2835 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2836 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2837 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2838 ErrorUnsupported(LSD, "linkage spec"); 2839 return; 2840 } 2841 2842 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 2843 I != E; ++I) { 2844 // Meta-data for ObjC class includes references to implemented methods. 2845 // Generate class's method definitions first. 2846 if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) { 2847 for (ObjCContainerDecl::method_iterator M = OID->meth_begin(), 2848 MEnd = OID->meth_end(); 2849 M != MEnd; ++M) 2850 EmitTopLevelDecl(*M); 2851 } 2852 EmitTopLevelDecl(*I); 2853 } 2854 } 2855 2856 /// EmitTopLevelDecl - Emit code for a single top level declaration. 2857 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 2858 // Ignore dependent declarations. 2859 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 2860 return; 2861 2862 switch (D->getKind()) { 2863 case Decl::CXXConversion: 2864 case Decl::CXXMethod: 2865 case Decl::Function: 2866 // Skip function templates 2867 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2868 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2869 return; 2870 2871 EmitGlobal(cast<FunctionDecl>(D)); 2872 break; 2873 2874 case Decl::Var: 2875 // Skip variable templates 2876 if (cast<VarDecl>(D)->getDescribedVarTemplate()) 2877 return; 2878 case Decl::VarTemplateSpecialization: 2879 EmitGlobal(cast<VarDecl>(D)); 2880 break; 2881 2882 // Indirect fields from global anonymous structs and unions can be 2883 // ignored; only the actual variable requires IR gen support. 2884 case Decl::IndirectField: 2885 break; 2886 2887 // C++ Decls 2888 case Decl::Namespace: 2889 EmitNamespace(cast<NamespaceDecl>(D)); 2890 break; 2891 // No code generation needed. 2892 case Decl::UsingShadow: 2893 case Decl::Using: 2894 case Decl::ClassTemplate: 2895 case Decl::VarTemplate: 2896 case Decl::VarTemplatePartialSpecialization: 2897 case Decl::FunctionTemplate: 2898 case Decl::TypeAliasTemplate: 2899 case Decl::Block: 2900 case Decl::Empty: 2901 break; 2902 case Decl::NamespaceAlias: 2903 if (CGDebugInfo *DI = getModuleDebugInfo()) 2904 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 2905 return; 2906 case Decl::UsingDirective: // using namespace X; [C++] 2907 if (CGDebugInfo *DI = getModuleDebugInfo()) 2908 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 2909 return; 2910 case Decl::CXXConstructor: 2911 // Skip function templates 2912 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2913 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2914 return; 2915 2916 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 2917 break; 2918 case Decl::CXXDestructor: 2919 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 2920 return; 2921 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 2922 break; 2923 2924 case Decl::StaticAssert: 2925 // Nothing to do. 2926 break; 2927 2928 // Objective-C Decls 2929 2930 // Forward declarations, no (immediate) code generation. 2931 case Decl::ObjCInterface: 2932 case Decl::ObjCCategory: 2933 break; 2934 2935 case Decl::ObjCProtocol: { 2936 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D); 2937 if (Proto->isThisDeclarationADefinition()) 2938 ObjCRuntime->GenerateProtocol(Proto); 2939 break; 2940 } 2941 2942 case Decl::ObjCCategoryImpl: 2943 // Categories have properties but don't support synthesize so we 2944 // can ignore them here. 2945 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2946 break; 2947 2948 case Decl::ObjCImplementation: { 2949 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 2950 EmitObjCPropertyImplementations(OMD); 2951 EmitObjCIvarInitializations(OMD); 2952 ObjCRuntime->GenerateClass(OMD); 2953 // Emit global variable debug information. 2954 if (CGDebugInfo *DI = getModuleDebugInfo()) 2955 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 2956 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 2957 OMD->getClassInterface()), OMD->getLocation()); 2958 break; 2959 } 2960 case Decl::ObjCMethod: { 2961 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 2962 // If this is not a prototype, emit the body. 2963 if (OMD->getBody()) 2964 CodeGenFunction(*this).GenerateObjCMethod(OMD); 2965 break; 2966 } 2967 case Decl::ObjCCompatibleAlias: 2968 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 2969 break; 2970 2971 case Decl::LinkageSpec: 2972 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2973 break; 2974 2975 case Decl::FileScopeAsm: { 2976 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 2977 StringRef AsmString = AD->getAsmString()->getString(); 2978 2979 const std::string &S = getModule().getModuleInlineAsm(); 2980 if (S.empty()) 2981 getModule().setModuleInlineAsm(AsmString); 2982 else if (S.end()[-1] == '\n') 2983 getModule().setModuleInlineAsm(S + AsmString.str()); 2984 else 2985 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2986 break; 2987 } 2988 2989 case Decl::Import: { 2990 ImportDecl *Import = cast<ImportDecl>(D); 2991 2992 // Ignore import declarations that come from imported modules. 2993 if (clang::Module *Owner = Import->getOwningModule()) { 2994 if (getLangOpts().CurrentModule.empty() || 2995 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule) 2996 break; 2997 } 2998 2999 ImportedModules.insert(Import->getImportedModule()); 3000 break; 3001 } 3002 3003 default: 3004 // Make sure we handled everything we should, every other kind is a 3005 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3006 // function. Need to recode Decl::Kind to do that easily. 3007 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 3008 } 3009 } 3010 3011 /// Turns the given pointer into a constant. 3012 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3013 const void *Ptr) { 3014 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 3015 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3016 return llvm::ConstantInt::get(i64, PtrInt); 3017 } 3018 3019 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3020 llvm::NamedMDNode *&GlobalMetadata, 3021 GlobalDecl D, 3022 llvm::GlobalValue *Addr) { 3023 if (!GlobalMetadata) 3024 GlobalMetadata = 3025 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3026 3027 // TODO: should we report variant information for ctors/dtors? 3028 llvm::Value *Ops[] = { 3029 Addr, 3030 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 3031 }; 3032 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3033 } 3034 3035 /// For each function which is declared within an extern "C" region and marked 3036 /// as 'used', but has internal linkage, create an alias from the unmangled 3037 /// name to the mangled name if possible. People expect to be able to refer 3038 /// to such functions with an unmangled name from inline assembly within the 3039 /// same translation unit. 3040 void CodeGenModule::EmitStaticExternCAliases() { 3041 for (StaticExternCMap::iterator I = StaticExternCValues.begin(), 3042 E = StaticExternCValues.end(); 3043 I != E; ++I) { 3044 IdentifierInfo *Name = I->first; 3045 llvm::GlobalValue *Val = I->second; 3046 if (Val && !getModule().getNamedValue(Name->getName())) 3047 AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(), 3048 Name->getName(), Val, &getModule())); 3049 } 3050 } 3051 3052 /// Emits metadata nodes associating all the global values in the 3053 /// current module with the Decls they came from. This is useful for 3054 /// projects using IR gen as a subroutine. 3055 /// 3056 /// Since there's currently no way to associate an MDNode directly 3057 /// with an llvm::GlobalValue, we create a global named metadata 3058 /// with the name 'clang.global.decl.ptrs'. 3059 void CodeGenModule::EmitDeclMetadata() { 3060 llvm::NamedMDNode *GlobalMetadata = 0; 3061 3062 // StaticLocalDeclMap 3063 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 3064 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 3065 I != E; ++I) { 3066 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 3067 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 3068 } 3069 } 3070 3071 /// Emits metadata nodes for all the local variables in the current 3072 /// function. 3073 void CodeGenFunction::EmitDeclMetadata() { 3074 if (LocalDeclMap.empty()) return; 3075 3076 llvm::LLVMContext &Context = getLLVMContext(); 3077 3078 // Find the unique metadata ID for this name. 3079 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3080 3081 llvm::NamedMDNode *GlobalMetadata = 0; 3082 3083 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 3084 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 3085 const Decl *D = I->first; 3086 llvm::Value *Addr = I->second; 3087 3088 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3089 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 3090 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 3091 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3092 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3093 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3094 } 3095 } 3096 } 3097 3098 void CodeGenModule::EmitVersionIdentMetadata() { 3099 llvm::NamedMDNode *IdentMetadata = 3100 TheModule.getOrInsertNamedMetadata("llvm.ident"); 3101 std::string Version = getClangFullVersion(); 3102 llvm::LLVMContext &Ctx = TheModule.getContext(); 3103 3104 llvm::Value *IdentNode[] = { 3105 llvm::MDString::get(Ctx, Version) 3106 }; 3107 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3108 } 3109 3110 void CodeGenModule::EmitCoverageFile() { 3111 if (!getCodeGenOpts().CoverageFile.empty()) { 3112 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3113 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3114 llvm::LLVMContext &Ctx = TheModule.getContext(); 3115 llvm::MDString *CoverageFile = 3116 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3117 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3118 llvm::MDNode *CU = CUNode->getOperand(i); 3119 llvm::Value *node[] = { CoverageFile, CU }; 3120 llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 3121 GCov->addOperand(N); 3122 } 3123 } 3124 } 3125 } 3126 3127 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid, 3128 QualType GuidType) { 3129 // Sema has checked that all uuid strings are of the form 3130 // "12345678-1234-1234-1234-1234567890ab". 3131 assert(Uuid.size() == 36); 3132 for (unsigned i = 0; i < 36; ++i) { 3133 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3134 else assert(isHexDigit(Uuid[i])); 3135 } 3136 3137 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 3138 3139 llvm::Constant *Field3[8]; 3140 for (unsigned Idx = 0; Idx < 8; ++Idx) 3141 Field3[Idx] = llvm::ConstantInt::get( 3142 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 3143 3144 llvm::Constant *Fields[4] = { 3145 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3146 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3147 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3148 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3149 }; 3150 3151 return llvm::ConstantStruct::getAnon(Fields); 3152 } 3153