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