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