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