1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This coordinates the per-module state used while generating code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeGenModule.h" 14 #include "CGBlocks.h" 15 #include "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGCall.h" 18 #include "CGDebugInfo.h" 19 #include "CGHLSLRuntime.h" 20 #include "CGObjCRuntime.h" 21 #include "CGOpenCLRuntime.h" 22 #include "CGOpenMPRuntime.h" 23 #include "CGOpenMPRuntimeGPU.h" 24 #include "CodeGenFunction.h" 25 #include "CodeGenPGO.h" 26 #include "ConstantEmitter.h" 27 #include "CoverageMappingGen.h" 28 #include "TargetInfo.h" 29 #include "clang/AST/ASTContext.h" 30 #include "clang/AST/CharUnits.h" 31 #include "clang/AST/DeclCXX.h" 32 #include "clang/AST/DeclObjC.h" 33 #include "clang/AST/DeclTemplate.h" 34 #include "clang/AST/Mangle.h" 35 #include "clang/AST/RecordLayout.h" 36 #include "clang/AST/RecursiveASTVisitor.h" 37 #include "clang/AST/StmtVisitor.h" 38 #include "clang/Basic/Builtins.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/CodeGenOptions.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/FileManager.h" 43 #include "clang/Basic/Module.h" 44 #include "clang/Basic/SourceManager.h" 45 #include "clang/Basic/TargetInfo.h" 46 #include "clang/Basic/Version.h" 47 #include "clang/CodeGen/BackendUtil.h" 48 #include "clang/CodeGen/ConstantInitBuilder.h" 49 #include "clang/Frontend/FrontendDiagnostic.h" 50 #include "llvm/ADT/StringSwitch.h" 51 #include "llvm/ADT/Triple.h" 52 #include "llvm/Analysis/TargetLibraryInfo.h" 53 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 54 #include "llvm/IR/CallingConv.h" 55 #include "llvm/IR/DataLayout.h" 56 #include "llvm/IR/Intrinsics.h" 57 #include "llvm/IR/LLVMContext.h" 58 #include "llvm/IR/Module.h" 59 #include "llvm/IR/ProfileSummary.h" 60 #include "llvm/ProfileData/InstrProfReader.h" 61 #include "llvm/Support/CodeGen.h" 62 #include "llvm/Support/CommandLine.h" 63 #include "llvm/Support/ConvertUTF.h" 64 #include "llvm/Support/ErrorHandling.h" 65 #include "llvm/Support/MD5.h" 66 #include "llvm/Support/TimeProfiler.h" 67 #include "llvm/Support/X86TargetParser.h" 68 69 using namespace clang; 70 using namespace CodeGen; 71 72 static llvm::cl::opt<bool> LimitedCoverage( 73 "limited-coverage-experimental", llvm::cl::Hidden, 74 llvm::cl::desc("Emit limited coverage mapping information (experimental)")); 75 76 static const char AnnotationSection[] = "llvm.metadata"; 77 78 static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 79 switch (CGM.getContext().getCXXABIKind()) { 80 case TargetCXXABI::AppleARM64: 81 case TargetCXXABI::Fuchsia: 82 case TargetCXXABI::GenericAArch64: 83 case TargetCXXABI::GenericARM: 84 case TargetCXXABI::iOS: 85 case TargetCXXABI::WatchOS: 86 case TargetCXXABI::GenericMIPS: 87 case TargetCXXABI::GenericItanium: 88 case TargetCXXABI::WebAssembly: 89 case TargetCXXABI::XL: 90 return CreateItaniumCXXABI(CGM); 91 case TargetCXXABI::Microsoft: 92 return CreateMicrosoftCXXABI(CGM); 93 } 94 95 llvm_unreachable("invalid C++ ABI kind"); 96 } 97 98 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 99 const PreprocessorOptions &PPO, 100 const CodeGenOptions &CGO, llvm::Module &M, 101 DiagnosticsEngine &diags, 102 CoverageSourceInfo *CoverageInfo) 103 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 104 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 105 Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 106 VMContext(M.getContext()), Types(*this), VTables(*this), 107 SanitizerMD(new SanitizerMetadata(*this)) { 108 109 // Initialize the type cache. 110 llvm::LLVMContext &LLVMContext = M.getContext(); 111 VoidTy = llvm::Type::getVoidTy(LLVMContext); 112 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 113 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 114 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 115 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 116 HalfTy = llvm::Type::getHalfTy(LLVMContext); 117 BFloatTy = llvm::Type::getBFloatTy(LLVMContext); 118 FloatTy = llvm::Type::getFloatTy(LLVMContext); 119 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 120 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 121 PointerAlignInBytes = 122 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 123 SizeSizeInBytes = 124 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 125 IntAlignInBytes = 126 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 127 CharTy = 128 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth()); 129 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 130 IntPtrTy = llvm::IntegerType::get(LLVMContext, 131 C.getTargetInfo().getMaxPointerWidth()); 132 Int8PtrTy = Int8Ty->getPointerTo(0); 133 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 134 const llvm::DataLayout &DL = M.getDataLayout(); 135 AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace()); 136 GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace()); 137 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 138 139 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 140 141 if (LangOpts.ObjC) 142 createObjCRuntime(); 143 if (LangOpts.OpenCL) 144 createOpenCLRuntime(); 145 if (LangOpts.OpenMP) 146 createOpenMPRuntime(); 147 if (LangOpts.CUDA) 148 createCUDARuntime(); 149 if (LangOpts.HLSL) 150 createHLSLRuntime(); 151 152 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 153 if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 154 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 155 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 156 getCXXABI().getMangleContext())); 157 158 // If debug info or coverage generation is enabled, create the CGDebugInfo 159 // object. 160 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 161 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 162 DebugInfo.reset(new CGDebugInfo(*this)); 163 164 Block.GlobalUniqueCount = 0; 165 166 if (C.getLangOpts().ObjC) 167 ObjCData.reset(new ObjCEntrypoints()); 168 169 if (CodeGenOpts.hasProfileClangUse()) { 170 auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 171 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile); 172 if (auto E = ReaderOrErr.takeError()) { 173 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 174 "Could not read profile %0: %1"); 175 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 176 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 177 << EI.message(); 178 }); 179 } else 180 PGOReader = std::move(ReaderOrErr.get()); 181 } 182 183 // If coverage mapping generation is enabled, create the 184 // CoverageMappingModuleGen object. 185 if (CodeGenOpts.CoverageMapping) 186 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 187 188 // Generate the module name hash here if needed. 189 if (CodeGenOpts.UniqueInternalLinkageNames && 190 !getModule().getSourceFileName().empty()) { 191 std::string Path = getModule().getSourceFileName(); 192 // Check if a path substitution is needed from the MacroPrefixMap. 193 for (const auto &Entry : LangOpts.MacroPrefixMap) 194 if (Path.rfind(Entry.first, 0) != std::string::npos) { 195 Path = Entry.second + Path.substr(Entry.first.size()); 196 break; 197 } 198 llvm::MD5 Md5; 199 Md5.update(Path); 200 llvm::MD5::MD5Result R; 201 Md5.final(R); 202 SmallString<32> Str; 203 llvm::MD5::stringifyResult(R, Str); 204 // Convert MD5hash to Decimal. Demangler suffixes can either contain 205 // numbers or characters but not both. 206 llvm::APInt IntHash(128, Str.str(), 16); 207 // Prepend "__uniq" before the hash for tools like profilers to understand 208 // that this symbol is of internal linkage type. The "__uniq" is the 209 // pre-determined prefix that is used to tell tools that this symbol was 210 // created with -funique-internal-linakge-symbols and the tools can strip or 211 // keep the prefix as needed. 212 ModuleNameHash = (Twine(".__uniq.") + 213 Twine(toString(IntHash, /* Radix = */ 10, /* Signed = */false))).str(); 214 } 215 } 216 217 CodeGenModule::~CodeGenModule() {} 218 219 void CodeGenModule::createObjCRuntime() { 220 // This is just isGNUFamily(), but we want to force implementors of 221 // new ABIs to decide how best to do this. 222 switch (LangOpts.ObjCRuntime.getKind()) { 223 case ObjCRuntime::GNUstep: 224 case ObjCRuntime::GCC: 225 case ObjCRuntime::ObjFW: 226 ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 227 return; 228 229 case ObjCRuntime::FragileMacOSX: 230 case ObjCRuntime::MacOSX: 231 case ObjCRuntime::iOS: 232 case ObjCRuntime::WatchOS: 233 ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 234 return; 235 } 236 llvm_unreachable("bad runtime kind"); 237 } 238 239 void CodeGenModule::createOpenCLRuntime() { 240 OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 241 } 242 243 void CodeGenModule::createOpenMPRuntime() { 244 // Select a specialized code generation class based on the target, if any. 245 // If it does not exist use the default implementation. 246 switch (getTriple().getArch()) { 247 case llvm::Triple::nvptx: 248 case llvm::Triple::nvptx64: 249 case llvm::Triple::amdgcn: 250 assert(getLangOpts().OpenMPIsDevice && 251 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); 252 OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this)); 253 break; 254 default: 255 if (LangOpts.OpenMPSimd) 256 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 257 else 258 OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 259 break; 260 } 261 } 262 263 void CodeGenModule::createCUDARuntime() { 264 CUDARuntime.reset(CreateNVCUDARuntime(*this)); 265 } 266 267 void CodeGenModule::createHLSLRuntime() { 268 HLSLRuntime.reset(new CGHLSLRuntime(*this)); 269 } 270 271 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 272 Replacements[Name] = C; 273 } 274 275 void CodeGenModule::applyReplacements() { 276 for (auto &I : Replacements) { 277 StringRef MangledName = I.first(); 278 llvm::Constant *Replacement = I.second; 279 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 280 if (!Entry) 281 continue; 282 auto *OldF = cast<llvm::Function>(Entry); 283 auto *NewF = dyn_cast<llvm::Function>(Replacement); 284 if (!NewF) { 285 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 286 NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 287 } else { 288 auto *CE = cast<llvm::ConstantExpr>(Replacement); 289 assert(CE->getOpcode() == llvm::Instruction::BitCast || 290 CE->getOpcode() == llvm::Instruction::GetElementPtr); 291 NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 292 } 293 } 294 295 // Replace old with new, but keep the old order. 296 OldF->replaceAllUsesWith(Replacement); 297 if (NewF) { 298 NewF->removeFromParent(); 299 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 300 NewF); 301 } 302 OldF->eraseFromParent(); 303 } 304 } 305 306 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 307 GlobalValReplacements.push_back(std::make_pair(GV, C)); 308 } 309 310 void CodeGenModule::applyGlobalValReplacements() { 311 for (auto &I : GlobalValReplacements) { 312 llvm::GlobalValue *GV = I.first; 313 llvm::Constant *C = I.second; 314 315 GV->replaceAllUsesWith(C); 316 GV->eraseFromParent(); 317 } 318 } 319 320 // This is only used in aliases that we created and we know they have a 321 // linear structure. 322 static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) { 323 const llvm::Constant *C; 324 if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV)) 325 C = GA->getAliasee(); 326 else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV)) 327 C = GI->getResolver(); 328 else 329 return GV; 330 331 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts()); 332 if (!AliaseeGV) 333 return nullptr; 334 335 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); 336 if (FinalGV == GV) 337 return nullptr; 338 339 return FinalGV; 340 } 341 342 static bool checkAliasedGlobal(DiagnosticsEngine &Diags, 343 SourceLocation Location, bool IsIFunc, 344 const llvm::GlobalValue *Alias, 345 const llvm::GlobalValue *&GV) { 346 GV = getAliasedGlobal(Alias); 347 if (!GV) { 348 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 349 return false; 350 } 351 352 if (GV->isDeclaration()) { 353 Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc; 354 return false; 355 } 356 357 if (IsIFunc) { 358 // Check resolver function type. 359 const auto *F = dyn_cast<llvm::Function>(GV); 360 if (!F) { 361 Diags.Report(Location, diag::err_alias_to_undefined) 362 << IsIFunc << IsIFunc; 363 return false; 364 } 365 366 llvm::FunctionType *FTy = F->getFunctionType(); 367 if (!FTy->getReturnType()->isPointerTy()) { 368 Diags.Report(Location, diag::err_ifunc_resolver_return); 369 return false; 370 } 371 } 372 373 return true; 374 } 375 376 void CodeGenModule::checkAliases() { 377 // Check if the constructed aliases are well formed. It is really unfortunate 378 // that we have to do this in CodeGen, but we only construct mangled names 379 // and aliases during codegen. 380 bool Error = false; 381 DiagnosticsEngine &Diags = getDiags(); 382 for (const GlobalDecl &GD : Aliases) { 383 const auto *D = cast<ValueDecl>(GD.getDecl()); 384 SourceLocation Location; 385 bool IsIFunc = D->hasAttr<IFuncAttr>(); 386 if (const Attr *A = D->getDefiningAttr()) 387 Location = A->getLocation(); 388 else 389 llvm_unreachable("Not an alias or ifunc?"); 390 391 StringRef MangledName = getMangledName(GD); 392 llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 393 const llvm::GlobalValue *GV = nullptr; 394 if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV)) { 395 Error = true; 396 continue; 397 } 398 399 llvm::Constant *Aliasee = 400 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver() 401 : cast<llvm::GlobalAlias>(Alias)->getAliasee(); 402 403 llvm::GlobalValue *AliaseeGV; 404 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 405 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 406 else 407 AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 408 409 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 410 StringRef AliasSection = SA->getName(); 411 if (AliasSection != AliaseeGV->getSection()) 412 Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 413 << AliasSection << IsIFunc << IsIFunc; 414 } 415 416 // We have to handle alias to weak aliases in here. LLVM itself disallows 417 // this since the object semantics would not match the IL one. For 418 // compatibility with gcc we implement it by just pointing the alias 419 // to its aliasee's aliasee. We also warn, since the user is probably 420 // expecting the link to be weak. 421 if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 422 if (GA->isInterposable()) { 423 Diags.Report(Location, diag::warn_alias_to_weak_alias) 424 << GV->getName() << GA->getName() << IsIFunc; 425 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 426 GA->getAliasee(), Alias->getType()); 427 428 if (IsIFunc) 429 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee); 430 else 431 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee); 432 } 433 } 434 } 435 if (!Error) 436 return; 437 438 for (const GlobalDecl &GD : Aliases) { 439 StringRef MangledName = getMangledName(GD); 440 llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 441 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 442 Alias->eraseFromParent(); 443 } 444 } 445 446 void CodeGenModule::clear() { 447 DeferredDeclsToEmit.clear(); 448 if (OpenMPRuntime) 449 OpenMPRuntime->clear(); 450 } 451 452 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 453 StringRef MainFile) { 454 if (!hasDiagnostics()) 455 return; 456 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 457 if (MainFile.empty()) 458 MainFile = "<stdin>"; 459 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 460 } else { 461 if (Mismatched > 0) 462 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 463 464 if (Missing > 0) 465 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 466 } 467 } 468 469 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, 470 llvm::Module &M) { 471 if (!LO.VisibilityFromDLLStorageClass) 472 return; 473 474 llvm::GlobalValue::VisibilityTypes DLLExportVisibility = 475 CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility()); 476 llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility = 477 CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility()); 478 llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility = 479 CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility()); 480 llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility = 481 CodeGenModule::GetLLVMVisibility( 482 LO.getExternDeclNoDLLStorageClassVisibility()); 483 484 for (llvm::GlobalValue &GV : M.global_values()) { 485 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) 486 continue; 487 488 // Reset DSO locality before setting the visibility. This removes 489 // any effects that visibility options and annotations may have 490 // had on the DSO locality. Setting the visibility will implicitly set 491 // appropriate globals to DSO Local; however, this will be pessimistic 492 // w.r.t. to the normal compiler IRGen. 493 GV.setDSOLocal(false); 494 495 if (GV.isDeclarationForLinker()) { 496 GV.setVisibility(GV.getDLLStorageClass() == 497 llvm::GlobalValue::DLLImportStorageClass 498 ? ExternDeclDLLImportVisibility 499 : ExternDeclNoDLLStorageClassVisibility); 500 } else { 501 GV.setVisibility(GV.getDLLStorageClass() == 502 llvm::GlobalValue::DLLExportStorageClass 503 ? DLLExportVisibility 504 : NoDLLStorageClassVisibility); 505 } 506 507 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 508 } 509 } 510 511 void CodeGenModule::Release() { 512 EmitDeferred(); 513 EmitVTablesOpportunistically(); 514 applyGlobalValReplacements(); 515 applyReplacements(); 516 emitMultiVersionFunctions(); 517 EmitCXXGlobalInitFunc(); 518 EmitCXXGlobalCleanUpFunc(); 519 registerGlobalDtorsWithAtExit(); 520 EmitCXXThreadLocalInitFunc(); 521 if (ObjCRuntime) 522 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 523 AddGlobalCtor(ObjCInitFunction); 524 if (Context.getLangOpts().CUDA && CUDARuntime) { 525 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) 526 AddGlobalCtor(CudaCtorFunction); 527 } 528 if (OpenMPRuntime) { 529 if (llvm::Function *OpenMPRequiresDirectiveRegFun = 530 OpenMPRuntime->emitRequiresDirectiveRegFun()) { 531 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); 532 } 533 OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 534 OpenMPRuntime->clear(); 535 } 536 if (PGOReader) { 537 getModule().setProfileSummary( 538 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 539 llvm::ProfileSummary::PSK_Instr); 540 if (PGOStats.hasDiagnostics()) 541 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 542 } 543 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 544 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 545 EmitGlobalAnnotations(); 546 EmitStaticExternCAliases(); 547 checkAliases(); 548 EmitDeferredUnusedCoverageMappings(); 549 CodeGenPGO(*this).setValueProfilingFlag(getModule()); 550 if (CoverageMapping) 551 CoverageMapping->emit(); 552 if (CodeGenOpts.SanitizeCfiCrossDso) { 553 CodeGenFunction(*this).EmitCfiCheckFail(); 554 CodeGenFunction(*this).EmitCfiCheckStub(); 555 } 556 emitAtAvailableLinkGuard(); 557 if (Context.getTargetInfo().getTriple().isWasm()) 558 EmitMainVoidAlias(); 559 560 if (getTriple().isAMDGPU()) { 561 // Emit reference of __amdgpu_device_library_preserve_asan_functions to 562 // preserve ASAN functions in bitcode libraries. 563 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 564 auto *FT = llvm::FunctionType::get(VoidTy, {}); 565 auto *F = llvm::Function::Create( 566 FT, llvm::GlobalValue::ExternalLinkage, 567 "__amdgpu_device_library_preserve_asan_functions", &getModule()); 568 auto *Var = new llvm::GlobalVariable( 569 getModule(), FT->getPointerTo(), 570 /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F, 571 "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr, 572 llvm::GlobalVariable::NotThreadLocal); 573 addCompilerUsedGlobal(Var); 574 } 575 // Emit amdgpu_code_object_version module flag, which is code object version 576 // times 100. 577 // ToDo: Enable module flag for all code object version when ROCm device 578 // library is ready. 579 if (getTarget().getTargetOpts().CodeObjectVersion == TargetOptions::COV_5) { 580 getModule().addModuleFlag(llvm::Module::Error, 581 "amdgpu_code_object_version", 582 getTarget().getTargetOpts().CodeObjectVersion); 583 } 584 } 585 586 // Emit a global array containing all external kernels or device variables 587 // used by host functions and mark it as used for CUDA/HIP. This is necessary 588 // to get kernels or device variables in archives linked in even if these 589 // kernels or device variables are only used in host functions. 590 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) { 591 SmallVector<llvm::Constant *, 8> UsedArray; 592 for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) { 593 GlobalDecl GD; 594 if (auto *FD = dyn_cast<FunctionDecl>(D)) 595 GD = GlobalDecl(FD, KernelReferenceKind::Kernel); 596 else 597 GD = GlobalDecl(D); 598 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 599 GetAddrOfGlobal(GD), Int8PtrTy)); 600 } 601 602 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size()); 603 604 auto *GV = new llvm::GlobalVariable( 605 getModule(), ATy, false, llvm::GlobalValue::InternalLinkage, 606 llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external"); 607 addCompilerUsedGlobal(GV); 608 } 609 610 emitLLVMUsed(); 611 if (SanStats) 612 SanStats->finish(); 613 614 if (CodeGenOpts.Autolink && 615 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 616 EmitModuleLinkOptions(); 617 } 618 619 // On ELF we pass the dependent library specifiers directly to the linker 620 // without manipulating them. This is in contrast to other platforms where 621 // they are mapped to a specific linker option by the compiler. This 622 // difference is a result of the greater variety of ELF linkers and the fact 623 // that ELF linkers tend to handle libraries in a more complicated fashion 624 // than on other platforms. This forces us to defer handling the dependent 625 // libs to the linker. 626 // 627 // CUDA/HIP device and host libraries are different. Currently there is no 628 // way to differentiate dependent libraries for host or device. Existing 629 // usage of #pragma comment(lib, *) is intended for host libraries on 630 // Windows. Therefore emit llvm.dependent-libraries only for host. 631 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 632 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 633 for (auto *MD : ELFDependentLibraries) 634 NMD->addOperand(MD); 635 } 636 637 // Record mregparm value now so it is visible through rest of codegen. 638 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 639 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 640 CodeGenOpts.NumRegisterParameters); 641 642 if (CodeGenOpts.DwarfVersion) { 643 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", 644 CodeGenOpts.DwarfVersion); 645 } 646 647 if (CodeGenOpts.Dwarf64) 648 getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1); 649 650 if (Context.getLangOpts().SemanticInterposition) 651 // Require various optimization to respect semantic interposition. 652 getModule().setSemanticInterposition(true); 653 654 if (CodeGenOpts.EmitCodeView) { 655 // Indicate that we want CodeView in the metadata. 656 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 657 } 658 if (CodeGenOpts.CodeViewGHash) { 659 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 660 } 661 if (CodeGenOpts.ControlFlowGuard) { 662 // Function ID tables and checks for Control Flow Guard (cfguard=2). 663 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); 664 } else if (CodeGenOpts.ControlFlowGuardNoChecks) { 665 // Function ID tables for Control Flow Guard (cfguard=1). 666 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); 667 } 668 if (CodeGenOpts.EHContGuard) { 669 // Function ID tables for EH Continuation Guard. 670 getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1); 671 } 672 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 673 // We don't support LTO with 2 with different StrictVTablePointers 674 // FIXME: we could support it by stripping all the information introduced 675 // by StrictVTablePointers. 676 677 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 678 679 llvm::Metadata *Ops[2] = { 680 llvm::MDString::get(VMContext, "StrictVTablePointers"), 681 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 682 llvm::Type::getInt32Ty(VMContext), 1))}; 683 684 getModule().addModuleFlag(llvm::Module::Require, 685 "StrictVTablePointersRequirement", 686 llvm::MDNode::get(VMContext, Ops)); 687 } 688 if (getModuleDebugInfo()) 689 // We support a single version in the linked module. The LLVM 690 // parser will drop debug info with a different version number 691 // (and warn about it, too). 692 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 693 llvm::DEBUG_METADATA_VERSION); 694 695 // We need to record the widths of enums and wchar_t, so that we can generate 696 // the correct build attributes in the ARM backend. wchar_size is also used by 697 // TargetLibraryInfo. 698 uint64_t WCharWidth = 699 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 700 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 701 702 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 703 if ( Arch == llvm::Triple::arm 704 || Arch == llvm::Triple::armeb 705 || Arch == llvm::Triple::thumb 706 || Arch == llvm::Triple::thumbeb) { 707 // The minimum width of an enum in bytes 708 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 709 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 710 } 711 712 if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) { 713 StringRef ABIStr = Target.getABI(); 714 llvm::LLVMContext &Ctx = TheModule.getContext(); 715 getModule().addModuleFlag(llvm::Module::Error, "target-abi", 716 llvm::MDString::get(Ctx, ABIStr)); 717 } 718 719 if (CodeGenOpts.SanitizeCfiCrossDso) { 720 // Indicate that we want cross-DSO control flow integrity checks. 721 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 722 } 723 724 if (CodeGenOpts.WholeProgramVTables) { 725 // Indicate whether VFE was enabled for this module, so that the 726 // vcall_visibility metadata added under whole program vtables is handled 727 // appropriately in the optimizer. 728 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim", 729 CodeGenOpts.VirtualFunctionElimination); 730 } 731 732 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { 733 getModule().addModuleFlag(llvm::Module::Override, 734 "CFI Canonical Jump Tables", 735 CodeGenOpts.SanitizeCfiCanonicalJumpTables); 736 } 737 738 if (CodeGenOpts.CFProtectionReturn && 739 Target.checkCFProtectionReturnSupported(getDiags())) { 740 // Indicate that we want to instrument return control flow protection. 741 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return", 742 1); 743 } 744 745 if (CodeGenOpts.CFProtectionBranch && 746 Target.checkCFProtectionBranchSupported(getDiags())) { 747 // Indicate that we want to instrument branch control flow protection. 748 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch", 749 1); 750 } 751 752 if (CodeGenOpts.IBTSeal) 753 getModule().addModuleFlag(llvm::Module::Override, "ibt-seal", 1); 754 755 // Add module metadata for return address signing (ignoring 756 // non-leaf/all) and stack tagging. These are actually turned on by function 757 // attributes, but we use module metadata to emit build attributes. This is 758 // needed for LTO, where the function attributes are inside bitcode 759 // serialised into a global variable by the time build attributes are 760 // emitted, so we can't access them. LTO objects could be compiled with 761 // different flags therefore module flags are set to "Min" behavior to achieve 762 // the same end result of the normal build where e.g BTI is off if any object 763 // doesn't support it. 764 if (Context.getTargetInfo().hasFeature("ptrauth") && 765 LangOpts.getSignReturnAddressScope() != 766 LangOptions::SignReturnAddressScopeKind::None) 767 getModule().addModuleFlag(llvm::Module::Override, 768 "sign-return-address-buildattr", 1); 769 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack)) 770 getModule().addModuleFlag(llvm::Module::Override, 771 "tag-stack-memory-buildattr", 1); 772 773 if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb || 774 Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb || 775 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 || 776 Arch == llvm::Triple::aarch64_be) { 777 getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement", 778 LangOpts.BranchTargetEnforcement); 779 780 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 781 LangOpts.hasSignReturnAddress()); 782 783 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all", 784 LangOpts.isSignReturnAddressScopeAll()); 785 786 getModule().addModuleFlag(llvm::Module::Min, 787 "sign-return-address-with-bkey", 788 !LangOpts.isSignReturnAddressWithAKey()); 789 } 790 791 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 792 llvm::LLVMContext &Ctx = TheModule.getContext(); 793 getModule().addModuleFlag( 794 llvm::Module::Error, "MemProfProfileFilename", 795 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput)); 796 } 797 798 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 799 // Indicate whether __nvvm_reflect should be configured to flush denormal 800 // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 801 // property.) 802 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 803 CodeGenOpts.FP32DenormalMode.Output != 804 llvm::DenormalMode::IEEE); 805 } 806 807 if (LangOpts.EHAsynch) 808 getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1); 809 810 // Indicate whether this Module was compiled with -fopenmp 811 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 812 getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP); 813 if (getLangOpts().OpenMPIsDevice) 814 getModule().addModuleFlag(llvm::Module::Max, "openmp-device", 815 LangOpts.OpenMP); 816 817 // Emit OpenCL specific module metadata: OpenCL/SPIR version. 818 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) { 819 EmitOpenCLMetadata(); 820 // Emit SPIR version. 821 if (getTriple().isSPIR()) { 822 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 823 // opencl.spir.version named metadata. 824 // C++ for OpenCL has a distinct mapping for version compatibility with 825 // OpenCL. 826 auto Version = LangOpts.getOpenCLCompatibleVersion(); 827 llvm::Metadata *SPIRVerElts[] = { 828 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 829 Int32Ty, Version / 100)), 830 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 831 Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 832 llvm::NamedMDNode *SPIRVerMD = 833 TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 834 llvm::LLVMContext &Ctx = TheModule.getContext(); 835 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 836 } 837 } 838 839 // HLSL related end of code gen work items. 840 if (LangOpts.HLSL) 841 getHLSLRuntime().finishCodeGen(); 842 843 if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 844 assert(PLevel < 3 && "Invalid PIC Level"); 845 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 846 if (Context.getLangOpts().PIE) 847 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 848 } 849 850 if (getCodeGenOpts().CodeModel.size() > 0) { 851 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 852 .Case("tiny", llvm::CodeModel::Tiny) 853 .Case("small", llvm::CodeModel::Small) 854 .Case("kernel", llvm::CodeModel::Kernel) 855 .Case("medium", llvm::CodeModel::Medium) 856 .Case("large", llvm::CodeModel::Large) 857 .Default(~0u); 858 if (CM != ~0u) { 859 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 860 getModule().setCodeModel(codeModel); 861 } 862 } 863 864 if (CodeGenOpts.NoPLT) 865 getModule().setRtLibUseGOT(); 866 if (CodeGenOpts.UnwindTables) 867 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 868 869 switch (CodeGenOpts.getFramePointer()) { 870 case CodeGenOptions::FramePointerKind::None: 871 // 0 ("none") is the default. 872 break; 873 case CodeGenOptions::FramePointerKind::NonLeaf: 874 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); 875 break; 876 case CodeGenOptions::FramePointerKind::All: 877 getModule().setFramePointer(llvm::FramePointerKind::All); 878 break; 879 } 880 881 SimplifyPersonality(); 882 883 if (getCodeGenOpts().EmitDeclMetadata) 884 EmitDeclMetadata(); 885 886 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 887 EmitCoverageFile(); 888 889 if (CGDebugInfo *DI = getModuleDebugInfo()) 890 DI->finalize(); 891 892 if (getCodeGenOpts().EmitVersionIdentMetadata) 893 EmitVersionIdentMetadata(); 894 895 if (!getCodeGenOpts().RecordCommandLine.empty()) 896 EmitCommandLineMetadata(); 897 898 if (!getCodeGenOpts().StackProtectorGuard.empty()) 899 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); 900 if (!getCodeGenOpts().StackProtectorGuardReg.empty()) 901 getModule().setStackProtectorGuardReg( 902 getCodeGenOpts().StackProtectorGuardReg); 903 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) 904 getModule().setStackProtectorGuardOffset( 905 getCodeGenOpts().StackProtectorGuardOffset); 906 if (getCodeGenOpts().StackAlignment) 907 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); 908 if (getCodeGenOpts().SkipRaxSetup) 909 getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1); 910 911 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames); 912 913 EmitBackendOptionsMetadata(getCodeGenOpts()); 914 915 // If there is device offloading code embed it in the host now. 916 EmbedObject(&getModule(), CodeGenOpts, getDiags()); 917 918 // Set visibility from DLL storage class 919 // We do this at the end of LLVM IR generation; after any operation 920 // that might affect the DLL storage class or the visibility, and 921 // before anything that might act on these. 922 setVisibilityFromDLLStorageClass(LangOpts, getModule()); 923 } 924 925 void CodeGenModule::EmitOpenCLMetadata() { 926 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 927 // opencl.ocl.version named metadata node. 928 // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL. 929 auto Version = LangOpts.getOpenCLCompatibleVersion(); 930 llvm::Metadata *OCLVerElts[] = { 931 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 932 Int32Ty, Version / 100)), 933 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 934 Int32Ty, (Version % 100) / 10))}; 935 llvm::NamedMDNode *OCLVerMD = 936 TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 937 llvm::LLVMContext &Ctx = TheModule.getContext(); 938 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 939 } 940 941 void CodeGenModule::EmitBackendOptionsMetadata( 942 const CodeGenOptions CodeGenOpts) { 943 switch (getTriple().getArch()) { 944 default: 945 break; 946 case llvm::Triple::riscv32: 947 case llvm::Triple::riscv64: 948 getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit", 949 CodeGenOpts.SmallDataLimit); 950 break; 951 } 952 } 953 954 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 955 // Make sure that this type is translated. 956 Types.UpdateCompletedType(TD); 957 } 958 959 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 960 // Make sure that this type is translated. 961 Types.RefreshTypeCacheForClass(RD); 962 } 963 964 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 965 if (!TBAA) 966 return nullptr; 967 return TBAA->getTypeInfo(QTy); 968 } 969 970 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 971 if (!TBAA) 972 return TBAAAccessInfo(); 973 if (getLangOpts().CUDAIsDevice) { 974 // As CUDA builtin surface/texture types are replaced, skip generating TBAA 975 // access info. 976 if (AccessType->isCUDADeviceBuiltinSurfaceType()) { 977 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != 978 nullptr) 979 return TBAAAccessInfo(); 980 } else if (AccessType->isCUDADeviceBuiltinTextureType()) { 981 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != 982 nullptr) 983 return TBAAAccessInfo(); 984 } 985 } 986 return TBAA->getAccessInfo(AccessType); 987 } 988 989 TBAAAccessInfo 990 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 991 if (!TBAA) 992 return TBAAAccessInfo(); 993 return TBAA->getVTablePtrAccessInfo(VTablePtrType); 994 } 995 996 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 997 if (!TBAA) 998 return nullptr; 999 return TBAA->getTBAAStructInfo(QTy); 1000 } 1001 1002 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 1003 if (!TBAA) 1004 return nullptr; 1005 return TBAA->getBaseTypeInfo(QTy); 1006 } 1007 1008 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 1009 if (!TBAA) 1010 return nullptr; 1011 return TBAA->getAccessTagInfo(Info); 1012 } 1013 1014 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 1015 TBAAAccessInfo TargetInfo) { 1016 if (!TBAA) 1017 return TBAAAccessInfo(); 1018 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 1019 } 1020 1021 TBAAAccessInfo 1022 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 1023 TBAAAccessInfo InfoB) { 1024 if (!TBAA) 1025 return TBAAAccessInfo(); 1026 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 1027 } 1028 1029 TBAAAccessInfo 1030 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 1031 TBAAAccessInfo SrcInfo) { 1032 if (!TBAA) 1033 return TBAAAccessInfo(); 1034 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 1035 } 1036 1037 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 1038 TBAAAccessInfo TBAAInfo) { 1039 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 1040 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 1041 } 1042 1043 void CodeGenModule::DecorateInstructionWithInvariantGroup( 1044 llvm::Instruction *I, const CXXRecordDecl *RD) { 1045 I->setMetadata(llvm::LLVMContext::MD_invariant_group, 1046 llvm::MDNode::get(getLLVMContext(), {})); 1047 } 1048 1049 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 1050 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1051 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 1052 } 1053 1054 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1055 /// specified stmt yet. 1056 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 1057 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1058 "cannot compile this %0 yet"); 1059 std::string Msg = Type; 1060 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 1061 << Msg << S->getSourceRange(); 1062 } 1063 1064 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1065 /// specified decl yet. 1066 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 1067 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1068 "cannot compile this %0 yet"); 1069 std::string Msg = Type; 1070 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 1071 } 1072 1073 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 1074 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 1075 } 1076 1077 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 1078 const NamedDecl *D) const { 1079 if (GV->hasDLLImportStorageClass()) 1080 return; 1081 // Internal definitions always have default visibility. 1082 if (GV->hasLocalLinkage()) { 1083 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1084 return; 1085 } 1086 if (!D) 1087 return; 1088 // Set visibility for definitions, and for declarations if requested globally 1089 // or set explicitly. 1090 LinkageInfo LV = D->getLinkageAndVisibility(); 1091 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 1092 !GV->isDeclarationForLinker()) 1093 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 1094 } 1095 1096 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 1097 llvm::GlobalValue *GV) { 1098 if (GV->hasLocalLinkage()) 1099 return true; 1100 1101 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 1102 return true; 1103 1104 // DLLImport explicitly marks the GV as external. 1105 if (GV->hasDLLImportStorageClass()) 1106 return false; 1107 1108 const llvm::Triple &TT = CGM.getTriple(); 1109 if (TT.isWindowsGNUEnvironment()) { 1110 // In MinGW, variables without DLLImport can still be automatically 1111 // imported from a DLL by the linker; don't mark variables that 1112 // potentially could come from another DLL as DSO local. 1113 1114 // With EmulatedTLS, TLS variables can be autoimported from other DLLs 1115 // (and this actually happens in the public interface of libstdc++), so 1116 // such variables can't be marked as DSO local. (Native TLS variables 1117 // can't be dllimported at all, though.) 1118 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 1119 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS)) 1120 return false; 1121 } 1122 1123 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 1124 // remain unresolved in the link, they can be resolved to zero, which is 1125 // outside the current DSO. 1126 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 1127 return false; 1128 1129 // Every other GV is local on COFF. 1130 // Make an exception for windows OS in the triple: Some firmware builds use 1131 // *-win32-macho triples. This (accidentally?) produced windows relocations 1132 // without GOT tables in older clang versions; Keep this behaviour. 1133 // FIXME: even thread local variables? 1134 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 1135 return true; 1136 1137 // Only handle COFF and ELF for now. 1138 if (!TT.isOSBinFormatELF()) 1139 return false; 1140 1141 // If this is not an executable, don't assume anything is local. 1142 const auto &CGOpts = CGM.getCodeGenOpts(); 1143 llvm::Reloc::Model RM = CGOpts.RelocationModel; 1144 const auto &LOpts = CGM.getLangOpts(); 1145 if (RM != llvm::Reloc::Static && !LOpts.PIE) { 1146 // On ELF, if -fno-semantic-interposition is specified and the target 1147 // supports local aliases, there will be neither CC1 1148 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set 1149 // dso_local on the function if using a local alias is preferable (can avoid 1150 // PLT indirection). 1151 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias())) 1152 return false; 1153 return !(CGM.getLangOpts().SemanticInterposition || 1154 CGM.getLangOpts().HalfNoSemanticInterposition); 1155 } 1156 1157 // A definition cannot be preempted from an executable. 1158 if (!GV->isDeclarationForLinker()) 1159 return true; 1160 1161 // Most PIC code sequences that assume that a symbol is local cannot produce a 1162 // 0 if it turns out the symbol is undefined. While this is ABI and relocation 1163 // depended, it seems worth it to handle it here. 1164 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 1165 return false; 1166 1167 // PowerPC64 prefers TOC indirection to avoid copy relocations. 1168 if (TT.isPPC64()) 1169 return false; 1170 1171 if (CGOpts.DirectAccessExternalData) { 1172 // If -fdirect-access-external-data (default for -fno-pic), set dso_local 1173 // for non-thread-local variables. If the symbol is not defined in the 1174 // executable, a copy relocation will be needed at link time. dso_local is 1175 // excluded for thread-local variables because they generally don't support 1176 // copy relocations. 1177 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 1178 if (!Var->isThreadLocal()) 1179 return true; 1180 1181 // -fno-pic sets dso_local on a function declaration to allow direct 1182 // accesses when taking its address (similar to a data symbol). If the 1183 // function is not defined in the executable, a canonical PLT entry will be 1184 // needed at link time. -fno-direct-access-external-data can avoid the 1185 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as 1186 // it could just cause trouble without providing perceptible benefits. 1187 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 1188 return true; 1189 } 1190 1191 // If we can use copy relocations we can assume it is local. 1192 1193 // Otherwise don't assume it is local. 1194 return false; 1195 } 1196 1197 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 1198 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 1199 } 1200 1201 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1202 GlobalDecl GD) const { 1203 const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 1204 // C++ destructors have a few C++ ABI specific special cases. 1205 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 1206 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 1207 return; 1208 } 1209 setDLLImportDLLExport(GV, D); 1210 } 1211 1212 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1213 const NamedDecl *D) const { 1214 if (D && D->isExternallyVisible()) { 1215 if (D->hasAttr<DLLImportAttr>()) 1216 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1217 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker()) 1218 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1219 } 1220 } 1221 1222 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1223 GlobalDecl GD) const { 1224 setDLLImportDLLExport(GV, GD); 1225 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 1226 } 1227 1228 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1229 const NamedDecl *D) const { 1230 setDLLImportDLLExport(GV, D); 1231 setGVPropertiesAux(GV, D); 1232 } 1233 1234 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 1235 const NamedDecl *D) const { 1236 setGlobalVisibility(GV, D); 1237 setDSOLocal(GV); 1238 GV->setPartition(CodeGenOpts.SymbolPartition); 1239 } 1240 1241 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 1242 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 1243 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 1244 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 1245 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 1246 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 1247 } 1248 1249 llvm::GlobalVariable::ThreadLocalMode 1250 CodeGenModule::GetDefaultLLVMTLSModel() const { 1251 switch (CodeGenOpts.getDefaultTLSModel()) { 1252 case CodeGenOptions::GeneralDynamicTLSModel: 1253 return llvm::GlobalVariable::GeneralDynamicTLSModel; 1254 case CodeGenOptions::LocalDynamicTLSModel: 1255 return llvm::GlobalVariable::LocalDynamicTLSModel; 1256 case CodeGenOptions::InitialExecTLSModel: 1257 return llvm::GlobalVariable::InitialExecTLSModel; 1258 case CodeGenOptions::LocalExecTLSModel: 1259 return llvm::GlobalVariable::LocalExecTLSModel; 1260 } 1261 llvm_unreachable("Invalid TLS model!"); 1262 } 1263 1264 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 1265 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 1266 1267 llvm::GlobalValue::ThreadLocalMode TLM; 1268 TLM = GetDefaultLLVMTLSModel(); 1269 1270 // Override the TLS model if it is explicitly specified. 1271 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 1272 TLM = GetLLVMTLSModel(Attr->getModel()); 1273 } 1274 1275 GV->setThreadLocalMode(TLM); 1276 } 1277 1278 static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 1279 StringRef Name) { 1280 const TargetInfo &Target = CGM.getTarget(); 1281 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 1282 } 1283 1284 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 1285 const CPUSpecificAttr *Attr, 1286 unsigned CPUIndex, 1287 raw_ostream &Out) { 1288 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 1289 // supported. 1290 if (Attr) 1291 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 1292 else if (CGM.getTarget().supportsIFunc()) 1293 Out << ".resolver"; 1294 } 1295 1296 static void AppendTargetMangling(const CodeGenModule &CGM, 1297 const TargetAttr *Attr, raw_ostream &Out) { 1298 if (Attr->isDefaultVersion()) 1299 return; 1300 1301 Out << '.'; 1302 const TargetInfo &Target = CGM.getTarget(); 1303 ParsedTargetAttr Info = 1304 Attr->parse([&Target](StringRef LHS, StringRef RHS) { 1305 // Multiversioning doesn't allow "no-${feature}", so we can 1306 // only have "+" prefixes here. 1307 assert(LHS.startswith("+") && RHS.startswith("+") && 1308 "Features should always have a prefix."); 1309 return Target.multiVersionSortPriority(LHS.substr(1)) > 1310 Target.multiVersionSortPriority(RHS.substr(1)); 1311 }); 1312 1313 bool IsFirst = true; 1314 1315 if (!Info.Architecture.empty()) { 1316 IsFirst = false; 1317 Out << "arch_" << Info.Architecture; 1318 } 1319 1320 for (StringRef Feat : Info.Features) { 1321 if (!IsFirst) 1322 Out << '_'; 1323 IsFirst = false; 1324 Out << Feat.substr(1); 1325 } 1326 } 1327 1328 // Returns true if GD is a function decl with internal linkage and 1329 // needs a unique suffix after the mangled name. 1330 static bool isUniqueInternalLinkageDecl(GlobalDecl GD, 1331 CodeGenModule &CGM) { 1332 const Decl *D = GD.getDecl(); 1333 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) && 1334 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); 1335 } 1336 1337 static void AppendTargetClonesMangling(const CodeGenModule &CGM, 1338 const TargetClonesAttr *Attr, 1339 unsigned VersionIndex, 1340 raw_ostream &Out) { 1341 Out << '.'; 1342 StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 1343 if (FeatureStr.startswith("arch=")) 1344 Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1); 1345 else 1346 Out << FeatureStr; 1347 1348 Out << '.' << Attr->getMangledIndex(VersionIndex); 1349 } 1350 1351 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, 1352 const NamedDecl *ND, 1353 bool OmitMultiVersionMangling = false) { 1354 SmallString<256> Buffer; 1355 llvm::raw_svector_ostream Out(Buffer); 1356 MangleContext &MC = CGM.getCXXABI().getMangleContext(); 1357 if (!CGM.getModuleNameHash().empty()) 1358 MC.needsUniqueInternalLinkageNames(); 1359 bool ShouldMangle = MC.shouldMangleDeclName(ND); 1360 if (ShouldMangle) 1361 MC.mangleName(GD.getWithDecl(ND), Out); 1362 else { 1363 IdentifierInfo *II = ND->getIdentifier(); 1364 assert(II && "Attempt to mangle unnamed decl."); 1365 const auto *FD = dyn_cast<FunctionDecl>(ND); 1366 1367 if (FD && 1368 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 1369 Out << "__regcall3__" << II->getName(); 1370 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && 1371 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { 1372 Out << "__device_stub__" << II->getName(); 1373 } else { 1374 Out << II->getName(); 1375 } 1376 } 1377 1378 // Check if the module name hash should be appended for internal linkage 1379 // symbols. This should come before multi-version target suffixes are 1380 // appended. This is to keep the name and module hash suffix of the 1381 // internal linkage function together. The unique suffix should only be 1382 // added when name mangling is done to make sure that the final name can 1383 // be properly demangled. For example, for C functions without prototypes, 1384 // name mangling is not done and the unique suffix should not be appeneded 1385 // then. 1386 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { 1387 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && 1388 "Hash computed when not explicitly requested"); 1389 Out << CGM.getModuleNameHash(); 1390 } 1391 1392 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 1393 if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 1394 switch (FD->getMultiVersionKind()) { 1395 case MultiVersionKind::CPUDispatch: 1396 case MultiVersionKind::CPUSpecific: 1397 AppendCPUSpecificCPUDispatchMangling(CGM, 1398 FD->getAttr<CPUSpecificAttr>(), 1399 GD.getMultiVersionIndex(), Out); 1400 break; 1401 case MultiVersionKind::Target: 1402 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 1403 break; 1404 case MultiVersionKind::TargetClones: 1405 AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), 1406 GD.getMultiVersionIndex(), Out); 1407 break; 1408 case MultiVersionKind::None: 1409 llvm_unreachable("None multiversion type isn't valid here"); 1410 } 1411 } 1412 1413 // Make unique name for device side static file-scope variable for HIP. 1414 if (CGM.getContext().shouldExternalize(ND) && 1415 CGM.getLangOpts().GPURelocatableDeviceCode && 1416 CGM.getLangOpts().CUDAIsDevice) 1417 CGM.printPostfixForExternalizedDecl(Out, ND); 1418 1419 return std::string(Out.str()); 1420 } 1421 1422 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 1423 const FunctionDecl *FD, 1424 StringRef &CurName) { 1425 if (!FD->isMultiVersion()) 1426 return; 1427 1428 // Get the name of what this would be without the 'target' attribute. This 1429 // allows us to lookup the version that was emitted when this wasn't a 1430 // multiversion function. 1431 std::string NonTargetName = 1432 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 1433 GlobalDecl OtherGD; 1434 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 1435 assert(OtherGD.getCanonicalDecl() 1436 .getDecl() 1437 ->getAsFunction() 1438 ->isMultiVersion() && 1439 "Other GD should now be a multiversioned function"); 1440 // OtherFD is the version of this function that was mangled BEFORE 1441 // becoming a MultiVersion function. It potentially needs to be updated. 1442 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 1443 .getDecl() 1444 ->getAsFunction() 1445 ->getMostRecentDecl(); 1446 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 1447 // This is so that if the initial version was already the 'default' 1448 // version, we don't try to update it. 1449 if (OtherName != NonTargetName) { 1450 // Remove instead of erase, since others may have stored the StringRef 1451 // to this. 1452 const auto ExistingRecord = Manglings.find(NonTargetName); 1453 if (ExistingRecord != std::end(Manglings)) 1454 Manglings.remove(&(*ExistingRecord)); 1455 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 1456 StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] = 1457 Result.first->first(); 1458 // If this is the current decl is being created, make sure we update the name. 1459 if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl()) 1460 CurName = OtherNameRef; 1461 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 1462 Entry->setName(OtherName); 1463 } 1464 } 1465 } 1466 1467 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 1468 GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 1469 1470 // Some ABIs don't have constructor variants. Make sure that base and 1471 // complete constructors get mangled the same. 1472 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 1473 if (!getTarget().getCXXABI().hasConstructorVariants()) { 1474 CXXCtorType OrigCtorType = GD.getCtorType(); 1475 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 1476 if (OrigCtorType == Ctor_Base) 1477 CanonicalGD = GlobalDecl(CD, Ctor_Complete); 1478 } 1479 } 1480 1481 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a 1482 // static device variable depends on whether the variable is referenced by 1483 // a host or device host function. Therefore the mangled name cannot be 1484 // cached. 1485 if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) { 1486 auto FoundName = MangledDeclNames.find(CanonicalGD); 1487 if (FoundName != MangledDeclNames.end()) 1488 return FoundName->second; 1489 } 1490 1491 // Keep the first result in the case of a mangling collision. 1492 const auto *ND = cast<NamedDecl>(GD.getDecl()); 1493 std::string MangledName = getMangledNameImpl(*this, GD, ND); 1494 1495 // Ensure either we have different ABIs between host and device compilations, 1496 // says host compilation following MSVC ABI but device compilation follows 1497 // Itanium C++ ABI or, if they follow the same ABI, kernel names after 1498 // mangling should be the same after name stubbing. The later checking is 1499 // very important as the device kernel name being mangled in host-compilation 1500 // is used to resolve the device binaries to be executed. Inconsistent naming 1501 // result in undefined behavior. Even though we cannot check that naming 1502 // directly between host- and device-compilations, the host- and 1503 // device-mangling in host compilation could help catching certain ones. 1504 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || 1505 getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice || 1506 (getContext().getAuxTargetInfo() && 1507 (getContext().getAuxTargetInfo()->getCXXABI() != 1508 getContext().getTargetInfo().getCXXABI())) || 1509 getCUDARuntime().getDeviceSideName(ND) == 1510 getMangledNameImpl( 1511 *this, 1512 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), 1513 ND)); 1514 1515 auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 1516 return MangledDeclNames[CanonicalGD] = Result.first->first(); 1517 } 1518 1519 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 1520 const BlockDecl *BD) { 1521 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 1522 const Decl *D = GD.getDecl(); 1523 1524 SmallString<256> Buffer; 1525 llvm::raw_svector_ostream Out(Buffer); 1526 if (!D) 1527 MangleCtx.mangleGlobalBlock(BD, 1528 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 1529 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 1530 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 1531 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 1532 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 1533 else 1534 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 1535 1536 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 1537 return Result.first->first(); 1538 } 1539 1540 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) { 1541 auto it = MangledDeclNames.begin(); 1542 while (it != MangledDeclNames.end()) { 1543 if (it->second == Name) 1544 return it->first; 1545 it++; 1546 } 1547 return GlobalDecl(); 1548 } 1549 1550 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 1551 return getModule().getNamedValue(Name); 1552 } 1553 1554 /// AddGlobalCtor - Add a function to the list that will be called before 1555 /// main() runs. 1556 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 1557 llvm::Constant *AssociatedData) { 1558 // FIXME: Type coercion of void()* types. 1559 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 1560 } 1561 1562 /// AddGlobalDtor - Add a function to the list that will be called 1563 /// when the module is unloaded. 1564 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, 1565 bool IsDtorAttrFunc) { 1566 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && 1567 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { 1568 DtorsUsingAtExit[Priority].push_back(Dtor); 1569 return; 1570 } 1571 1572 // FIXME: Type coercion of void()* types. 1573 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 1574 } 1575 1576 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 1577 if (Fns.empty()) return; 1578 1579 // Ctor function type is void()*. 1580 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 1581 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 1582 TheModule.getDataLayout().getProgramAddressSpace()); 1583 1584 // Get the type of a ctor entry, { i32, void ()*, i8* }. 1585 llvm::StructType *CtorStructTy = llvm::StructType::get( 1586 Int32Ty, CtorPFTy, VoidPtrTy); 1587 1588 // Construct the constructor and destructor arrays. 1589 ConstantInitBuilder builder(*this); 1590 auto ctors = builder.beginArray(CtorStructTy); 1591 for (const auto &I : Fns) { 1592 auto ctor = ctors.beginStruct(CtorStructTy); 1593 ctor.addInt(Int32Ty, I.Priority); 1594 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 1595 if (I.AssociatedData) 1596 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 1597 else 1598 ctor.addNullPointer(VoidPtrTy); 1599 ctor.finishAndAddTo(ctors); 1600 } 1601 1602 auto list = 1603 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 1604 /*constant*/ false, 1605 llvm::GlobalValue::AppendingLinkage); 1606 1607 // The LTO linker doesn't seem to like it when we set an alignment 1608 // on appending variables. Take it off as a workaround. 1609 list->setAlignment(llvm::None); 1610 1611 Fns.clear(); 1612 } 1613 1614 llvm::GlobalValue::LinkageTypes 1615 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 1616 const auto *D = cast<FunctionDecl>(GD.getDecl()); 1617 1618 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 1619 1620 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 1621 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 1622 1623 if (isa<CXXConstructorDecl>(D) && 1624 cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 1625 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1626 // Our approach to inheriting constructors is fundamentally different from 1627 // that used by the MS ABI, so keep our inheriting constructor thunks 1628 // internal rather than trying to pick an unambiguous mangling for them. 1629 return llvm::GlobalValue::InternalLinkage; 1630 } 1631 1632 return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false); 1633 } 1634 1635 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 1636 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 1637 if (!MDS) return nullptr; 1638 1639 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 1640 } 1641 1642 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 1643 const CGFunctionInfo &Info, 1644 llvm::Function *F, bool IsThunk) { 1645 unsigned CallingConv; 1646 llvm::AttributeList PAL; 1647 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, 1648 /*AttrOnCallSite=*/false, IsThunk); 1649 F->setAttributes(PAL); 1650 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 1651 } 1652 1653 static void removeImageAccessQualifier(std::string& TyName) { 1654 std::string ReadOnlyQual("__read_only"); 1655 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 1656 if (ReadOnlyPos != std::string::npos) 1657 // "+ 1" for the space after access qualifier. 1658 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 1659 else { 1660 std::string WriteOnlyQual("__write_only"); 1661 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 1662 if (WriteOnlyPos != std::string::npos) 1663 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 1664 else { 1665 std::string ReadWriteQual("__read_write"); 1666 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 1667 if (ReadWritePos != std::string::npos) 1668 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 1669 } 1670 } 1671 } 1672 1673 // Returns the address space id that should be produced to the 1674 // kernel_arg_addr_space metadata. This is always fixed to the ids 1675 // as specified in the SPIR 2.0 specification in order to differentiate 1676 // for example in clGetKernelArgInfo() implementation between the address 1677 // spaces with targets without unique mapping to the OpenCL address spaces 1678 // (basically all single AS CPUs). 1679 static unsigned ArgInfoAddressSpace(LangAS AS) { 1680 switch (AS) { 1681 case LangAS::opencl_global: 1682 return 1; 1683 case LangAS::opencl_constant: 1684 return 2; 1685 case LangAS::opencl_local: 1686 return 3; 1687 case LangAS::opencl_generic: 1688 return 4; // Not in SPIR 2.0 specs. 1689 case LangAS::opencl_global_device: 1690 return 5; 1691 case LangAS::opencl_global_host: 1692 return 6; 1693 default: 1694 return 0; // Assume private. 1695 } 1696 } 1697 1698 void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn, 1699 const FunctionDecl *FD, 1700 CodeGenFunction *CGF) { 1701 assert(((FD && CGF) || (!FD && !CGF)) && 1702 "Incorrect use - FD and CGF should either be both null or not!"); 1703 // Create MDNodes that represent the kernel arg metadata. 1704 // Each MDNode is a list in the form of "key", N number of values which is 1705 // the same number of values as their are kernel arguments. 1706 1707 const PrintingPolicy &Policy = Context.getPrintingPolicy(); 1708 1709 // MDNode for the kernel argument address space qualifiers. 1710 SmallVector<llvm::Metadata *, 8> addressQuals; 1711 1712 // MDNode for the kernel argument access qualifiers (images only). 1713 SmallVector<llvm::Metadata *, 8> accessQuals; 1714 1715 // MDNode for the kernel argument type names. 1716 SmallVector<llvm::Metadata *, 8> argTypeNames; 1717 1718 // MDNode for the kernel argument base type names. 1719 SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 1720 1721 // MDNode for the kernel argument type qualifiers. 1722 SmallVector<llvm::Metadata *, 8> argTypeQuals; 1723 1724 // MDNode for the kernel argument names. 1725 SmallVector<llvm::Metadata *, 8> argNames; 1726 1727 if (FD && CGF) 1728 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 1729 const ParmVarDecl *parm = FD->getParamDecl(i); 1730 QualType ty = parm->getType(); 1731 std::string typeQuals; 1732 1733 // Get image and pipe access qualifier: 1734 if (ty->isImageType() || ty->isPipeType()) { 1735 const Decl *PDecl = parm; 1736 if (auto *TD = dyn_cast<TypedefType>(ty)) 1737 PDecl = TD->getDecl(); 1738 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 1739 if (A && A->isWriteOnly()) 1740 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 1741 else if (A && A->isReadWrite()) 1742 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 1743 else 1744 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 1745 } else 1746 accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 1747 1748 // Get argument name. 1749 argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 1750 1751 auto getTypeSpelling = [&](QualType Ty) { 1752 auto typeName = Ty.getUnqualifiedType().getAsString(Policy); 1753 1754 if (Ty.isCanonical()) { 1755 StringRef typeNameRef = typeName; 1756 // Turn "unsigned type" to "utype" 1757 if (typeNameRef.consume_front("unsigned ")) 1758 return std::string("u") + typeNameRef.str(); 1759 if (typeNameRef.consume_front("signed ")) 1760 return typeNameRef.str(); 1761 } 1762 1763 return typeName; 1764 }; 1765 1766 if (ty->isPointerType()) { 1767 QualType pointeeTy = ty->getPointeeType(); 1768 1769 // Get address qualifier. 1770 addressQuals.push_back( 1771 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 1772 ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 1773 1774 // Get argument type name. 1775 std::string typeName = getTypeSpelling(pointeeTy) + "*"; 1776 std::string baseTypeName = 1777 getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 1778 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1779 argBaseTypeNames.push_back( 1780 llvm::MDString::get(VMContext, baseTypeName)); 1781 1782 // Get argument type qualifiers: 1783 if (ty.isRestrictQualified()) 1784 typeQuals = "restrict"; 1785 if (pointeeTy.isConstQualified() || 1786 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 1787 typeQuals += typeQuals.empty() ? "const" : " const"; 1788 if (pointeeTy.isVolatileQualified()) 1789 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 1790 } else { 1791 uint32_t AddrSpc = 0; 1792 bool isPipe = ty->isPipeType(); 1793 if (ty->isImageType() || isPipe) 1794 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 1795 1796 addressQuals.push_back( 1797 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 1798 1799 // Get argument type name. 1800 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; 1801 std::string typeName = getTypeSpelling(ty); 1802 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); 1803 1804 // Remove access qualifiers on images 1805 // (as they are inseparable from type in clang implementation, 1806 // but OpenCL spec provides a special query to get access qualifier 1807 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 1808 if (ty->isImageType()) { 1809 removeImageAccessQualifier(typeName); 1810 removeImageAccessQualifier(baseTypeName); 1811 } 1812 1813 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1814 argBaseTypeNames.push_back( 1815 llvm::MDString::get(VMContext, baseTypeName)); 1816 1817 if (isPipe) 1818 typeQuals = "pipe"; 1819 } 1820 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 1821 } 1822 1823 Fn->setMetadata("kernel_arg_addr_space", 1824 llvm::MDNode::get(VMContext, addressQuals)); 1825 Fn->setMetadata("kernel_arg_access_qual", 1826 llvm::MDNode::get(VMContext, accessQuals)); 1827 Fn->setMetadata("kernel_arg_type", 1828 llvm::MDNode::get(VMContext, argTypeNames)); 1829 Fn->setMetadata("kernel_arg_base_type", 1830 llvm::MDNode::get(VMContext, argBaseTypeNames)); 1831 Fn->setMetadata("kernel_arg_type_qual", 1832 llvm::MDNode::get(VMContext, argTypeQuals)); 1833 if (getCodeGenOpts().EmitOpenCLArgMetadata) 1834 Fn->setMetadata("kernel_arg_name", 1835 llvm::MDNode::get(VMContext, argNames)); 1836 } 1837 1838 /// Determines whether the language options require us to model 1839 /// unwind exceptions. We treat -fexceptions as mandating this 1840 /// except under the fragile ObjC ABI with only ObjC exceptions 1841 /// enabled. This means, for example, that C with -fexceptions 1842 /// enables this. 1843 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 1844 // If exceptions are completely disabled, obviously this is false. 1845 if (!LangOpts.Exceptions) return false; 1846 1847 // If C++ exceptions are enabled, this is true. 1848 if (LangOpts.CXXExceptions) return true; 1849 1850 // If ObjC exceptions are enabled, this depends on the ABI. 1851 if (LangOpts.ObjCExceptions) { 1852 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 1853 } 1854 1855 return true; 1856 } 1857 1858 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 1859 const CXXMethodDecl *MD) { 1860 // Check that the type metadata can ever actually be used by a call. 1861 if (!CGM.getCodeGenOpts().LTOUnit || 1862 !CGM.HasHiddenLTOVisibility(MD->getParent())) 1863 return false; 1864 1865 // Only functions whose address can be taken with a member function pointer 1866 // need this sort of type metadata. 1867 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) && 1868 !isa<CXXDestructorDecl>(MD); 1869 } 1870 1871 std::vector<const CXXRecordDecl *> 1872 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 1873 llvm::SetVector<const CXXRecordDecl *> MostBases; 1874 1875 std::function<void (const CXXRecordDecl *)> CollectMostBases; 1876 CollectMostBases = [&](const CXXRecordDecl *RD) { 1877 if (RD->getNumBases() == 0) 1878 MostBases.insert(RD); 1879 for (const CXXBaseSpecifier &B : RD->bases()) 1880 CollectMostBases(B.getType()->getAsCXXRecordDecl()); 1881 }; 1882 CollectMostBases(RD); 1883 return MostBases.takeVector(); 1884 } 1885 1886 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 1887 llvm::Function *F) { 1888 llvm::AttrBuilder B(F->getContext()); 1889 1890 if (CodeGenOpts.UnwindTables) 1891 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 1892 1893 if (CodeGenOpts.StackClashProtector) 1894 B.addAttribute("probe-stack", "inline-asm"); 1895 1896 if (!hasUnwindExceptions(LangOpts)) 1897 B.addAttribute(llvm::Attribute::NoUnwind); 1898 1899 if (!D || !D->hasAttr<NoStackProtectorAttr>()) { 1900 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 1901 B.addAttribute(llvm::Attribute::StackProtect); 1902 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 1903 B.addAttribute(llvm::Attribute::StackProtectStrong); 1904 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 1905 B.addAttribute(llvm::Attribute::StackProtectReq); 1906 } 1907 1908 if (!D) { 1909 // If we don't have a declaration to control inlining, the function isn't 1910 // explicitly marked as alwaysinline for semantic reasons, and inlining is 1911 // disabled, mark the function as noinline. 1912 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 1913 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 1914 B.addAttribute(llvm::Attribute::NoInline); 1915 1916 F->addFnAttrs(B); 1917 return; 1918 } 1919 1920 // Track whether we need to add the optnone LLVM attribute, 1921 // starting with the default for this optimization level. 1922 bool ShouldAddOptNone = 1923 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 1924 // We can't add optnone in the following cases, it won't pass the verifier. 1925 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 1926 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 1927 1928 // Add optnone, but do so only if the function isn't always_inline. 1929 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && 1930 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1931 B.addAttribute(llvm::Attribute::OptimizeNone); 1932 1933 // OptimizeNone implies noinline; we should not be inlining such functions. 1934 B.addAttribute(llvm::Attribute::NoInline); 1935 1936 // We still need to handle naked functions even though optnone subsumes 1937 // much of their semantics. 1938 if (D->hasAttr<NakedAttr>()) 1939 B.addAttribute(llvm::Attribute::Naked); 1940 1941 // OptimizeNone wins over OptimizeForSize and MinSize. 1942 F->removeFnAttr(llvm::Attribute::OptimizeForSize); 1943 F->removeFnAttr(llvm::Attribute::MinSize); 1944 } else if (D->hasAttr<NakedAttr>()) { 1945 // Naked implies noinline: we should not be inlining such functions. 1946 B.addAttribute(llvm::Attribute::Naked); 1947 B.addAttribute(llvm::Attribute::NoInline); 1948 } else if (D->hasAttr<NoDuplicateAttr>()) { 1949 B.addAttribute(llvm::Attribute::NoDuplicate); 1950 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1951 // Add noinline if the function isn't always_inline. 1952 B.addAttribute(llvm::Attribute::NoInline); 1953 } else if (D->hasAttr<AlwaysInlineAttr>() && 1954 !F->hasFnAttribute(llvm::Attribute::NoInline)) { 1955 // (noinline wins over always_inline, and we can't specify both in IR) 1956 B.addAttribute(llvm::Attribute::AlwaysInline); 1957 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 1958 // If we're not inlining, then force everything that isn't always_inline to 1959 // carry an explicit noinline attribute. 1960 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 1961 B.addAttribute(llvm::Attribute::NoInline); 1962 } else { 1963 // Otherwise, propagate the inline hint attribute and potentially use its 1964 // absence to mark things as noinline. 1965 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1966 // Search function and template pattern redeclarations for inline. 1967 auto CheckForInline = [](const FunctionDecl *FD) { 1968 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 1969 return Redecl->isInlineSpecified(); 1970 }; 1971 if (any_of(FD->redecls(), CheckRedeclForInline)) 1972 return true; 1973 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 1974 if (!Pattern) 1975 return false; 1976 return any_of(Pattern->redecls(), CheckRedeclForInline); 1977 }; 1978 if (CheckForInline(FD)) { 1979 B.addAttribute(llvm::Attribute::InlineHint); 1980 } else if (CodeGenOpts.getInlining() == 1981 CodeGenOptions::OnlyHintInlining && 1982 !FD->isInlined() && 1983 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1984 B.addAttribute(llvm::Attribute::NoInline); 1985 } 1986 } 1987 } 1988 1989 // Add other optimization related attributes if we are optimizing this 1990 // function. 1991 if (!D->hasAttr<OptimizeNoneAttr>()) { 1992 if (D->hasAttr<ColdAttr>()) { 1993 if (!ShouldAddOptNone) 1994 B.addAttribute(llvm::Attribute::OptimizeForSize); 1995 B.addAttribute(llvm::Attribute::Cold); 1996 } 1997 if (D->hasAttr<HotAttr>()) 1998 B.addAttribute(llvm::Attribute::Hot); 1999 if (D->hasAttr<MinSizeAttr>()) 2000 B.addAttribute(llvm::Attribute::MinSize); 2001 } 2002 2003 F->addFnAttrs(B); 2004 2005 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 2006 if (alignment) 2007 F->setAlignment(llvm::Align(alignment)); 2008 2009 if (!D->hasAttr<AlignedAttr>()) 2010 if (LangOpts.FunctionAlignment) 2011 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 2012 2013 // Some C++ ABIs require 2-byte alignment for member functions, in order to 2014 // reserve a bit for differentiating between virtual and non-virtual member 2015 // functions. If the current target's C++ ABI requires this and this is a 2016 // member function, set its alignment accordingly. 2017 if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 2018 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 2019 F->setAlignment(llvm::Align(2)); 2020 } 2021 2022 // In the cross-dso CFI mode with canonical jump tables, we want !type 2023 // attributes on definitions only. 2024 if (CodeGenOpts.SanitizeCfiCrossDso && 2025 CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 2026 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 2027 // Skip available_externally functions. They won't be codegen'ed in the 2028 // current module anyway. 2029 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 2030 CreateFunctionTypeMetadataForIcall(FD, F); 2031 } 2032 } 2033 2034 // Emit type metadata on member functions for member function pointer checks. 2035 // These are only ever necessary on definitions; we're guaranteed that the 2036 // definition will be present in the LTO unit as a result of LTO visibility. 2037 auto *MD = dyn_cast<CXXMethodDecl>(D); 2038 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 2039 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 2040 llvm::Metadata *Id = 2041 CreateMetadataIdentifierForType(Context.getMemberPointerType( 2042 MD->getType(), Context.getRecordType(Base).getTypePtr())); 2043 F->addTypeMetadata(0, Id); 2044 } 2045 } 2046 } 2047 2048 void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D, 2049 llvm::Function *F) { 2050 if (D->hasAttr<StrictFPAttr>()) { 2051 llvm::AttrBuilder FuncAttrs(F->getContext()); 2052 FuncAttrs.addAttribute("strictfp"); 2053 F->addFnAttrs(FuncAttrs); 2054 } 2055 } 2056 2057 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 2058 const Decl *D = GD.getDecl(); 2059 if (isa_and_nonnull<NamedDecl>(D)) 2060 setGVProperties(GV, GD); 2061 else 2062 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 2063 2064 if (D && D->hasAttr<UsedAttr>()) 2065 addUsedOrCompilerUsedGlobal(GV); 2066 2067 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) { 2068 const auto *VD = cast<VarDecl>(D); 2069 if (VD->getType().isConstQualified() && 2070 VD->getStorageDuration() == SD_Static) 2071 addUsedOrCompilerUsedGlobal(GV); 2072 } 2073 } 2074 2075 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 2076 llvm::AttrBuilder &Attrs) { 2077 // Add target-cpu and target-features attributes to functions. If 2078 // we have a decl for the function and it has a target attribute then 2079 // parse that and add it to the feature set. 2080 StringRef TargetCPU = getTarget().getTargetOpts().CPU; 2081 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 2082 std::vector<std::string> Features; 2083 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 2084 FD = FD ? FD->getMostRecentDecl() : FD; 2085 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 2086 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 2087 const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; 2088 bool AddedAttr = false; 2089 if (TD || SD || TC) { 2090 llvm::StringMap<bool> FeatureMap; 2091 getContext().getFunctionFeatureMap(FeatureMap, GD); 2092 2093 // Produce the canonical string for this set of features. 2094 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 2095 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 2096 2097 // Now add the target-cpu and target-features to the function. 2098 // While we populated the feature map above, we still need to 2099 // get and parse the target attribute so we can get the cpu for 2100 // the function. 2101 if (TD) { 2102 ParsedTargetAttr ParsedAttr = TD->parse(); 2103 if (!ParsedAttr.Architecture.empty() && 2104 getTarget().isValidCPUName(ParsedAttr.Architecture)) { 2105 TargetCPU = ParsedAttr.Architecture; 2106 TuneCPU = ""; // Clear the tune CPU. 2107 } 2108 if (!ParsedAttr.Tune.empty() && 2109 getTarget().isValidCPUName(ParsedAttr.Tune)) 2110 TuneCPU = ParsedAttr.Tune; 2111 } 2112 2113 if (SD) { 2114 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can 2115 // favor this processor. 2116 TuneCPU = getTarget().getCPUSpecificTuneName( 2117 SD->getCPUName(GD.getMultiVersionIndex())->getName()); 2118 } 2119 } else { 2120 // Otherwise just add the existing target cpu and target features to the 2121 // function. 2122 Features = getTarget().getTargetOpts().Features; 2123 } 2124 2125 if (!TargetCPU.empty()) { 2126 Attrs.addAttribute("target-cpu", TargetCPU); 2127 AddedAttr = true; 2128 } 2129 if (!TuneCPU.empty()) { 2130 Attrs.addAttribute("tune-cpu", TuneCPU); 2131 AddedAttr = true; 2132 } 2133 if (!Features.empty()) { 2134 llvm::sort(Features); 2135 Attrs.addAttribute("target-features", llvm::join(Features, ",")); 2136 AddedAttr = true; 2137 } 2138 2139 return AddedAttr; 2140 } 2141 2142 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 2143 llvm::GlobalObject *GO) { 2144 const Decl *D = GD.getDecl(); 2145 SetCommonAttributes(GD, GO); 2146 2147 if (D) { 2148 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2149 if (D->hasAttr<RetainAttr>()) 2150 addUsedGlobal(GV); 2151 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 2152 GV->addAttribute("bss-section", SA->getName()); 2153 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 2154 GV->addAttribute("data-section", SA->getName()); 2155 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 2156 GV->addAttribute("rodata-section", SA->getName()); 2157 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2158 GV->addAttribute("relro-section", SA->getName()); 2159 } 2160 2161 if (auto *F = dyn_cast<llvm::Function>(GO)) { 2162 if (D->hasAttr<RetainAttr>()) 2163 addUsedGlobal(F); 2164 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 2165 if (!D->getAttr<SectionAttr>()) 2166 F->addFnAttr("implicit-section-name", SA->getName()); 2167 2168 llvm::AttrBuilder Attrs(F->getContext()); 2169 if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 2170 // We know that GetCPUAndFeaturesAttributes will always have the 2171 // newest set, since it has the newest possible FunctionDecl, so the 2172 // new ones should replace the old. 2173 llvm::AttributeMask RemoveAttrs; 2174 RemoveAttrs.addAttribute("target-cpu"); 2175 RemoveAttrs.addAttribute("target-features"); 2176 RemoveAttrs.addAttribute("tune-cpu"); 2177 F->removeFnAttrs(RemoveAttrs); 2178 F->addFnAttrs(Attrs); 2179 } 2180 } 2181 2182 if (const auto *CSA = D->getAttr<CodeSegAttr>()) 2183 GO->setSection(CSA->getName()); 2184 else if (const auto *SA = D->getAttr<SectionAttr>()) 2185 GO->setSection(SA->getName()); 2186 } 2187 2188 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 2189 } 2190 2191 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 2192 llvm::Function *F, 2193 const CGFunctionInfo &FI) { 2194 const Decl *D = GD.getDecl(); 2195 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 2196 SetLLVMFunctionAttributesForDefinition(D, F); 2197 2198 F->setLinkage(llvm::Function::InternalLinkage); 2199 2200 setNonAliasAttributes(GD, F); 2201 } 2202 2203 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 2204 // Set linkage and visibility in case we never see a definition. 2205 LinkageInfo LV = ND->getLinkageAndVisibility(); 2206 // Don't set internal linkage on declarations. 2207 // "extern_weak" is overloaded in LLVM; we probably should have 2208 // separate linkage types for this. 2209 if (isExternallyVisible(LV.getLinkage()) && 2210 (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 2211 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 2212 } 2213 2214 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 2215 llvm::Function *F) { 2216 // Only if we are checking indirect calls. 2217 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 2218 return; 2219 2220 // Non-static class methods are handled via vtable or member function pointer 2221 // checks elsewhere. 2222 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2223 return; 2224 2225 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 2226 F->addTypeMetadata(0, MD); 2227 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 2228 2229 // Emit a hash-based bit set entry for cross-DSO calls. 2230 if (CodeGenOpts.SanitizeCfiCrossDso) 2231 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 2232 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 2233 } 2234 2235 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 2236 bool IsIncompleteFunction, 2237 bool IsThunk) { 2238 2239 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 2240 // If this is an intrinsic function, set the function's attributes 2241 // to the intrinsic's attributes. 2242 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 2243 return; 2244 } 2245 2246 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2247 2248 if (!IsIncompleteFunction) 2249 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2250 IsThunk); 2251 2252 // Add the Returned attribute for "this", except for iOS 5 and earlier 2253 // where substantial code, including the libstdc++ dylib, was compiled with 2254 // GCC and does not actually return "this". 2255 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 2256 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 2257 assert(!F->arg_empty() && 2258 F->arg_begin()->getType() 2259 ->canLosslesslyBitCastTo(F->getReturnType()) && 2260 "unexpected this return"); 2261 F->addParamAttr(0, llvm::Attribute::Returned); 2262 } 2263 2264 // Only a few attributes are set on declarations; these may later be 2265 // overridden by a definition. 2266 2267 setLinkageForGV(F, FD); 2268 setGVProperties(F, FD); 2269 2270 // Setup target-specific attributes. 2271 if (!IsIncompleteFunction && F->isDeclaration()) 2272 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 2273 2274 if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 2275 F->setSection(CSA->getName()); 2276 else if (const auto *SA = FD->getAttr<SectionAttr>()) 2277 F->setSection(SA->getName()); 2278 2279 if (const auto *EA = FD->getAttr<ErrorAttr>()) { 2280 if (EA->isError()) 2281 F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); 2282 else if (EA->isWarning()) 2283 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); 2284 } 2285 2286 // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2287 if (FD->isInlineBuiltinDeclaration()) { 2288 const FunctionDecl *FDBody; 2289 bool HasBody = FD->hasBody(FDBody); 2290 (void)HasBody; 2291 assert(HasBody && "Inline builtin declarations should always have an " 2292 "available body!"); 2293 if (shouldEmitFunction(FDBody)) 2294 F->addFnAttr(llvm::Attribute::NoBuiltin); 2295 } 2296 2297 if (FD->isReplaceableGlobalAllocationFunction()) { 2298 // A replaceable global allocation function does not act like a builtin by 2299 // default, only if it is invoked by a new-expression or delete-expression. 2300 F->addFnAttr(llvm::Attribute::NoBuiltin); 2301 } 2302 2303 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 2304 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2305 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 2306 if (MD->isVirtual()) 2307 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2308 2309 // Don't emit entries for function declarations in the cross-DSO mode. This 2310 // is handled with better precision by the receiving DSO. But if jump tables 2311 // are non-canonical then we need type metadata in order to produce the local 2312 // jump table. 2313 if (!CodeGenOpts.SanitizeCfiCrossDso || 2314 !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 2315 CreateFunctionTypeMetadataForIcall(FD, F); 2316 2317 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 2318 getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 2319 2320 if (const auto *CB = FD->getAttr<CallbackAttr>()) { 2321 // Annotate the callback behavior as metadata: 2322 // - The callback callee (as argument number). 2323 // - The callback payloads (as argument numbers). 2324 llvm::LLVMContext &Ctx = F->getContext(); 2325 llvm::MDBuilder MDB(Ctx); 2326 2327 // The payload indices are all but the first one in the encoding. The first 2328 // identifies the callback callee. 2329 int CalleeIdx = *CB->encoding_begin(); 2330 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 2331 F->addMetadata(llvm::LLVMContext::MD_callback, 2332 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 2333 CalleeIdx, PayloadIndices, 2334 /* VarArgsArePassed */ false)})); 2335 } 2336 } 2337 2338 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2339 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2340 "Only globals with definition can force usage."); 2341 LLVMUsed.emplace_back(GV); 2342 } 2343 2344 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 2345 assert(!GV->isDeclaration() && 2346 "Only globals with definition can force usage."); 2347 LLVMCompilerUsed.emplace_back(GV); 2348 } 2349 2350 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { 2351 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2352 "Only globals with definition can force usage."); 2353 if (getTriple().isOSBinFormatELF()) 2354 LLVMCompilerUsed.emplace_back(GV); 2355 else 2356 LLVMUsed.emplace_back(GV); 2357 } 2358 2359 static void emitUsed(CodeGenModule &CGM, StringRef Name, 2360 std::vector<llvm::WeakTrackingVH> &List) { 2361 // Don't create llvm.used if there is no need. 2362 if (List.empty()) 2363 return; 2364 2365 // Convert List to what ConstantArray needs. 2366 SmallVector<llvm::Constant*, 8> UsedArray; 2367 UsedArray.resize(List.size()); 2368 for (unsigned i = 0, e = List.size(); i != e; ++i) { 2369 UsedArray[i] = 2370 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2371 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 2372 } 2373 2374 if (UsedArray.empty()) 2375 return; 2376 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 2377 2378 auto *GV = new llvm::GlobalVariable( 2379 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 2380 llvm::ConstantArray::get(ATy, UsedArray), Name); 2381 2382 GV->setSection("llvm.metadata"); 2383 } 2384 2385 void CodeGenModule::emitLLVMUsed() { 2386 emitUsed(*this, "llvm.used", LLVMUsed); 2387 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 2388 } 2389 2390 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 2391 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 2392 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2393 } 2394 2395 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 2396 llvm::SmallString<32> Opt; 2397 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2398 if (Opt.empty()) 2399 return; 2400 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2401 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2402 } 2403 2404 void CodeGenModule::AddDependentLib(StringRef Lib) { 2405 auto &C = getLLVMContext(); 2406 if (getTarget().getTriple().isOSBinFormatELF()) { 2407 ELFDependentLibraries.push_back( 2408 llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 2409 return; 2410 } 2411 2412 llvm::SmallString<24> Opt; 2413 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 2414 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2415 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 2416 } 2417 2418 /// Add link options implied by the given module, including modules 2419 /// it depends on, using a postorder walk. 2420 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 2421 SmallVectorImpl<llvm::MDNode *> &Metadata, 2422 llvm::SmallPtrSet<Module *, 16> &Visited) { 2423 // Import this module's parent. 2424 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 2425 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 2426 } 2427 2428 // Import this module's dependencies. 2429 for (Module *Import : llvm::reverse(Mod->Imports)) { 2430 if (Visited.insert(Import).second) 2431 addLinkOptionsPostorder(CGM, Import, Metadata, Visited); 2432 } 2433 2434 // Add linker options to link against the libraries/frameworks 2435 // described by this module. 2436 llvm::LLVMContext &Context = CGM.getLLVMContext(); 2437 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 2438 2439 // For modules that use export_as for linking, use that module 2440 // name instead. 2441 if (Mod->UseExportAsModuleLinkName) 2442 return; 2443 2444 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { 2445 // Link against a framework. Frameworks are currently Darwin only, so we 2446 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 2447 if (LL.IsFramework) { 2448 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"), 2449 llvm::MDString::get(Context, LL.Library)}; 2450 2451 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2452 continue; 2453 } 2454 2455 // Link against a library. 2456 if (IsELF) { 2457 llvm::Metadata *Args[2] = { 2458 llvm::MDString::get(Context, "lib"), 2459 llvm::MDString::get(Context, LL.Library), 2460 }; 2461 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2462 } else { 2463 llvm::SmallString<24> Opt; 2464 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); 2465 auto *OptString = llvm::MDString::get(Context, Opt); 2466 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 2467 } 2468 } 2469 } 2470 2471 void CodeGenModule::EmitModuleLinkOptions() { 2472 // Collect the set of all of the modules we want to visit to emit link 2473 // options, which is essentially the imported modules and all of their 2474 // non-explicit child modules. 2475 llvm::SetVector<clang::Module *> LinkModules; 2476 llvm::SmallPtrSet<clang::Module *, 16> Visited; 2477 SmallVector<clang::Module *, 16> Stack; 2478 2479 // Seed the stack with imported modules. 2480 for (Module *M : ImportedModules) { 2481 // Do not add any link flags when an implementation TU of a module imports 2482 // a header of that same module. 2483 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 2484 !getLangOpts().isCompilingModule()) 2485 continue; 2486 if (Visited.insert(M).second) 2487 Stack.push_back(M); 2488 } 2489 2490 // Find all of the modules to import, making a little effort to prune 2491 // non-leaf modules. 2492 while (!Stack.empty()) { 2493 clang::Module *Mod = Stack.pop_back_val(); 2494 2495 bool AnyChildren = false; 2496 2497 // Visit the submodules of this module. 2498 for (const auto &SM : Mod->submodules()) { 2499 // Skip explicit children; they need to be explicitly imported to be 2500 // linked against. 2501 if (SM->IsExplicit) 2502 continue; 2503 2504 if (Visited.insert(SM).second) { 2505 Stack.push_back(SM); 2506 AnyChildren = true; 2507 } 2508 } 2509 2510 // We didn't find any children, so add this module to the list of 2511 // modules to link against. 2512 if (!AnyChildren) { 2513 LinkModules.insert(Mod); 2514 } 2515 } 2516 2517 // Add link options for all of the imported modules in reverse topological 2518 // order. We don't do anything to try to order import link flags with respect 2519 // to linker options inserted by things like #pragma comment(). 2520 SmallVector<llvm::MDNode *, 16> MetadataArgs; 2521 Visited.clear(); 2522 for (Module *M : LinkModules) 2523 if (Visited.insert(M).second) 2524 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 2525 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 2526 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 2527 2528 // Add the linker options metadata flag. 2529 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 2530 for (auto *MD : LinkerOptionsMetadata) 2531 NMD->addOperand(MD); 2532 } 2533 2534 void CodeGenModule::EmitDeferred() { 2535 // Emit deferred declare target declarations. 2536 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 2537 getOpenMPRuntime().emitDeferredTargetDecls(); 2538 2539 // Emit code for any potentially referenced deferred decls. Since a 2540 // previously unused static decl may become used during the generation of code 2541 // for a static function, iterate until no changes are made. 2542 2543 if (!DeferredVTables.empty()) { 2544 EmitDeferredVTables(); 2545 2546 // Emitting a vtable doesn't directly cause more vtables to 2547 // become deferred, although it can cause functions to be 2548 // emitted that then need those vtables. 2549 assert(DeferredVTables.empty()); 2550 } 2551 2552 // Emit CUDA/HIP static device variables referenced by host code only. 2553 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still 2554 // needed for further handling. 2555 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 2556 llvm::append_range(DeferredDeclsToEmit, 2557 getContext().CUDADeviceVarODRUsedByHost); 2558 2559 // Stop if we're out of both deferred vtables and deferred declarations. 2560 if (DeferredDeclsToEmit.empty()) 2561 return; 2562 2563 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 2564 // work, it will not interfere with this. 2565 std::vector<GlobalDecl> CurDeclsToEmit; 2566 CurDeclsToEmit.swap(DeferredDeclsToEmit); 2567 2568 for (GlobalDecl &D : CurDeclsToEmit) { 2569 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 2570 // to get GlobalValue with exactly the type we need, not something that 2571 // might had been created for another decl with the same mangled name but 2572 // different type. 2573 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 2574 GetAddrOfGlobal(D, ForDefinition)); 2575 2576 // In case of different address spaces, we may still get a cast, even with 2577 // IsForDefinition equal to true. Query mangled names table to get 2578 // GlobalValue. 2579 if (!GV) 2580 GV = GetGlobalValue(getMangledName(D)); 2581 2582 // Make sure GetGlobalValue returned non-null. 2583 assert(GV); 2584 2585 // Check to see if we've already emitted this. This is necessary 2586 // for a couple of reasons: first, decls can end up in the 2587 // deferred-decls queue multiple times, and second, decls can end 2588 // up with definitions in unusual ways (e.g. by an extern inline 2589 // function acquiring a strong function redefinition). Just 2590 // ignore these cases. 2591 if (!GV->isDeclaration()) 2592 continue; 2593 2594 // If this is OpenMP, check if it is legal to emit this global normally. 2595 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 2596 continue; 2597 2598 // Otherwise, emit the definition and move on to the next one. 2599 EmitGlobalDefinition(D, GV); 2600 2601 // If we found out that we need to emit more decls, do that recursively. 2602 // This has the advantage that the decls are emitted in a DFS and related 2603 // ones are close together, which is convenient for testing. 2604 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 2605 EmitDeferred(); 2606 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 2607 } 2608 } 2609 } 2610 2611 void CodeGenModule::EmitVTablesOpportunistically() { 2612 // Try to emit external vtables as available_externally if they have emitted 2613 // all inlined virtual functions. It runs after EmitDeferred() and therefore 2614 // is not allowed to create new references to things that need to be emitted 2615 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 2616 2617 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 2618 && "Only emit opportunistic vtables with optimizations"); 2619 2620 for (const CXXRecordDecl *RD : OpportunisticVTables) { 2621 assert(getVTables().isVTableExternal(RD) && 2622 "This queue should only contain external vtables"); 2623 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 2624 VTables.GenerateClassData(RD); 2625 } 2626 OpportunisticVTables.clear(); 2627 } 2628 2629 void CodeGenModule::EmitGlobalAnnotations() { 2630 if (Annotations.empty()) 2631 return; 2632 2633 // Create a new global variable for the ConstantStruct in the Module. 2634 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 2635 Annotations[0]->getType(), Annotations.size()), Annotations); 2636 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 2637 llvm::GlobalValue::AppendingLinkage, 2638 Array, "llvm.global.annotations"); 2639 gv->setSection(AnnotationSection); 2640 } 2641 2642 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 2643 llvm::Constant *&AStr = AnnotationStrings[Str]; 2644 if (AStr) 2645 return AStr; 2646 2647 // Not found yet, create a new global. 2648 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 2649 auto *gv = 2650 new llvm::GlobalVariable(getModule(), s->getType(), true, 2651 llvm::GlobalValue::PrivateLinkage, s, ".str"); 2652 gv->setSection(AnnotationSection); 2653 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2654 AStr = gv; 2655 return gv; 2656 } 2657 2658 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 2659 SourceManager &SM = getContext().getSourceManager(); 2660 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2661 if (PLoc.isValid()) 2662 return EmitAnnotationString(PLoc.getFilename()); 2663 return EmitAnnotationString(SM.getBufferName(Loc)); 2664 } 2665 2666 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 2667 SourceManager &SM = getContext().getSourceManager(); 2668 PresumedLoc PLoc = SM.getPresumedLoc(L); 2669 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 2670 SM.getExpansionLineNumber(L); 2671 return llvm::ConstantInt::get(Int32Ty, LineNo); 2672 } 2673 2674 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 2675 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 2676 if (Exprs.empty()) 2677 return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy); 2678 2679 llvm::FoldingSetNodeID ID; 2680 for (Expr *E : Exprs) { 2681 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 2682 } 2683 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 2684 if (Lookup) 2685 return Lookup; 2686 2687 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 2688 LLVMArgs.reserve(Exprs.size()); 2689 ConstantEmitter ConstEmiter(*this); 2690 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 2691 const auto *CE = cast<clang::ConstantExpr>(E); 2692 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 2693 CE->getType()); 2694 }); 2695 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 2696 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 2697 llvm::GlobalValue::PrivateLinkage, Struct, 2698 ".args"); 2699 GV->setSection(AnnotationSection); 2700 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2701 auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy); 2702 2703 Lookup = Bitcasted; 2704 return Bitcasted; 2705 } 2706 2707 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 2708 const AnnotateAttr *AA, 2709 SourceLocation L) { 2710 // Get the globals for file name, annotation, and the line number. 2711 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 2712 *UnitGV = EmitAnnotationUnit(L), 2713 *LineNoCst = EmitAnnotationLineNo(L), 2714 *Args = EmitAnnotationArgs(AA); 2715 2716 llvm::Constant *GVInGlobalsAS = GV; 2717 if (GV->getAddressSpace() != 2718 getDataLayout().getDefaultGlobalsAddressSpace()) { 2719 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( 2720 GV, GV->getValueType()->getPointerTo( 2721 getDataLayout().getDefaultGlobalsAddressSpace())); 2722 } 2723 2724 // Create the ConstantStruct for the global annotation. 2725 llvm::Constant *Fields[] = { 2726 llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy), 2727 llvm::ConstantExpr::getBitCast(AnnoGV, GlobalsInt8PtrTy), 2728 llvm::ConstantExpr::getBitCast(UnitGV, GlobalsInt8PtrTy), 2729 LineNoCst, 2730 Args, 2731 }; 2732 return llvm::ConstantStruct::getAnon(Fields); 2733 } 2734 2735 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 2736 llvm::GlobalValue *GV) { 2737 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2738 // Get the struct elements for these annotations. 2739 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2740 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 2741 } 2742 2743 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 2744 SourceLocation Loc) const { 2745 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2746 // NoSanitize by function name. 2747 if (NoSanitizeL.containsFunction(Kind, Fn->getName())) 2748 return true; 2749 // NoSanitize by location. 2750 if (Loc.isValid()) 2751 return NoSanitizeL.containsLocation(Kind, Loc); 2752 // If location is unknown, this may be a compiler-generated function. Assume 2753 // it's located in the main file. 2754 auto &SM = Context.getSourceManager(); 2755 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2756 return NoSanitizeL.containsFile(Kind, MainFile->getName()); 2757 } 2758 return false; 2759 } 2760 2761 bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV, 2762 SourceLocation Loc, QualType Ty, 2763 StringRef Category) const { 2764 // For now globals can be ignored only in ASan and KASan. 2765 const SanitizerMask EnabledAsanMask = 2766 LangOpts.Sanitize.Mask & 2767 (SanitizerKind::Address | SanitizerKind::KernelAddress | 2768 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress | 2769 SanitizerKind::MemTag); 2770 if (!EnabledAsanMask) 2771 return false; 2772 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2773 if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category)) 2774 return true; 2775 if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category)) 2776 return true; 2777 // Check global type. 2778 if (!Ty.isNull()) { 2779 // Drill down the array types: if global variable of a fixed type is 2780 // not sanitized, we also don't instrument arrays of them. 2781 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 2782 Ty = AT->getElementType(); 2783 Ty = Ty.getCanonicalType().getUnqualifiedType(); 2784 // Only record types (classes, structs etc.) are ignored. 2785 if (Ty->isRecordType()) { 2786 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 2787 if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category)) 2788 return true; 2789 } 2790 } 2791 return false; 2792 } 2793 2794 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 2795 StringRef Category) const { 2796 const auto &XRayFilter = getContext().getXRayFilter(); 2797 using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 2798 auto Attr = ImbueAttr::NONE; 2799 if (Loc.isValid()) 2800 Attr = XRayFilter.shouldImbueLocation(Loc, Category); 2801 if (Attr == ImbueAttr::NONE) 2802 Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 2803 switch (Attr) { 2804 case ImbueAttr::NONE: 2805 return false; 2806 case ImbueAttr::ALWAYS: 2807 Fn->addFnAttr("function-instrument", "xray-always"); 2808 break; 2809 case ImbueAttr::ALWAYS_ARG1: 2810 Fn->addFnAttr("function-instrument", "xray-always"); 2811 Fn->addFnAttr("xray-log-args", "1"); 2812 break; 2813 case ImbueAttr::NEVER: 2814 Fn->addFnAttr("function-instrument", "xray-never"); 2815 break; 2816 } 2817 return true; 2818 } 2819 2820 bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn, 2821 SourceLocation Loc) const { 2822 const auto &ProfileList = getContext().getProfileList(); 2823 // If the profile list is empty, then instrument everything. 2824 if (ProfileList.isEmpty()) 2825 return false; 2826 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 2827 // First, check the function name. 2828 Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind); 2829 if (V.hasValue()) 2830 return *V; 2831 // Next, check the source location. 2832 if (Loc.isValid()) { 2833 Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind); 2834 if (V.hasValue()) 2835 return *V; 2836 } 2837 // If location is unknown, this may be a compiler-generated function. Assume 2838 // it's located in the main file. 2839 auto &SM = Context.getSourceManager(); 2840 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2841 Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind); 2842 if (V.hasValue()) 2843 return *V; 2844 } 2845 return ProfileList.getDefault(); 2846 } 2847 2848 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 2849 // Never defer when EmitAllDecls is specified. 2850 if (LangOpts.EmitAllDecls) 2851 return true; 2852 2853 if (CodeGenOpts.KeepStaticConsts) { 2854 const auto *VD = dyn_cast<VarDecl>(Global); 2855 if (VD && VD->getType().isConstQualified() && 2856 VD->getStorageDuration() == SD_Static) 2857 return true; 2858 } 2859 2860 return getContext().DeclMustBeEmitted(Global); 2861 } 2862 2863 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 2864 // In OpenMP 5.0 variables and function may be marked as 2865 // device_type(host/nohost) and we should not emit them eagerly unless we sure 2866 // that they must be emitted on the host/device. To be sure we need to have 2867 // seen a declare target with an explicit mentioning of the function, we know 2868 // we have if the level of the declare target attribute is -1. Note that we 2869 // check somewhere else if we should emit this at all. 2870 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { 2871 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 2872 OMPDeclareTargetDeclAttr::getActiveAttr(Global); 2873 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) 2874 return false; 2875 } 2876 2877 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2878 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 2879 // Implicit template instantiations may change linkage if they are later 2880 // explicitly instantiated, so they should not be emitted eagerly. 2881 return false; 2882 } 2883 if (const auto *VD = dyn_cast<VarDecl>(Global)) 2884 if (Context.getInlineVariableDefinitionKind(VD) == 2885 ASTContext::InlineVariableDefinitionKind::WeakUnknown) 2886 // A definition of an inline constexpr static data member may change 2887 // linkage later if it's redeclared outside the class. 2888 return false; 2889 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 2890 // codegen for global variables, because they may be marked as threadprivate. 2891 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 2892 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 2893 !isTypeConstant(Global->getType(), false) && 2894 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 2895 return false; 2896 2897 return true; 2898 } 2899 2900 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 2901 StringRef Name = getMangledName(GD); 2902 2903 // The UUID descriptor should be pointer aligned. 2904 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 2905 2906 // Look for an existing global. 2907 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 2908 return ConstantAddress(GV, GV->getValueType(), Alignment); 2909 2910 ConstantEmitter Emitter(*this); 2911 llvm::Constant *Init; 2912 2913 APValue &V = GD->getAsAPValue(); 2914 if (!V.isAbsent()) { 2915 // If possible, emit the APValue version of the initializer. In particular, 2916 // this gets the type of the constant right. 2917 Init = Emitter.emitForInitializer( 2918 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 2919 } else { 2920 // As a fallback, directly construct the constant. 2921 // FIXME: This may get padding wrong under esoteric struct layout rules. 2922 // MSVC appears to create a complete type 'struct __s_GUID' that it 2923 // presumably uses to represent these constants. 2924 MSGuidDecl::Parts Parts = GD->getParts(); 2925 llvm::Constant *Fields[4] = { 2926 llvm::ConstantInt::get(Int32Ty, Parts.Part1), 2927 llvm::ConstantInt::get(Int16Ty, Parts.Part2), 2928 llvm::ConstantInt::get(Int16Ty, Parts.Part3), 2929 llvm::ConstantDataArray::getRaw( 2930 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 2931 Int8Ty)}; 2932 Init = llvm::ConstantStruct::getAnon(Fields); 2933 } 2934 2935 auto *GV = new llvm::GlobalVariable( 2936 getModule(), Init->getType(), 2937 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2938 if (supportsCOMDAT()) 2939 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2940 setDSOLocal(GV); 2941 2942 if (!V.isAbsent()) { 2943 Emitter.finalize(GV); 2944 return ConstantAddress(GV, GV->getValueType(), Alignment); 2945 } 2946 2947 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 2948 llvm::Constant *Addr = llvm::ConstantExpr::getBitCast( 2949 GV, Ty->getPointerTo(GV->getAddressSpace())); 2950 return ConstantAddress(Addr, Ty, Alignment); 2951 } 2952 2953 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl( 2954 const UnnamedGlobalConstantDecl *GCD) { 2955 CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType()); 2956 2957 llvm::GlobalVariable **Entry = nullptr; 2958 Entry = &UnnamedGlobalConstantDeclMap[GCD]; 2959 if (*Entry) 2960 return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment); 2961 2962 ConstantEmitter Emitter(*this); 2963 llvm::Constant *Init; 2964 2965 const APValue &V = GCD->getValue(); 2966 2967 assert(!V.isAbsent()); 2968 Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(), 2969 GCD->getType()); 2970 2971 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), 2972 /*isConstant=*/true, 2973 llvm::GlobalValue::PrivateLinkage, Init, 2974 ".constant"); 2975 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2976 GV->setAlignment(Alignment.getAsAlign()); 2977 2978 Emitter.finalize(GV); 2979 2980 *Entry = GV; 2981 return ConstantAddress(GV, GV->getValueType(), Alignment); 2982 } 2983 2984 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( 2985 const TemplateParamObjectDecl *TPO) { 2986 StringRef Name = getMangledName(TPO); 2987 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); 2988 2989 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 2990 return ConstantAddress(GV, GV->getValueType(), Alignment); 2991 2992 ConstantEmitter Emitter(*this); 2993 llvm::Constant *Init = Emitter.emitForInitializer( 2994 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); 2995 2996 if (!Init) { 2997 ErrorUnsupported(TPO, "template parameter object"); 2998 return ConstantAddress::invalid(); 2999 } 3000 3001 auto *GV = new llvm::GlobalVariable( 3002 getModule(), Init->getType(), 3003 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 3004 if (supportsCOMDAT()) 3005 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3006 Emitter.finalize(GV); 3007 3008 return ConstantAddress(GV, GV->getValueType(), Alignment); 3009 } 3010 3011 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 3012 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 3013 assert(AA && "No alias?"); 3014 3015 CharUnits Alignment = getContext().getDeclAlign(VD); 3016 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 3017 3018 // See if there is already something with the target's name in the module. 3019 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 3020 if (Entry) { 3021 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 3022 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 3023 return ConstantAddress(Ptr, DeclTy, Alignment); 3024 } 3025 3026 llvm::Constant *Aliasee; 3027 if (isa<llvm::FunctionType>(DeclTy)) 3028 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 3029 GlobalDecl(cast<FunctionDecl>(VD)), 3030 /*ForVTable=*/false); 3031 else 3032 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 3033 nullptr); 3034 3035 auto *F = cast<llvm::GlobalValue>(Aliasee); 3036 F->setLinkage(llvm::Function::ExternalWeakLinkage); 3037 WeakRefReferences.insert(F); 3038 3039 return ConstantAddress(Aliasee, DeclTy, Alignment); 3040 } 3041 3042 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 3043 const auto *Global = cast<ValueDecl>(GD.getDecl()); 3044 3045 // Weak references don't produce any output by themselves. 3046 if (Global->hasAttr<WeakRefAttr>()) 3047 return; 3048 3049 // If this is an alias definition (which otherwise looks like a declaration) 3050 // emit it now. 3051 if (Global->hasAttr<AliasAttr>()) 3052 return EmitAliasDefinition(GD); 3053 3054 // IFunc like an alias whose value is resolved at runtime by calling resolver. 3055 if (Global->hasAttr<IFuncAttr>()) 3056 return emitIFuncDefinition(GD); 3057 3058 // If this is a cpu_dispatch multiversion function, emit the resolver. 3059 if (Global->hasAttr<CPUDispatchAttr>()) 3060 return emitCPUDispatchDefinition(GD); 3061 3062 // If this is CUDA, be selective about which declarations we emit. 3063 if (LangOpts.CUDA) { 3064 if (LangOpts.CUDAIsDevice) { 3065 if (!Global->hasAttr<CUDADeviceAttr>() && 3066 !Global->hasAttr<CUDAGlobalAttr>() && 3067 !Global->hasAttr<CUDAConstantAttr>() && 3068 !Global->hasAttr<CUDASharedAttr>() && 3069 !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 3070 !Global->getType()->isCUDADeviceBuiltinTextureType()) 3071 return; 3072 } else { 3073 // We need to emit host-side 'shadows' for all global 3074 // device-side variables because the CUDA runtime needs their 3075 // size and host-side address in order to provide access to 3076 // their device-side incarnations. 3077 3078 // So device-only functions are the only things we skip. 3079 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 3080 Global->hasAttr<CUDADeviceAttr>()) 3081 return; 3082 3083 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 3084 "Expected Variable or Function"); 3085 } 3086 } 3087 3088 if (LangOpts.OpenMP) { 3089 // If this is OpenMP, check if it is legal to emit this global normally. 3090 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 3091 return; 3092 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 3093 if (MustBeEmitted(Global)) 3094 EmitOMPDeclareReduction(DRD); 3095 return; 3096 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 3097 if (MustBeEmitted(Global)) 3098 EmitOMPDeclareMapper(DMD); 3099 return; 3100 } 3101 } 3102 3103 // Ignore declarations, they will be emitted on their first use. 3104 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3105 // Forward declarations are emitted lazily on first use. 3106 if (!FD->doesThisDeclarationHaveABody()) { 3107 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 3108 return; 3109 3110 StringRef MangledName = getMangledName(GD); 3111 3112 // Compute the function info and LLVM type. 3113 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3114 llvm::Type *Ty = getTypes().GetFunctionType(FI); 3115 3116 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 3117 /*DontDefer=*/false); 3118 return; 3119 } 3120 } else { 3121 const auto *VD = cast<VarDecl>(Global); 3122 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 3123 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 3124 !Context.isMSStaticDataMemberInlineDefinition(VD)) { 3125 if (LangOpts.OpenMP) { 3126 // Emit declaration of the must-be-emitted declare target variable. 3127 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3128 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 3129 bool UnifiedMemoryEnabled = 3130 getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 3131 if (*Res == OMPDeclareTargetDeclAttr::MT_To && 3132 !UnifiedMemoryEnabled) { 3133 (void)GetAddrOfGlobalVar(VD); 3134 } else { 3135 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 3136 (*Res == OMPDeclareTargetDeclAttr::MT_To && 3137 UnifiedMemoryEnabled)) && 3138 "Link clause or to clause with unified memory expected."); 3139 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 3140 } 3141 3142 return; 3143 } 3144 } 3145 // If this declaration may have caused an inline variable definition to 3146 // change linkage, make sure that it's emitted. 3147 if (Context.getInlineVariableDefinitionKind(VD) == 3148 ASTContext::InlineVariableDefinitionKind::Strong) 3149 GetAddrOfGlobalVar(VD); 3150 return; 3151 } 3152 } 3153 3154 // Defer code generation to first use when possible, e.g. if this is an inline 3155 // function. If the global must always be emitted, do it eagerly if possible 3156 // to benefit from cache locality. 3157 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 3158 // Emit the definition if it can't be deferred. 3159 EmitGlobalDefinition(GD); 3160 return; 3161 } 3162 3163 // If we're deferring emission of a C++ variable with an 3164 // initializer, remember the order in which it appeared in the file. 3165 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 3166 cast<VarDecl>(Global)->hasInit()) { 3167 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 3168 CXXGlobalInits.push_back(nullptr); 3169 } 3170 3171 StringRef MangledName = getMangledName(GD); 3172 if (GetGlobalValue(MangledName) != nullptr) { 3173 // The value has already been used and should therefore be emitted. 3174 addDeferredDeclToEmit(GD); 3175 } else if (MustBeEmitted(Global)) { 3176 // The value must be emitted, but cannot be emitted eagerly. 3177 assert(!MayBeEmittedEagerly(Global)); 3178 addDeferredDeclToEmit(GD); 3179 } else { 3180 // Otherwise, remember that we saw a deferred decl with this name. The 3181 // first use of the mangled name will cause it to move into 3182 // DeferredDeclsToEmit. 3183 DeferredDecls[MangledName] = GD; 3184 } 3185 } 3186 3187 // Check if T is a class type with a destructor that's not dllimport. 3188 static bool HasNonDllImportDtor(QualType T) { 3189 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 3190 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 3191 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 3192 return true; 3193 3194 return false; 3195 } 3196 3197 namespace { 3198 struct FunctionIsDirectlyRecursive 3199 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 3200 const StringRef Name; 3201 const Builtin::Context &BI; 3202 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 3203 : Name(N), BI(C) {} 3204 3205 bool VisitCallExpr(const CallExpr *E) { 3206 const FunctionDecl *FD = E->getDirectCallee(); 3207 if (!FD) 3208 return false; 3209 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3210 if (Attr && Name == Attr->getLabel()) 3211 return true; 3212 unsigned BuiltinID = FD->getBuiltinID(); 3213 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 3214 return false; 3215 StringRef BuiltinName = BI.getName(BuiltinID); 3216 if (BuiltinName.startswith("__builtin_") && 3217 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 3218 return true; 3219 } 3220 return false; 3221 } 3222 3223 bool VisitStmt(const Stmt *S) { 3224 for (const Stmt *Child : S->children()) 3225 if (Child && this->Visit(Child)) 3226 return true; 3227 return false; 3228 } 3229 }; 3230 3231 // Make sure we're not referencing non-imported vars or functions. 3232 struct DLLImportFunctionVisitor 3233 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 3234 bool SafeToInline = true; 3235 3236 bool shouldVisitImplicitCode() const { return true; } 3237 3238 bool VisitVarDecl(VarDecl *VD) { 3239 if (VD->getTLSKind()) { 3240 // A thread-local variable cannot be imported. 3241 SafeToInline = false; 3242 return SafeToInline; 3243 } 3244 3245 // A variable definition might imply a destructor call. 3246 if (VD->isThisDeclarationADefinition()) 3247 SafeToInline = !HasNonDllImportDtor(VD->getType()); 3248 3249 return SafeToInline; 3250 } 3251 3252 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 3253 if (const auto *D = E->getTemporary()->getDestructor()) 3254 SafeToInline = D->hasAttr<DLLImportAttr>(); 3255 return SafeToInline; 3256 } 3257 3258 bool VisitDeclRefExpr(DeclRefExpr *E) { 3259 ValueDecl *VD = E->getDecl(); 3260 if (isa<FunctionDecl>(VD)) 3261 SafeToInline = VD->hasAttr<DLLImportAttr>(); 3262 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 3263 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 3264 return SafeToInline; 3265 } 3266 3267 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 3268 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 3269 return SafeToInline; 3270 } 3271 3272 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3273 CXXMethodDecl *M = E->getMethodDecl(); 3274 if (!M) { 3275 // Call through a pointer to member function. This is safe to inline. 3276 SafeToInline = true; 3277 } else { 3278 SafeToInline = M->hasAttr<DLLImportAttr>(); 3279 } 3280 return SafeToInline; 3281 } 3282 3283 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 3284 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 3285 return SafeToInline; 3286 } 3287 3288 bool VisitCXXNewExpr(CXXNewExpr *E) { 3289 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 3290 return SafeToInline; 3291 } 3292 }; 3293 } 3294 3295 // isTriviallyRecursive - Check if this function calls another 3296 // decl that, because of the asm attribute or the other decl being a builtin, 3297 // ends up pointing to itself. 3298 bool 3299 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 3300 StringRef Name; 3301 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 3302 // asm labels are a special kind of mangling we have to support. 3303 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3304 if (!Attr) 3305 return false; 3306 Name = Attr->getLabel(); 3307 } else { 3308 Name = FD->getName(); 3309 } 3310 3311 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 3312 const Stmt *Body = FD->getBody(); 3313 return Body ? Walker.Visit(Body) : false; 3314 } 3315 3316 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 3317 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 3318 return true; 3319 const auto *F = cast<FunctionDecl>(GD.getDecl()); 3320 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 3321 return false; 3322 3323 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 3324 // Check whether it would be safe to inline this dllimport function. 3325 DLLImportFunctionVisitor Visitor; 3326 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 3327 if (!Visitor.SafeToInline) 3328 return false; 3329 3330 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 3331 // Implicit destructor invocations aren't captured in the AST, so the 3332 // check above can't see them. Check for them manually here. 3333 for (const Decl *Member : Dtor->getParent()->decls()) 3334 if (isa<FieldDecl>(Member)) 3335 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 3336 return false; 3337 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 3338 if (HasNonDllImportDtor(B.getType())) 3339 return false; 3340 } 3341 } 3342 3343 // Inline builtins declaration must be emitted. They often are fortified 3344 // functions. 3345 if (F->isInlineBuiltinDeclaration()) 3346 return true; 3347 3348 // PR9614. Avoid cases where the source code is lying to us. An available 3349 // externally function should have an equivalent function somewhere else, 3350 // but a function that calls itself through asm label/`__builtin_` trickery is 3351 // clearly not equivalent to the real implementation. 3352 // This happens in glibc's btowc and in some configure checks. 3353 return !isTriviallyRecursive(F); 3354 } 3355 3356 bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 3357 return CodeGenOpts.OptimizationLevel > 0; 3358 } 3359 3360 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 3361 llvm::GlobalValue *GV) { 3362 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3363 3364 if (FD->isCPUSpecificMultiVersion()) { 3365 auto *Spec = FD->getAttr<CPUSpecificAttr>(); 3366 for (unsigned I = 0; I < Spec->cpus_size(); ++I) 3367 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 3368 } else if (FD->isTargetClonesMultiVersion()) { 3369 auto *Clone = FD->getAttr<TargetClonesAttr>(); 3370 for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I) 3371 if (Clone->isFirstOfVersion(I)) 3372 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 3373 // Ensure that the resolver function is also emitted. 3374 GetOrCreateMultiVersionResolver(GD); 3375 } else 3376 EmitGlobalFunctionDefinition(GD, GV); 3377 } 3378 3379 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 3380 const auto *D = cast<ValueDecl>(GD.getDecl()); 3381 3382 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 3383 Context.getSourceManager(), 3384 "Generating code for declaration"); 3385 3386 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3387 // At -O0, don't generate IR for functions with available_externally 3388 // linkage. 3389 if (!shouldEmitFunction(GD)) 3390 return; 3391 3392 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 3393 std::string Name; 3394 llvm::raw_string_ostream OS(Name); 3395 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 3396 /*Qualified=*/true); 3397 return Name; 3398 }); 3399 3400 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 3401 // Make sure to emit the definition(s) before we emit the thunks. 3402 // This is necessary for the generation of certain thunks. 3403 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 3404 ABI->emitCXXStructor(GD); 3405 else if (FD->isMultiVersion()) 3406 EmitMultiVersionFunctionDefinition(GD, GV); 3407 else 3408 EmitGlobalFunctionDefinition(GD, GV); 3409 3410 if (Method->isVirtual()) 3411 getVTables().EmitThunks(GD); 3412 3413 return; 3414 } 3415 3416 if (FD->isMultiVersion()) 3417 return EmitMultiVersionFunctionDefinition(GD, GV); 3418 return EmitGlobalFunctionDefinition(GD, GV); 3419 } 3420 3421 if (const auto *VD = dyn_cast<VarDecl>(D)) 3422 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 3423 3424 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 3425 } 3426 3427 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3428 llvm::Function *NewFn); 3429 3430 static unsigned 3431 TargetMVPriority(const TargetInfo &TI, 3432 const CodeGenFunction::MultiVersionResolverOption &RO) { 3433 unsigned Priority = 0; 3434 for (StringRef Feat : RO.Conditions.Features) 3435 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 3436 3437 if (!RO.Conditions.Architecture.empty()) 3438 Priority = std::max( 3439 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 3440 return Priority; 3441 } 3442 3443 // Multiversion functions should be at most 'WeakODRLinkage' so that a different 3444 // TU can forward declare the function without causing problems. Particularly 3445 // in the cases of CPUDispatch, this causes issues. This also makes sure we 3446 // work with internal linkage functions, so that the same function name can be 3447 // used with internal linkage in multiple TUs. 3448 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, 3449 GlobalDecl GD) { 3450 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 3451 if (FD->getFormalLinkage() == InternalLinkage) 3452 return llvm::GlobalValue::InternalLinkage; 3453 return llvm::GlobalValue::WeakODRLinkage; 3454 } 3455 3456 void CodeGenModule::emitMultiVersionFunctions() { 3457 std::vector<GlobalDecl> MVFuncsToEmit; 3458 MultiVersionFuncs.swap(MVFuncsToEmit); 3459 for (GlobalDecl GD : MVFuncsToEmit) { 3460 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3461 assert(FD && "Expected a FunctionDecl"); 3462 3463 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3464 if (FD->isTargetMultiVersion()) { 3465 getContext().forEachMultiversionedFunctionVersion( 3466 FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 3467 GlobalDecl CurGD{ 3468 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 3469 StringRef MangledName = getMangledName(CurGD); 3470 llvm::Constant *Func = GetGlobalValue(MangledName); 3471 if (!Func) { 3472 if (CurFD->isDefined()) { 3473 EmitGlobalFunctionDefinition(CurGD, nullptr); 3474 Func = GetGlobalValue(MangledName); 3475 } else { 3476 const CGFunctionInfo &FI = 3477 getTypes().arrangeGlobalDeclaration(GD); 3478 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3479 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 3480 /*DontDefer=*/false, ForDefinition); 3481 } 3482 assert(Func && "This should have just been created"); 3483 } 3484 3485 const auto *TA = CurFD->getAttr<TargetAttr>(); 3486 llvm::SmallVector<StringRef, 8> Feats; 3487 TA->getAddedFeatures(Feats); 3488 3489 Options.emplace_back(cast<llvm::Function>(Func), 3490 TA->getArchitecture(), Feats); 3491 }); 3492 } else if (FD->isTargetClonesMultiVersion()) { 3493 const auto *TC = FD->getAttr<TargetClonesAttr>(); 3494 for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size(); 3495 ++VersionIndex) { 3496 if (!TC->isFirstOfVersion(VersionIndex)) 3497 continue; 3498 GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD), 3499 VersionIndex}; 3500 StringRef Version = TC->getFeatureStr(VersionIndex); 3501 StringRef MangledName = getMangledName(CurGD); 3502 llvm::Constant *Func = GetGlobalValue(MangledName); 3503 if (!Func) { 3504 if (FD->isDefined()) { 3505 EmitGlobalFunctionDefinition(CurGD, nullptr); 3506 Func = GetGlobalValue(MangledName); 3507 } else { 3508 const CGFunctionInfo &FI = 3509 getTypes().arrangeGlobalDeclaration(CurGD); 3510 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3511 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 3512 /*DontDefer=*/false, ForDefinition); 3513 } 3514 assert(Func && "This should have just been created"); 3515 } 3516 3517 StringRef Architecture; 3518 llvm::SmallVector<StringRef, 1> Feature; 3519 3520 if (Version.startswith("arch=")) 3521 Architecture = Version.drop_front(sizeof("arch=") - 1); 3522 else if (Version != "default") 3523 Feature.push_back(Version); 3524 3525 Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature); 3526 } 3527 } else { 3528 assert(0 && "Expected a target or target_clones multiversion function"); 3529 continue; 3530 } 3531 3532 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD); 3533 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) 3534 ResolverConstant = IFunc->getResolver(); 3535 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant); 3536 3537 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3538 3539 if (supportsCOMDAT()) 3540 ResolverFunc->setComdat( 3541 getModule().getOrInsertComdat(ResolverFunc->getName())); 3542 3543 const TargetInfo &TI = getTarget(); 3544 llvm::stable_sort( 3545 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 3546 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3547 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 3548 }); 3549 CodeGenFunction CGF(*this); 3550 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3551 } 3552 3553 // Ensure that any additions to the deferred decls list caused by emitting a 3554 // variant are emitted. This can happen when the variant itself is inline and 3555 // calls a function without linkage. 3556 if (!MVFuncsToEmit.empty()) 3557 EmitDeferred(); 3558 3559 // Ensure that any additions to the multiversion funcs list from either the 3560 // deferred decls or the multiversion functions themselves are emitted. 3561 if (!MultiVersionFuncs.empty()) 3562 emitMultiVersionFunctions(); 3563 } 3564 3565 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 3566 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3567 assert(FD && "Not a FunctionDecl?"); 3568 assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?"); 3569 const auto *DD = FD->getAttr<CPUDispatchAttr>(); 3570 assert(DD && "Not a cpu_dispatch Function?"); 3571 3572 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3573 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 3574 3575 StringRef ResolverName = getMangledName(GD); 3576 UpdateMultiVersionNames(GD, FD, ResolverName); 3577 3578 llvm::Type *ResolverType; 3579 GlobalDecl ResolverGD; 3580 if (getTarget().supportsIFunc()) { 3581 ResolverType = llvm::FunctionType::get( 3582 llvm::PointerType::get(DeclTy, 3583 Context.getTargetAddressSpace(FD->getType())), 3584 false); 3585 } 3586 else { 3587 ResolverType = DeclTy; 3588 ResolverGD = GD; 3589 } 3590 3591 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 3592 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 3593 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3594 if (supportsCOMDAT()) 3595 ResolverFunc->setComdat( 3596 getModule().getOrInsertComdat(ResolverFunc->getName())); 3597 3598 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3599 const TargetInfo &Target = getTarget(); 3600 unsigned Index = 0; 3601 for (const IdentifierInfo *II : DD->cpus()) { 3602 // Get the name of the target function so we can look it up/create it. 3603 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 3604 getCPUSpecificMangling(*this, II->getName()); 3605 3606 llvm::Constant *Func = GetGlobalValue(MangledName); 3607 3608 if (!Func) { 3609 GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 3610 if (ExistingDecl.getDecl() && 3611 ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 3612 EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 3613 Func = GetGlobalValue(MangledName); 3614 } else { 3615 if (!ExistingDecl.getDecl()) 3616 ExistingDecl = GD.getWithMultiVersionIndex(Index); 3617 3618 Func = GetOrCreateLLVMFunction( 3619 MangledName, DeclTy, ExistingDecl, 3620 /*ForVTable=*/false, /*DontDefer=*/true, 3621 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 3622 } 3623 } 3624 3625 llvm::SmallVector<StringRef, 32> Features; 3626 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 3627 llvm::transform(Features, Features.begin(), 3628 [](StringRef Str) { return Str.substr(1); }); 3629 llvm::erase_if(Features, [&Target](StringRef Feat) { 3630 return !Target.validateCpuSupports(Feat); 3631 }); 3632 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 3633 ++Index; 3634 } 3635 3636 llvm::stable_sort( 3637 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 3638 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3639 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > 3640 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); 3641 }); 3642 3643 // If the list contains multiple 'default' versions, such as when it contains 3644 // 'pentium' and 'generic', don't emit the call to the generic one (since we 3645 // always run on at least a 'pentium'). We do this by deleting the 'least 3646 // advanced' (read, lowest mangling letter). 3647 while (Options.size() > 1 && 3648 llvm::X86::getCpuSupportsMask( 3649 (Options.end() - 2)->Conditions.Features) == 0) { 3650 StringRef LHSName = (Options.end() - 2)->Function->getName(); 3651 StringRef RHSName = (Options.end() - 1)->Function->getName(); 3652 if (LHSName.compare(RHSName) < 0) 3653 Options.erase(Options.end() - 2); 3654 else 3655 Options.erase(Options.end() - 1); 3656 } 3657 3658 CodeGenFunction CGF(*this); 3659 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3660 3661 if (getTarget().supportsIFunc()) { 3662 llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD); 3663 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD)); 3664 3665 // Fix up function declarations that were created for cpu_specific before 3666 // cpu_dispatch was known 3667 if (!dyn_cast<llvm::GlobalIFunc>(IFunc)) { 3668 assert(cast<llvm::Function>(IFunc)->isDeclaration()); 3669 auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc, 3670 &getModule()); 3671 GI->takeName(IFunc); 3672 IFunc->replaceAllUsesWith(GI); 3673 IFunc->eraseFromParent(); 3674 IFunc = GI; 3675 } 3676 3677 std::string AliasName = getMangledNameImpl( 3678 *this, GD, FD, /*OmitMultiVersionMangling=*/true); 3679 llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 3680 if (!AliasFunc) { 3681 auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc, 3682 &getModule()); 3683 SetCommonAttributes(GD, GA); 3684 } 3685 } 3686 } 3687 3688 /// If a dispatcher for the specified mangled name is not in the module, create 3689 /// and return an llvm Function with the specified type. 3690 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) { 3691 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3692 assert(FD && "Not a FunctionDecl?"); 3693 3694 std::string MangledName = 3695 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 3696 3697 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 3698 // a separate resolver). 3699 std::string ResolverName = MangledName; 3700 if (getTarget().supportsIFunc()) 3701 ResolverName += ".ifunc"; 3702 else if (FD->isTargetMultiVersion()) 3703 ResolverName += ".resolver"; 3704 3705 // If the resolver has already been created, just return it. 3706 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 3707 return ResolverGV; 3708 3709 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3710 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 3711 3712 // The resolver needs to be created. For target and target_clones, defer 3713 // creation until the end of the TU. 3714 if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion()) 3715 MultiVersionFuncs.push_back(GD); 3716 3717 // For cpu_specific, don't create an ifunc yet because we don't know if the 3718 // cpu_dispatch will be emitted in this translation unit. 3719 if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) { 3720 llvm::Type *ResolverType = llvm::FunctionType::get( 3721 llvm::PointerType::get( 3722 DeclTy, getContext().getTargetAddressSpace(FD->getType())), 3723 false); 3724 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3725 MangledName + ".resolver", ResolverType, GlobalDecl{}, 3726 /*ForVTable=*/false); 3727 llvm::GlobalIFunc *GIF = 3728 llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), 3729 "", Resolver, &getModule()); 3730 GIF->setName(ResolverName); 3731 SetCommonAttributes(FD, GIF); 3732 3733 return GIF; 3734 } 3735 3736 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3737 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 3738 assert(isa<llvm::GlobalValue>(Resolver) && 3739 "Resolver should be created for the first time"); 3740 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 3741 return Resolver; 3742 } 3743 3744 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 3745 /// module, create and return an llvm Function with the specified type. If there 3746 /// is something in the module with the specified name, return it potentially 3747 /// bitcasted to the right type. 3748 /// 3749 /// If D is non-null, it specifies a decl that correspond to this. This is used 3750 /// to set the attributes on the function when it is first created. 3751 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 3752 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 3753 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 3754 ForDefinition_t IsForDefinition) { 3755 const Decl *D = GD.getDecl(); 3756 3757 // Any attempts to use a MultiVersion function should result in retrieving 3758 // the iFunc instead. Name Mangling will handle the rest of the changes. 3759 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 3760 // For the device mark the function as one that should be emitted. 3761 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 3762 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 3763 !DontDefer && !IsForDefinition) { 3764 if (const FunctionDecl *FDDef = FD->getDefinition()) { 3765 GlobalDecl GDDef; 3766 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 3767 GDDef = GlobalDecl(CD, GD.getCtorType()); 3768 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 3769 GDDef = GlobalDecl(DD, GD.getDtorType()); 3770 else 3771 GDDef = GlobalDecl(FDDef); 3772 EmitGlobal(GDDef); 3773 } 3774 } 3775 3776 if (FD->isMultiVersion()) { 3777 UpdateMultiVersionNames(GD, FD, MangledName); 3778 if (!IsForDefinition) 3779 return GetOrCreateMultiVersionResolver(GD); 3780 } 3781 } 3782 3783 // Lookup the entry, lazily creating it if necessary. 3784 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3785 if (Entry) { 3786 if (WeakRefReferences.erase(Entry)) { 3787 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 3788 if (FD && !FD->hasAttr<WeakAttr>()) 3789 Entry->setLinkage(llvm::Function::ExternalLinkage); 3790 } 3791 3792 // Handle dropped DLL attributes. 3793 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) { 3794 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3795 setDSOLocal(Entry); 3796 } 3797 3798 // If there are two attempts to define the same mangled name, issue an 3799 // error. 3800 if (IsForDefinition && !Entry->isDeclaration()) { 3801 GlobalDecl OtherGD; 3802 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 3803 // to make sure that we issue an error only once. 3804 if (lookupRepresentativeDecl(MangledName, OtherGD) && 3805 (GD.getCanonicalDecl().getDecl() != 3806 OtherGD.getCanonicalDecl().getDecl()) && 3807 DiagnosedConflictingDefinitions.insert(GD).second) { 3808 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3809 << MangledName; 3810 getDiags().Report(OtherGD.getDecl()->getLocation(), 3811 diag::note_previous_definition); 3812 } 3813 } 3814 3815 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 3816 (Entry->getValueType() == Ty)) { 3817 return Entry; 3818 } 3819 3820 // Make sure the result is of the correct type. 3821 // (If function is requested for a definition, we always need to create a new 3822 // function, not just return a bitcast.) 3823 if (!IsForDefinition) 3824 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 3825 } 3826 3827 // This function doesn't have a complete type (for example, the return 3828 // type is an incomplete struct). Use a fake type instead, and make 3829 // sure not to try to set attributes. 3830 bool IsIncompleteFunction = false; 3831 3832 llvm::FunctionType *FTy; 3833 if (isa<llvm::FunctionType>(Ty)) { 3834 FTy = cast<llvm::FunctionType>(Ty); 3835 } else { 3836 FTy = llvm::FunctionType::get(VoidTy, false); 3837 IsIncompleteFunction = true; 3838 } 3839 3840 llvm::Function *F = 3841 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 3842 Entry ? StringRef() : MangledName, &getModule()); 3843 3844 // If we already created a function with the same mangled name (but different 3845 // type) before, take its name and add it to the list of functions to be 3846 // replaced with F at the end of CodeGen. 3847 // 3848 // This happens if there is a prototype for a function (e.g. "int f()") and 3849 // then a definition of a different type (e.g. "int f(int x)"). 3850 if (Entry) { 3851 F->takeName(Entry); 3852 3853 // This might be an implementation of a function without a prototype, in 3854 // which case, try to do special replacement of calls which match the new 3855 // prototype. The really key thing here is that we also potentially drop 3856 // arguments from the call site so as to make a direct call, which makes the 3857 // inliner happier and suppresses a number of optimizer warnings (!) about 3858 // dropping arguments. 3859 if (!Entry->use_empty()) { 3860 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 3861 Entry->removeDeadConstantUsers(); 3862 } 3863 3864 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 3865 F, Entry->getValueType()->getPointerTo()); 3866 addGlobalValReplacement(Entry, BC); 3867 } 3868 3869 assert(F->getName() == MangledName && "name was uniqued!"); 3870 if (D) 3871 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 3872 if (ExtraAttrs.hasFnAttrs()) { 3873 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); 3874 F->addFnAttrs(B); 3875 } 3876 3877 if (!DontDefer) { 3878 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 3879 // each other bottoming out with the base dtor. Therefore we emit non-base 3880 // dtors on usage, even if there is no dtor definition in the TU. 3881 if (D && isa<CXXDestructorDecl>(D) && 3882 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 3883 GD.getDtorType())) 3884 addDeferredDeclToEmit(GD); 3885 3886 // This is the first use or definition of a mangled name. If there is a 3887 // deferred decl with this name, remember that we need to emit it at the end 3888 // of the file. 3889 auto DDI = DeferredDecls.find(MangledName); 3890 if (DDI != DeferredDecls.end()) { 3891 // Move the potentially referenced deferred decl to the 3892 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 3893 // don't need it anymore). 3894 addDeferredDeclToEmit(DDI->second); 3895 DeferredDecls.erase(DDI); 3896 3897 // Otherwise, there are cases we have to worry about where we're 3898 // using a declaration for which we must emit a definition but where 3899 // we might not find a top-level definition: 3900 // - member functions defined inline in their classes 3901 // - friend functions defined inline in some class 3902 // - special member functions with implicit definitions 3903 // If we ever change our AST traversal to walk into class methods, 3904 // this will be unnecessary. 3905 // 3906 // We also don't emit a definition for a function if it's going to be an 3907 // entry in a vtable, unless it's already marked as used. 3908 } else if (getLangOpts().CPlusPlus && D) { 3909 // Look for a declaration that's lexically in a record. 3910 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 3911 FD = FD->getPreviousDecl()) { 3912 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 3913 if (FD->doesThisDeclarationHaveABody()) { 3914 addDeferredDeclToEmit(GD.getWithDecl(FD)); 3915 break; 3916 } 3917 } 3918 } 3919 } 3920 } 3921 3922 // Make sure the result is of the requested type. 3923 if (!IsIncompleteFunction) { 3924 assert(F->getFunctionType() == Ty); 3925 return F; 3926 } 3927 3928 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3929 return llvm::ConstantExpr::getBitCast(F, PTy); 3930 } 3931 3932 /// GetAddrOfFunction - Return the address of the given function. If Ty is 3933 /// non-null, then this function will use the specified type if it has to 3934 /// create it (this occurs when we see a definition of the function). 3935 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 3936 llvm::Type *Ty, 3937 bool ForVTable, 3938 bool DontDefer, 3939 ForDefinition_t IsForDefinition) { 3940 assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() && 3941 "consteval function should never be emitted"); 3942 // If there was no specific requested type, just convert it now. 3943 if (!Ty) { 3944 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3945 Ty = getTypes().ConvertType(FD->getType()); 3946 } 3947 3948 // Devirtualized destructor calls may come through here instead of via 3949 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 3950 // of the complete destructor when necessary. 3951 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 3952 if (getTarget().getCXXABI().isMicrosoft() && 3953 GD.getDtorType() == Dtor_Complete && 3954 DD->getParent()->getNumVBases() == 0) 3955 GD = GlobalDecl(DD, Dtor_Base); 3956 } 3957 3958 StringRef MangledName = getMangledName(GD); 3959 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 3960 /*IsThunk=*/false, llvm::AttributeList(), 3961 IsForDefinition); 3962 // Returns kernel handle for HIP kernel stub function. 3963 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && 3964 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { 3965 auto *Handle = getCUDARuntime().getKernelHandle( 3966 cast<llvm::Function>(F->stripPointerCasts()), GD); 3967 if (IsForDefinition) 3968 return F; 3969 return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo()); 3970 } 3971 return F; 3972 } 3973 3974 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { 3975 llvm::GlobalValue *F = 3976 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts()); 3977 3978 return llvm::ConstantExpr::getBitCast(llvm::NoCFIValue::get(F), 3979 llvm::Type::getInt8PtrTy(VMContext)); 3980 } 3981 3982 static const FunctionDecl * 3983 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 3984 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 3985 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3986 3987 IdentifierInfo &CII = C.Idents.get(Name); 3988 for (const auto *Result : DC->lookup(&CII)) 3989 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 3990 return FD; 3991 3992 if (!C.getLangOpts().CPlusPlus) 3993 return nullptr; 3994 3995 // Demangle the premangled name from getTerminateFn() 3996 IdentifierInfo &CXXII = 3997 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 3998 ? C.Idents.get("terminate") 3999 : C.Idents.get(Name); 4000 4001 for (const auto &N : {"__cxxabiv1", "std"}) { 4002 IdentifierInfo &NS = C.Idents.get(N); 4003 for (const auto *Result : DC->lookup(&NS)) { 4004 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 4005 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 4006 for (const auto *Result : LSD->lookup(&NS)) 4007 if ((ND = dyn_cast<NamespaceDecl>(Result))) 4008 break; 4009 4010 if (ND) 4011 for (const auto *Result : ND->lookup(&CXXII)) 4012 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4013 return FD; 4014 } 4015 } 4016 4017 return nullptr; 4018 } 4019 4020 /// CreateRuntimeFunction - Create a new runtime function with the specified 4021 /// type and name. 4022 llvm::FunctionCallee 4023 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 4024 llvm::AttributeList ExtraAttrs, bool Local, 4025 bool AssumeConvergent) { 4026 if (AssumeConvergent) { 4027 ExtraAttrs = 4028 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 4029 } 4030 4031 llvm::Constant *C = 4032 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 4033 /*DontDefer=*/false, /*IsThunk=*/false, 4034 ExtraAttrs); 4035 4036 if (auto *F = dyn_cast<llvm::Function>(C)) { 4037 if (F->empty()) { 4038 F->setCallingConv(getRuntimeCC()); 4039 4040 // In Windows Itanium environments, try to mark runtime functions 4041 // dllimport. For Mingw and MSVC, don't. We don't really know if the user 4042 // will link their standard library statically or dynamically. Marking 4043 // functions imported when they are not imported can cause linker errors 4044 // and warnings. 4045 if (!Local && getTriple().isWindowsItaniumEnvironment() && 4046 !getCodeGenOpts().LTOVisibilityPublicStd) { 4047 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 4048 if (!FD || FD->hasAttr<DLLImportAttr>()) { 4049 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 4050 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 4051 } 4052 } 4053 setDSOLocal(F); 4054 } 4055 } 4056 4057 return {FTy, C}; 4058 } 4059 4060 /// isTypeConstant - Determine whether an object of this type can be emitted 4061 /// as a constant. 4062 /// 4063 /// If ExcludeCtor is true, the duration when the object's constructor runs 4064 /// will not be considered. The caller will need to verify that the object is 4065 /// not written to during its construction. 4066 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 4067 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 4068 return false; 4069 4070 if (Context.getLangOpts().CPlusPlus) { 4071 if (const CXXRecordDecl *Record 4072 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 4073 return ExcludeCtor && !Record->hasMutableFields() && 4074 Record->hasTrivialDestructor(); 4075 } 4076 4077 return true; 4078 } 4079 4080 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 4081 /// create and return an llvm GlobalVariable with the specified type and address 4082 /// space. If there is something in the module with the specified name, return 4083 /// it potentially bitcasted to the right type. 4084 /// 4085 /// If D is non-null, it specifies a decl that correspond to this. This is used 4086 /// to set the attributes on the global when it is first created. 4087 /// 4088 /// If IsForDefinition is true, it is guaranteed that an actual global with 4089 /// type Ty will be returned, not conversion of a variable with the same 4090 /// mangled name but some other type. 4091 llvm::Constant * 4092 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4093 LangAS AddrSpace, const VarDecl *D, 4094 ForDefinition_t IsForDefinition) { 4095 // Lookup the entry, lazily creating it if necessary. 4096 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4097 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 4098 if (Entry) { 4099 if (WeakRefReferences.erase(Entry)) { 4100 if (D && !D->hasAttr<WeakAttr>()) 4101 Entry->setLinkage(llvm::Function::ExternalLinkage); 4102 } 4103 4104 // Handle dropped DLL attributes. 4105 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 4106 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4107 4108 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 4109 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 4110 4111 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 4112 return Entry; 4113 4114 // If there are two attempts to define the same mangled name, issue an 4115 // error. 4116 if (IsForDefinition && !Entry->isDeclaration()) { 4117 GlobalDecl OtherGD; 4118 const VarDecl *OtherD; 4119 4120 // Check that D is not yet in DiagnosedConflictingDefinitions is required 4121 // to make sure that we issue an error only once. 4122 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 4123 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 4124 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 4125 OtherD->hasInit() && 4126 DiagnosedConflictingDefinitions.insert(D).second) { 4127 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4128 << MangledName; 4129 getDiags().Report(OtherGD.getDecl()->getLocation(), 4130 diag::note_previous_definition); 4131 } 4132 } 4133 4134 // Make sure the result is of the correct type. 4135 if (Entry->getType()->getAddressSpace() != TargetAS) { 4136 return llvm::ConstantExpr::getAddrSpaceCast(Entry, 4137 Ty->getPointerTo(TargetAS)); 4138 } 4139 4140 // (If global is requested for a definition, we always need to create a new 4141 // global, not just return a bitcast.) 4142 if (!IsForDefinition) 4143 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS)); 4144 } 4145 4146 auto DAddrSpace = GetGlobalVarAddressSpace(D); 4147 4148 auto *GV = new llvm::GlobalVariable( 4149 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 4150 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 4151 getContext().getTargetAddressSpace(DAddrSpace)); 4152 4153 // If we already created a global with the same mangled name (but different 4154 // type) before, take its name and remove it from its parent. 4155 if (Entry) { 4156 GV->takeName(Entry); 4157 4158 if (!Entry->use_empty()) { 4159 llvm::Constant *NewPtrForOldDecl = 4160 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 4161 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4162 } 4163 4164 Entry->eraseFromParent(); 4165 } 4166 4167 // This is the first use or definition of a mangled name. If there is a 4168 // deferred decl with this name, remember that we need to emit it at the end 4169 // of the file. 4170 auto DDI = DeferredDecls.find(MangledName); 4171 if (DDI != DeferredDecls.end()) { 4172 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 4173 // list, and remove it from DeferredDecls (since we don't need it anymore). 4174 addDeferredDeclToEmit(DDI->second); 4175 DeferredDecls.erase(DDI); 4176 } 4177 4178 // Handle things which are present even on external declarations. 4179 if (D) { 4180 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 4181 getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 4182 4183 // FIXME: This code is overly simple and should be merged with other global 4184 // handling. 4185 GV->setConstant(isTypeConstant(D->getType(), false)); 4186 4187 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4188 4189 setLinkageForGV(GV, D); 4190 4191 if (D->getTLSKind()) { 4192 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4193 CXXThreadLocals.push_back(D); 4194 setTLSMode(GV, *D); 4195 } 4196 4197 setGVProperties(GV, D); 4198 4199 // If required by the ABI, treat declarations of static data members with 4200 // inline initializers as definitions. 4201 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 4202 EmitGlobalVarDefinition(D); 4203 } 4204 4205 // Emit section information for extern variables. 4206 if (D->hasExternalStorage()) { 4207 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 4208 GV->setSection(SA->getName()); 4209 } 4210 4211 // Handle XCore specific ABI requirements. 4212 if (getTriple().getArch() == llvm::Triple::xcore && 4213 D->getLanguageLinkage() == CLanguageLinkage && 4214 D->getType().isConstant(Context) && 4215 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 4216 GV->setSection(".cp.rodata"); 4217 4218 // Check if we a have a const declaration with an initializer, we may be 4219 // able to emit it as available_externally to expose it's value to the 4220 // optimizer. 4221 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 4222 D->getType().isConstQualified() && !GV->hasInitializer() && 4223 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 4224 const auto *Record = 4225 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 4226 bool HasMutableFields = Record && Record->hasMutableFields(); 4227 if (!HasMutableFields) { 4228 const VarDecl *InitDecl; 4229 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4230 if (InitExpr) { 4231 ConstantEmitter emitter(*this); 4232 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 4233 if (Init) { 4234 auto *InitType = Init->getType(); 4235 if (GV->getValueType() != InitType) { 4236 // The type of the initializer does not match the definition. 4237 // This happens when an initializer has a different type from 4238 // the type of the global (because of padding at the end of a 4239 // structure for instance). 4240 GV->setName(StringRef()); 4241 // Make a new global with the correct type, this is now guaranteed 4242 // to work. 4243 auto *NewGV = cast<llvm::GlobalVariable>( 4244 GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4245 ->stripPointerCasts()); 4246 4247 // Erase the old global, since it is no longer used. 4248 GV->eraseFromParent(); 4249 GV = NewGV; 4250 } else { 4251 GV->setInitializer(Init); 4252 GV->setConstant(true); 4253 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 4254 } 4255 emitter.finalize(GV); 4256 } 4257 } 4258 } 4259 } 4260 } 4261 4262 if (GV->isDeclaration()) { 4263 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4264 // External HIP managed variables needed to be recorded for transformation 4265 // in both device and host compilations. 4266 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4267 D->hasExternalStorage()) 4268 getCUDARuntime().handleVarRegistration(D, *GV); 4269 } 4270 4271 LangAS ExpectedAS = 4272 D ? D->getType().getAddressSpace() 4273 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4274 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4275 if (DAddrSpace != ExpectedAS) { 4276 return getTargetCodeGenInfo().performAddrSpaceCast( 4277 *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS)); 4278 } 4279 4280 return GV; 4281 } 4282 4283 llvm::Constant * 4284 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 4285 const Decl *D = GD.getDecl(); 4286 4287 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 4288 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 4289 /*DontDefer=*/false, IsForDefinition); 4290 4291 if (isa<CXXMethodDecl>(D)) { 4292 auto FInfo = 4293 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 4294 auto Ty = getTypes().GetFunctionType(*FInfo); 4295 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4296 IsForDefinition); 4297 } 4298 4299 if (isa<FunctionDecl>(D)) { 4300 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4301 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4302 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4303 IsForDefinition); 4304 } 4305 4306 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 4307 } 4308 4309 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 4310 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 4311 unsigned Alignment) { 4312 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 4313 llvm::GlobalVariable *OldGV = nullptr; 4314 4315 if (GV) { 4316 // Check if the variable has the right type. 4317 if (GV->getValueType() == Ty) 4318 return GV; 4319 4320 // Because C++ name mangling, the only way we can end up with an already 4321 // existing global with the same name is if it has been declared extern "C". 4322 assert(GV->isDeclaration() && "Declaration has wrong type!"); 4323 OldGV = GV; 4324 } 4325 4326 // Create a new variable. 4327 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 4328 Linkage, nullptr, Name); 4329 4330 if (OldGV) { 4331 // Replace occurrences of the old variable if needed. 4332 GV->takeName(OldGV); 4333 4334 if (!OldGV->use_empty()) { 4335 llvm::Constant *NewPtrForOldDecl = 4336 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 4337 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 4338 } 4339 4340 OldGV->eraseFromParent(); 4341 } 4342 4343 if (supportsCOMDAT() && GV->isWeakForLinker() && 4344 !GV->hasAvailableExternallyLinkage()) 4345 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 4346 4347 GV->setAlignment(llvm::MaybeAlign(Alignment)); 4348 4349 return GV; 4350 } 4351 4352 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 4353 /// given global variable. If Ty is non-null and if the global doesn't exist, 4354 /// then it will be created with the specified type instead of whatever the 4355 /// normal requested type would be. If IsForDefinition is true, it is guaranteed 4356 /// that an actual global with type Ty will be returned, not conversion of a 4357 /// variable with the same mangled name but some other type. 4358 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 4359 llvm::Type *Ty, 4360 ForDefinition_t IsForDefinition) { 4361 assert(D->hasGlobalStorage() && "Not a global variable"); 4362 QualType ASTTy = D->getType(); 4363 if (!Ty) 4364 Ty = getTypes().ConvertTypeForMem(ASTTy); 4365 4366 StringRef MangledName = getMangledName(D); 4367 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 4368 IsForDefinition); 4369 } 4370 4371 /// CreateRuntimeVariable - Create a new runtime global variable with the 4372 /// specified type and name. 4373 llvm::Constant * 4374 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 4375 StringRef Name) { 4376 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 4377 : LangAS::Default; 4378 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 4379 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 4380 return Ret; 4381 } 4382 4383 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 4384 assert(!D->getInit() && "Cannot emit definite definitions here!"); 4385 4386 StringRef MangledName = getMangledName(D); 4387 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 4388 4389 // We already have a definition, not declaration, with the same mangled name. 4390 // Emitting of declaration is not required (and actually overwrites emitted 4391 // definition). 4392 if (GV && !GV->isDeclaration()) 4393 return; 4394 4395 // If we have not seen a reference to this variable yet, place it into the 4396 // deferred declarations table to be emitted if needed later. 4397 if (!MustBeEmitted(D) && !GV) { 4398 DeferredDecls[MangledName] = D; 4399 return; 4400 } 4401 4402 // The tentative definition is the only definition. 4403 EmitGlobalVarDefinition(D); 4404 } 4405 4406 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 4407 EmitExternalVarDeclaration(D); 4408 } 4409 4410 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 4411 return Context.toCharUnitsFromBits( 4412 getDataLayout().getTypeStoreSizeInBits(Ty)); 4413 } 4414 4415 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 4416 if (LangOpts.OpenCL) { 4417 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 4418 assert(AS == LangAS::opencl_global || 4419 AS == LangAS::opencl_global_device || 4420 AS == LangAS::opencl_global_host || 4421 AS == LangAS::opencl_constant || 4422 AS == LangAS::opencl_local || 4423 AS >= LangAS::FirstTargetAddressSpace); 4424 return AS; 4425 } 4426 4427 if (LangOpts.SYCLIsDevice && 4428 (!D || D->getType().getAddressSpace() == LangAS::Default)) 4429 return LangAS::sycl_global; 4430 4431 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 4432 if (D && D->hasAttr<CUDAConstantAttr>()) 4433 return LangAS::cuda_constant; 4434 else if (D && D->hasAttr<CUDASharedAttr>()) 4435 return LangAS::cuda_shared; 4436 else if (D && D->hasAttr<CUDADeviceAttr>()) 4437 return LangAS::cuda_device; 4438 else if (D && D->getType().isConstQualified()) 4439 return LangAS::cuda_constant; 4440 else 4441 return LangAS::cuda_device; 4442 } 4443 4444 if (LangOpts.OpenMP) { 4445 LangAS AS; 4446 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 4447 return AS; 4448 } 4449 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 4450 } 4451 4452 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 4453 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 4454 if (LangOpts.OpenCL) 4455 return LangAS::opencl_constant; 4456 if (LangOpts.SYCLIsDevice) 4457 return LangAS::sycl_global; 4458 if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) 4459 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) 4460 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up 4461 // with OpVariable instructions with Generic storage class which is not 4462 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V 4463 // UniformConstant storage class is not viable as pointers to it may not be 4464 // casted to Generic pointers which are used to model HIP's "flat" pointers. 4465 return LangAS::cuda_device; 4466 if (auto AS = getTarget().getConstantAddressSpace()) 4467 return AS.getValue(); 4468 return LangAS::Default; 4469 } 4470 4471 // In address space agnostic languages, string literals are in default address 4472 // space in AST. However, certain targets (e.g. amdgcn) request them to be 4473 // emitted in constant address space in LLVM IR. To be consistent with other 4474 // parts of AST, string literal global variables in constant address space 4475 // need to be casted to default address space before being put into address 4476 // map and referenced by other part of CodeGen. 4477 // In OpenCL, string literals are in constant address space in AST, therefore 4478 // they should not be casted to default address space. 4479 static llvm::Constant * 4480 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 4481 llvm::GlobalVariable *GV) { 4482 llvm::Constant *Cast = GV; 4483 if (!CGM.getLangOpts().OpenCL) { 4484 auto AS = CGM.GetGlobalConstantAddressSpace(); 4485 if (AS != LangAS::Default) 4486 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 4487 CGM, GV, AS, LangAS::Default, 4488 GV->getValueType()->getPointerTo( 4489 CGM.getContext().getTargetAddressSpace(LangAS::Default))); 4490 } 4491 return Cast; 4492 } 4493 4494 template<typename SomeDecl> 4495 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 4496 llvm::GlobalValue *GV) { 4497 if (!getLangOpts().CPlusPlus) 4498 return; 4499 4500 // Must have 'used' attribute, or else inline assembly can't rely on 4501 // the name existing. 4502 if (!D->template hasAttr<UsedAttr>()) 4503 return; 4504 4505 // Must have internal linkage and an ordinary name. 4506 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 4507 return; 4508 4509 // Must be in an extern "C" context. Entities declared directly within 4510 // a record are not extern "C" even if the record is in such a context. 4511 const SomeDecl *First = D->getFirstDecl(); 4512 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 4513 return; 4514 4515 // OK, this is an internal linkage entity inside an extern "C" linkage 4516 // specification. Make a note of that so we can give it the "expected" 4517 // mangled name if nothing else is using that name. 4518 std::pair<StaticExternCMap::iterator, bool> R = 4519 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 4520 4521 // If we have multiple internal linkage entities with the same name 4522 // in extern "C" regions, none of them gets that name. 4523 if (!R.second) 4524 R.first->second = nullptr; 4525 } 4526 4527 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 4528 if (!CGM.supportsCOMDAT()) 4529 return false; 4530 4531 if (D.hasAttr<SelectAnyAttr>()) 4532 return true; 4533 4534 GVALinkage Linkage; 4535 if (auto *VD = dyn_cast<VarDecl>(&D)) 4536 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 4537 else 4538 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 4539 4540 switch (Linkage) { 4541 case GVA_Internal: 4542 case GVA_AvailableExternally: 4543 case GVA_StrongExternal: 4544 return false; 4545 case GVA_DiscardableODR: 4546 case GVA_StrongODR: 4547 return true; 4548 } 4549 llvm_unreachable("No such linkage"); 4550 } 4551 4552 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 4553 llvm::GlobalObject &GO) { 4554 if (!shouldBeInCOMDAT(*this, D)) 4555 return; 4556 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 4557 } 4558 4559 /// Pass IsTentative as true if you want to create a tentative definition. 4560 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 4561 bool IsTentative) { 4562 // OpenCL global variables of sampler type are translated to function calls, 4563 // therefore no need to be translated. 4564 QualType ASTTy = D->getType(); 4565 if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 4566 return; 4567 4568 // If this is OpenMP device, check if it is legal to emit this global 4569 // normally. 4570 if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 4571 OpenMPRuntime->emitTargetGlobalVariable(D)) 4572 return; 4573 4574 llvm::TrackingVH<llvm::Constant> Init; 4575 bool NeedsGlobalCtor = false; 4576 bool NeedsGlobalDtor = 4577 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 4578 4579 const VarDecl *InitDecl; 4580 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4581 4582 Optional<ConstantEmitter> emitter; 4583 4584 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 4585 // as part of their declaration." Sema has already checked for 4586 // error cases, so we just need to set Init to UndefValue. 4587 bool IsCUDASharedVar = 4588 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 4589 // Shadows of initialized device-side global variables are also left 4590 // undefined. 4591 // Managed Variables should be initialized on both host side and device side. 4592 bool IsCUDAShadowVar = 4593 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4594 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 4595 D->hasAttr<CUDASharedAttr>()); 4596 bool IsCUDADeviceShadowVar = 4597 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4598 (D->getType()->isCUDADeviceBuiltinSurfaceType() || 4599 D->getType()->isCUDADeviceBuiltinTextureType()); 4600 if (getLangOpts().CUDA && 4601 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 4602 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4603 else if (D->hasAttr<LoaderUninitializedAttr>()) 4604 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4605 else if (!InitExpr) { 4606 // This is a tentative definition; tentative definitions are 4607 // implicitly initialized with { 0 }. 4608 // 4609 // Note that tentative definitions are only emitted at the end of 4610 // a translation unit, so they should never have incomplete 4611 // type. In addition, EmitTentativeDefinition makes sure that we 4612 // never attempt to emit a tentative definition if a real one 4613 // exists. A use may still exists, however, so we still may need 4614 // to do a RAUW. 4615 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 4616 Init = EmitNullConstant(D->getType()); 4617 } else { 4618 initializedGlobalDecl = GlobalDecl(D); 4619 emitter.emplace(*this); 4620 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 4621 if (!Initializer) { 4622 QualType T = InitExpr->getType(); 4623 if (D->getType()->isReferenceType()) 4624 T = D->getType(); 4625 4626 if (getLangOpts().CPlusPlus) { 4627 if (InitDecl->hasFlexibleArrayInit(getContext())) 4628 ErrorUnsupported(D, "flexible array initializer"); 4629 Init = EmitNullConstant(T); 4630 NeedsGlobalCtor = true; 4631 } else { 4632 ErrorUnsupported(D, "static initializer"); 4633 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 4634 } 4635 } else { 4636 Init = Initializer; 4637 // We don't need an initializer, so remove the entry for the delayed 4638 // initializer position (just in case this entry was delayed) if we 4639 // also don't need to register a destructor. 4640 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 4641 DelayedCXXInitPosition.erase(D); 4642 4643 #ifndef NDEBUG 4644 CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) + 4645 InitDecl->getFlexibleArrayInitChars(getContext()); 4646 CharUnits CstSize = CharUnits::fromQuantity( 4647 getDataLayout().getTypeAllocSize(Init->getType())); 4648 assert(VarSize == CstSize && "Emitted constant has unexpected size"); 4649 #endif 4650 } 4651 } 4652 4653 llvm::Type* InitType = Init->getType(); 4654 llvm::Constant *Entry = 4655 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 4656 4657 // Strip off pointer casts if we got them. 4658 Entry = Entry->stripPointerCasts(); 4659 4660 // Entry is now either a Function or GlobalVariable. 4661 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 4662 4663 // We have a definition after a declaration with the wrong type. 4664 // We must make a new GlobalVariable* and update everything that used OldGV 4665 // (a declaration or tentative definition) with the new GlobalVariable* 4666 // (which will be a definition). 4667 // 4668 // This happens if there is a prototype for a global (e.g. 4669 // "extern int x[];") and then a definition of a different type (e.g. 4670 // "int x[10];"). This also happens when an initializer has a different type 4671 // from the type of the global (this happens with unions). 4672 if (!GV || GV->getValueType() != InitType || 4673 GV->getType()->getAddressSpace() != 4674 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 4675 4676 // Move the old entry aside so that we'll create a new one. 4677 Entry->setName(StringRef()); 4678 4679 // Make a new global with the correct type, this is now guaranteed to work. 4680 GV = cast<llvm::GlobalVariable>( 4681 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4682 ->stripPointerCasts()); 4683 4684 // Replace all uses of the old global with the new global 4685 llvm::Constant *NewPtrForOldDecl = 4686 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 4687 Entry->getType()); 4688 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4689 4690 // Erase the old global, since it is no longer used. 4691 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 4692 } 4693 4694 MaybeHandleStaticInExternC(D, GV); 4695 4696 if (D->hasAttr<AnnotateAttr>()) 4697 AddGlobalAnnotations(D, GV); 4698 4699 // Set the llvm linkage type as appropriate. 4700 llvm::GlobalValue::LinkageTypes Linkage = 4701 getLLVMLinkageVarDefinition(D, GV->isConstant()); 4702 4703 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 4704 // the device. [...]" 4705 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 4706 // __device__, declares a variable that: [...] 4707 // Is accessible from all the threads within the grid and from the host 4708 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 4709 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 4710 if (GV && LangOpts.CUDA) { 4711 if (LangOpts.CUDAIsDevice) { 4712 if (Linkage != llvm::GlobalValue::InternalLinkage && 4713 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 4714 D->getType()->isCUDADeviceBuiltinSurfaceType() || 4715 D->getType()->isCUDADeviceBuiltinTextureType())) 4716 GV->setExternallyInitialized(true); 4717 } else { 4718 getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 4719 } 4720 getCUDARuntime().handleVarRegistration(D, *GV); 4721 } 4722 4723 GV->setInitializer(Init); 4724 if (emitter) 4725 emitter->finalize(GV); 4726 4727 // If it is safe to mark the global 'constant', do so now. 4728 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 4729 isTypeConstant(D->getType(), true)); 4730 4731 // If it is in a read-only section, mark it 'constant'. 4732 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4733 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 4734 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 4735 GV->setConstant(true); 4736 } 4737 4738 CharUnits AlignVal = getContext().getDeclAlign(D); 4739 // Check for alignment specifed in an 'omp allocate' directive. 4740 if (llvm::Optional<CharUnits> AlignValFromAllocate = 4741 getOMPAllocateAlignment(D)) 4742 AlignVal = AlignValFromAllocate.getValue(); 4743 GV->setAlignment(AlignVal.getAsAlign()); 4744 4745 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 4746 // function is only defined alongside the variable, not also alongside 4747 // callers. Normally, all accesses to a thread_local go through the 4748 // thread-wrapper in order to ensure initialization has occurred, underlying 4749 // variable will never be used other than the thread-wrapper, so it can be 4750 // converted to internal linkage. 4751 // 4752 // However, if the variable has the 'constinit' attribute, it _can_ be 4753 // referenced directly, without calling the thread-wrapper, so the linkage 4754 // must not be changed. 4755 // 4756 // Additionally, if the variable isn't plain external linkage, e.g. if it's 4757 // weak or linkonce, the de-duplication semantics are important to preserve, 4758 // so we don't change the linkage. 4759 if (D->getTLSKind() == VarDecl::TLS_Dynamic && 4760 Linkage == llvm::GlobalValue::ExternalLinkage && 4761 Context.getTargetInfo().getTriple().isOSDarwin() && 4762 !D->hasAttr<ConstInitAttr>()) 4763 Linkage = llvm::GlobalValue::InternalLinkage; 4764 4765 GV->setLinkage(Linkage); 4766 if (D->hasAttr<DLLImportAttr>()) 4767 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 4768 else if (D->hasAttr<DLLExportAttr>()) 4769 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 4770 else 4771 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 4772 4773 if (Linkage == llvm::GlobalVariable::CommonLinkage) { 4774 // common vars aren't constant even if declared const. 4775 GV->setConstant(false); 4776 // Tentative definition of global variables may be initialized with 4777 // non-zero null pointers. In this case they should have weak linkage 4778 // since common linkage must have zero initializer and must not have 4779 // explicit section therefore cannot have non-zero initial value. 4780 if (!GV->getInitializer()->isNullValue()) 4781 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 4782 } 4783 4784 setNonAliasAttributes(D, GV); 4785 4786 if (D->getTLSKind() && !GV->isThreadLocal()) { 4787 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4788 CXXThreadLocals.push_back(D); 4789 setTLSMode(GV, *D); 4790 } 4791 4792 maybeSetTrivialComdat(*D, *GV); 4793 4794 // Emit the initializer function if necessary. 4795 if (NeedsGlobalCtor || NeedsGlobalDtor) 4796 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 4797 4798 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 4799 4800 // Emit global variable debug information. 4801 if (CGDebugInfo *DI = getModuleDebugInfo()) 4802 if (getCodeGenOpts().hasReducedDebugInfo()) 4803 DI->EmitGlobalVariable(GV, D); 4804 } 4805 4806 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 4807 if (CGDebugInfo *DI = getModuleDebugInfo()) 4808 if (getCodeGenOpts().hasReducedDebugInfo()) { 4809 QualType ASTTy = D->getType(); 4810 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 4811 llvm::Constant *GV = 4812 GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 4813 DI->EmitExternalVariable( 4814 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 4815 } 4816 } 4817 4818 static bool isVarDeclStrongDefinition(const ASTContext &Context, 4819 CodeGenModule &CGM, const VarDecl *D, 4820 bool NoCommon) { 4821 // Don't give variables common linkage if -fno-common was specified unless it 4822 // was overridden by a NoCommon attribute. 4823 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 4824 return true; 4825 4826 // C11 6.9.2/2: 4827 // A declaration of an identifier for an object that has file scope without 4828 // an initializer, and without a storage-class specifier or with the 4829 // storage-class specifier static, constitutes a tentative definition. 4830 if (D->getInit() || D->hasExternalStorage()) 4831 return true; 4832 4833 // A variable cannot be both common and exist in a section. 4834 if (D->hasAttr<SectionAttr>()) 4835 return true; 4836 4837 // A variable cannot be both common and exist in a section. 4838 // We don't try to determine which is the right section in the front-end. 4839 // If no specialized section name is applicable, it will resort to default. 4840 if (D->hasAttr<PragmaClangBSSSectionAttr>() || 4841 D->hasAttr<PragmaClangDataSectionAttr>() || 4842 D->hasAttr<PragmaClangRelroSectionAttr>() || 4843 D->hasAttr<PragmaClangRodataSectionAttr>()) 4844 return true; 4845 4846 // Thread local vars aren't considered common linkage. 4847 if (D->getTLSKind()) 4848 return true; 4849 4850 // Tentative definitions marked with WeakImportAttr are true definitions. 4851 if (D->hasAttr<WeakImportAttr>()) 4852 return true; 4853 4854 // A variable cannot be both common and exist in a comdat. 4855 if (shouldBeInCOMDAT(CGM, *D)) 4856 return true; 4857 4858 // Declarations with a required alignment do not have common linkage in MSVC 4859 // mode. 4860 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4861 if (D->hasAttr<AlignedAttr>()) 4862 return true; 4863 QualType VarType = D->getType(); 4864 if (Context.isAlignmentRequired(VarType)) 4865 return true; 4866 4867 if (const auto *RT = VarType->getAs<RecordType>()) { 4868 const RecordDecl *RD = RT->getDecl(); 4869 for (const FieldDecl *FD : RD->fields()) { 4870 if (FD->isBitField()) 4871 continue; 4872 if (FD->hasAttr<AlignedAttr>()) 4873 return true; 4874 if (Context.isAlignmentRequired(FD->getType())) 4875 return true; 4876 } 4877 } 4878 } 4879 4880 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 4881 // common symbols, so symbols with greater alignment requirements cannot be 4882 // common. 4883 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 4884 // alignments for common symbols via the aligncomm directive, so this 4885 // restriction only applies to MSVC environments. 4886 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 4887 Context.getTypeAlignIfKnown(D->getType()) > 4888 Context.toBits(CharUnits::fromQuantity(32))) 4889 return true; 4890 4891 return false; 4892 } 4893 4894 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 4895 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 4896 if (Linkage == GVA_Internal) 4897 return llvm::Function::InternalLinkage; 4898 4899 if (D->hasAttr<WeakAttr>()) 4900 return llvm::GlobalVariable::WeakAnyLinkage; 4901 4902 if (const auto *FD = D->getAsFunction()) 4903 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 4904 return llvm::GlobalVariable::LinkOnceAnyLinkage; 4905 4906 // We are guaranteed to have a strong definition somewhere else, 4907 // so we can use available_externally linkage. 4908 if (Linkage == GVA_AvailableExternally) 4909 return llvm::GlobalValue::AvailableExternallyLinkage; 4910 4911 // Note that Apple's kernel linker doesn't support symbol 4912 // coalescing, so we need to avoid linkonce and weak linkages there. 4913 // Normally, this means we just map to internal, but for explicit 4914 // instantiations we'll map to external. 4915 4916 // In C++, the compiler has to emit a definition in every translation unit 4917 // that references the function. We should use linkonce_odr because 4918 // a) if all references in this translation unit are optimized away, we 4919 // don't need to codegen it. b) if the function persists, it needs to be 4920 // merged with other definitions. c) C++ has the ODR, so we know the 4921 // definition is dependable. 4922 if (Linkage == GVA_DiscardableODR) 4923 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 4924 : llvm::Function::InternalLinkage; 4925 4926 // An explicit instantiation of a template has weak linkage, since 4927 // explicit instantiations can occur in multiple translation units 4928 // and must all be equivalent. However, we are not allowed to 4929 // throw away these explicit instantiations. 4930 // 4931 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 4932 // so say that CUDA templates are either external (for kernels) or internal. 4933 // This lets llvm perform aggressive inter-procedural optimizations. For 4934 // -fgpu-rdc case, device function calls across multiple TU's are allowed, 4935 // therefore we need to follow the normal linkage paradigm. 4936 if (Linkage == GVA_StrongODR) { 4937 if (getLangOpts().AppleKext) 4938 return llvm::Function::ExternalLinkage; 4939 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 4940 !getLangOpts().GPURelocatableDeviceCode) 4941 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 4942 : llvm::Function::InternalLinkage; 4943 return llvm::Function::WeakODRLinkage; 4944 } 4945 4946 // C++ doesn't have tentative definitions and thus cannot have common 4947 // linkage. 4948 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 4949 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 4950 CodeGenOpts.NoCommon)) 4951 return llvm::GlobalVariable::CommonLinkage; 4952 4953 // selectany symbols are externally visible, so use weak instead of 4954 // linkonce. MSVC optimizes away references to const selectany globals, so 4955 // all definitions should be the same and ODR linkage should be used. 4956 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 4957 if (D->hasAttr<SelectAnyAttr>()) 4958 return llvm::GlobalVariable::WeakODRLinkage; 4959 4960 // Otherwise, we have strong external linkage. 4961 assert(Linkage == GVA_StrongExternal); 4962 return llvm::GlobalVariable::ExternalLinkage; 4963 } 4964 4965 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 4966 const VarDecl *VD, bool IsConstant) { 4967 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 4968 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 4969 } 4970 4971 /// Replace the uses of a function that was declared with a non-proto type. 4972 /// We want to silently drop extra arguments from call sites 4973 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 4974 llvm::Function *newFn) { 4975 // Fast path. 4976 if (old->use_empty()) return; 4977 4978 llvm::Type *newRetTy = newFn->getReturnType(); 4979 SmallVector<llvm::Value*, 4> newArgs; 4980 4981 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 4982 ui != ue; ) { 4983 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 4984 llvm::User *user = use->getUser(); 4985 4986 // Recognize and replace uses of bitcasts. Most calls to 4987 // unprototyped functions will use bitcasts. 4988 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 4989 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 4990 replaceUsesOfNonProtoConstant(bitcast, newFn); 4991 continue; 4992 } 4993 4994 // Recognize calls to the function. 4995 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 4996 if (!callSite) continue; 4997 if (!callSite->isCallee(&*use)) 4998 continue; 4999 5000 // If the return types don't match exactly, then we can't 5001 // transform this call unless it's dead. 5002 if (callSite->getType() != newRetTy && !callSite->use_empty()) 5003 continue; 5004 5005 // Get the call site's attribute list. 5006 SmallVector<llvm::AttributeSet, 8> newArgAttrs; 5007 llvm::AttributeList oldAttrs = callSite->getAttributes(); 5008 5009 // If the function was passed too few arguments, don't transform. 5010 unsigned newNumArgs = newFn->arg_size(); 5011 if (callSite->arg_size() < newNumArgs) 5012 continue; 5013 5014 // If extra arguments were passed, we silently drop them. 5015 // If any of the types mismatch, we don't transform. 5016 unsigned argNo = 0; 5017 bool dontTransform = false; 5018 for (llvm::Argument &A : newFn->args()) { 5019 if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 5020 dontTransform = true; 5021 break; 5022 } 5023 5024 // Add any parameter attributes. 5025 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 5026 argNo++; 5027 } 5028 if (dontTransform) 5029 continue; 5030 5031 // Okay, we can transform this. Create the new call instruction and copy 5032 // over the required information. 5033 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 5034 5035 // Copy over any operand bundles. 5036 SmallVector<llvm::OperandBundleDef, 1> newBundles; 5037 callSite->getOperandBundlesAsDefs(newBundles); 5038 5039 llvm::CallBase *newCall; 5040 if (isa<llvm::CallInst>(callSite)) { 5041 newCall = 5042 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 5043 } else { 5044 auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 5045 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 5046 oldInvoke->getUnwindDest(), newArgs, 5047 newBundles, "", callSite); 5048 } 5049 newArgs.clear(); // for the next iteration 5050 5051 if (!newCall->getType()->isVoidTy()) 5052 newCall->takeName(callSite); 5053 newCall->setAttributes( 5054 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 5055 oldAttrs.getRetAttrs(), newArgAttrs)); 5056 newCall->setCallingConv(callSite->getCallingConv()); 5057 5058 // Finally, remove the old call, replacing any uses with the new one. 5059 if (!callSite->use_empty()) 5060 callSite->replaceAllUsesWith(newCall); 5061 5062 // Copy debug location attached to CI. 5063 if (callSite->getDebugLoc()) 5064 newCall->setDebugLoc(callSite->getDebugLoc()); 5065 5066 callSite->eraseFromParent(); 5067 } 5068 } 5069 5070 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 5071 /// implement a function with no prototype, e.g. "int foo() {}". If there are 5072 /// existing call uses of the old function in the module, this adjusts them to 5073 /// call the new function directly. 5074 /// 5075 /// This is not just a cleanup: the always_inline pass requires direct calls to 5076 /// functions to be able to inline them. If there is a bitcast in the way, it 5077 /// won't inline them. Instcombine normally deletes these calls, but it isn't 5078 /// run at -O0. 5079 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 5080 llvm::Function *NewFn) { 5081 // If we're redefining a global as a function, don't transform it. 5082 if (!isa<llvm::Function>(Old)) return; 5083 5084 replaceUsesOfNonProtoConstant(Old, NewFn); 5085 } 5086 5087 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 5088 auto DK = VD->isThisDeclarationADefinition(); 5089 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 5090 return; 5091 5092 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 5093 // If we have a definition, this might be a deferred decl. If the 5094 // instantiation is explicit, make sure we emit it at the end. 5095 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 5096 GetAddrOfGlobalVar(VD); 5097 5098 EmitTopLevelDecl(VD); 5099 } 5100 5101 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 5102 llvm::GlobalValue *GV) { 5103 const auto *D = cast<FunctionDecl>(GD.getDecl()); 5104 5105 // Compute the function info and LLVM type. 5106 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 5107 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 5108 5109 // Get or create the prototype for the function. 5110 if (!GV || (GV->getValueType() != Ty)) 5111 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 5112 /*DontDefer=*/true, 5113 ForDefinition)); 5114 5115 // Already emitted. 5116 if (!GV->isDeclaration()) 5117 return; 5118 5119 // We need to set linkage and visibility on the function before 5120 // generating code for it because various parts of IR generation 5121 // want to propagate this information down (e.g. to local static 5122 // declarations). 5123 auto *Fn = cast<llvm::Function>(GV); 5124 setFunctionLinkage(GD, Fn); 5125 5126 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 5127 setGVProperties(Fn, GD); 5128 5129 MaybeHandleStaticInExternC(D, Fn); 5130 5131 maybeSetTrivialComdat(*D, *Fn); 5132 5133 // Set CodeGen attributes that represent floating point environment. 5134 setLLVMFunctionFEnvAttributes(D, Fn); 5135 5136 CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 5137 5138 setNonAliasAttributes(GD, Fn); 5139 SetLLVMFunctionAttributesForDefinition(D, Fn); 5140 5141 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 5142 AddGlobalCtor(Fn, CA->getPriority()); 5143 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5144 AddGlobalDtor(Fn, DA->getPriority(), true); 5145 if (D->hasAttr<AnnotateAttr>()) 5146 AddGlobalAnnotations(D, Fn); 5147 } 5148 5149 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 5150 const auto *D = cast<ValueDecl>(GD.getDecl()); 5151 const AliasAttr *AA = D->getAttr<AliasAttr>(); 5152 assert(AA && "Not an alias?"); 5153 5154 StringRef MangledName = getMangledName(GD); 5155 5156 if (AA->getAliasee() == MangledName) { 5157 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5158 return; 5159 } 5160 5161 // If there is a definition in the module, then it wins over the alias. 5162 // This is dubious, but allow it to be safe. Just ignore the alias. 5163 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5164 if (Entry && !Entry->isDeclaration()) 5165 return; 5166 5167 Aliases.push_back(GD); 5168 5169 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5170 5171 // Create a reference to the named value. This ensures that it is emitted 5172 // if a deferred decl. 5173 llvm::Constant *Aliasee; 5174 llvm::GlobalValue::LinkageTypes LT; 5175 if (isa<llvm::FunctionType>(DeclTy)) { 5176 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 5177 /*ForVTable=*/false); 5178 LT = getFunctionLinkage(GD); 5179 } else { 5180 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 5181 /*D=*/nullptr); 5182 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 5183 LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified()); 5184 else 5185 LT = getFunctionLinkage(GD); 5186 } 5187 5188 // Create the new alias itself, but don't set a name yet. 5189 unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 5190 auto *GA = 5191 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 5192 5193 if (Entry) { 5194 if (GA->getAliasee() == Entry) { 5195 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5196 return; 5197 } 5198 5199 assert(Entry->isDeclaration()); 5200 5201 // If there is a declaration in the module, then we had an extern followed 5202 // by the alias, as in: 5203 // extern int test6(); 5204 // ... 5205 // int test6() __attribute__((alias("test7"))); 5206 // 5207 // Remove it and replace uses of it with the alias. 5208 GA->takeName(Entry); 5209 5210 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 5211 Entry->getType())); 5212 Entry->eraseFromParent(); 5213 } else { 5214 GA->setName(MangledName); 5215 } 5216 5217 // Set attributes which are particular to an alias; this is a 5218 // specialization of the attributes which may be set on a global 5219 // variable/function. 5220 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 5221 D->isWeakImported()) { 5222 GA->setLinkage(llvm::Function::WeakAnyLinkage); 5223 } 5224 5225 if (const auto *VD = dyn_cast<VarDecl>(D)) 5226 if (VD->getTLSKind()) 5227 setTLSMode(GA, *VD); 5228 5229 SetCommonAttributes(GD, GA); 5230 5231 // Emit global alias debug information. 5232 if (isa<VarDecl>(D)) 5233 if (CGDebugInfo *DI = getModuleDebugInfo()) 5234 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()), GD); 5235 } 5236 5237 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 5238 const auto *D = cast<ValueDecl>(GD.getDecl()); 5239 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 5240 assert(IFA && "Not an ifunc?"); 5241 5242 StringRef MangledName = getMangledName(GD); 5243 5244 if (IFA->getResolver() == MangledName) { 5245 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5246 return; 5247 } 5248 5249 // Report an error if some definition overrides ifunc. 5250 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5251 if (Entry && !Entry->isDeclaration()) { 5252 GlobalDecl OtherGD; 5253 if (lookupRepresentativeDecl(MangledName, OtherGD) && 5254 DiagnosedConflictingDefinitions.insert(GD).second) { 5255 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 5256 << MangledName; 5257 Diags.Report(OtherGD.getDecl()->getLocation(), 5258 diag::note_previous_definition); 5259 } 5260 return; 5261 } 5262 5263 Aliases.push_back(GD); 5264 5265 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5266 llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 5267 llvm::Constant *Resolver = 5268 GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 5269 /*ForVTable=*/false); 5270 llvm::GlobalIFunc *GIF = 5271 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 5272 "", Resolver, &getModule()); 5273 if (Entry) { 5274 if (GIF->getResolver() == Entry) { 5275 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5276 return; 5277 } 5278 assert(Entry->isDeclaration()); 5279 5280 // If there is a declaration in the module, then we had an extern followed 5281 // by the ifunc, as in: 5282 // extern int test(); 5283 // ... 5284 // int test() __attribute__((ifunc("resolver"))); 5285 // 5286 // Remove it and replace uses of it with the ifunc. 5287 GIF->takeName(Entry); 5288 5289 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 5290 Entry->getType())); 5291 Entry->eraseFromParent(); 5292 } else 5293 GIF->setName(MangledName); 5294 5295 SetCommonAttributes(GD, GIF); 5296 } 5297 5298 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 5299 ArrayRef<llvm::Type*> Tys) { 5300 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 5301 Tys); 5302 } 5303 5304 static llvm::StringMapEntry<llvm::GlobalVariable *> & 5305 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 5306 const StringLiteral *Literal, bool TargetIsLSB, 5307 bool &IsUTF16, unsigned &StringLength) { 5308 StringRef String = Literal->getString(); 5309 unsigned NumBytes = String.size(); 5310 5311 // Check for simple case. 5312 if (!Literal->containsNonAsciiOrNull()) { 5313 StringLength = NumBytes; 5314 return *Map.insert(std::make_pair(String, nullptr)).first; 5315 } 5316 5317 // Otherwise, convert the UTF8 literals into a string of shorts. 5318 IsUTF16 = true; 5319 5320 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 5321 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5322 llvm::UTF16 *ToPtr = &ToBuf[0]; 5323 5324 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5325 ToPtr + NumBytes, llvm::strictConversion); 5326 5327 // ConvertUTF8toUTF16 returns the length in ToPtr. 5328 StringLength = ToPtr - &ToBuf[0]; 5329 5330 // Add an explicit null. 5331 *ToPtr = 0; 5332 return *Map.insert(std::make_pair( 5333 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 5334 (StringLength + 1) * 2), 5335 nullptr)).first; 5336 } 5337 5338 ConstantAddress 5339 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 5340 unsigned StringLength = 0; 5341 bool isUTF16 = false; 5342 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 5343 GetConstantCFStringEntry(CFConstantStringMap, Literal, 5344 getDataLayout().isLittleEndian(), isUTF16, 5345 StringLength); 5346 5347 if (auto *C = Entry.second) 5348 return ConstantAddress( 5349 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 5350 5351 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 5352 llvm::Constant *Zeros[] = { Zero, Zero }; 5353 5354 const ASTContext &Context = getContext(); 5355 const llvm::Triple &Triple = getTriple(); 5356 5357 const auto CFRuntime = getLangOpts().CFRuntime; 5358 const bool IsSwiftABI = 5359 static_cast<unsigned>(CFRuntime) >= 5360 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 5361 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 5362 5363 // If we don't already have it, get __CFConstantStringClassReference. 5364 if (!CFConstantStringClassRef) { 5365 const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 5366 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 5367 Ty = llvm::ArrayType::get(Ty, 0); 5368 5369 switch (CFRuntime) { 5370 default: break; 5371 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH; 5372 case LangOptions::CoreFoundationABI::Swift5_0: 5373 CFConstantStringClassName = 5374 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 5375 : "$s10Foundation19_NSCFConstantStringCN"; 5376 Ty = IntPtrTy; 5377 break; 5378 case LangOptions::CoreFoundationABI::Swift4_2: 5379 CFConstantStringClassName = 5380 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 5381 : "$S10Foundation19_NSCFConstantStringCN"; 5382 Ty = IntPtrTy; 5383 break; 5384 case LangOptions::CoreFoundationABI::Swift4_1: 5385 CFConstantStringClassName = 5386 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 5387 : "__T010Foundation19_NSCFConstantStringCN"; 5388 Ty = IntPtrTy; 5389 break; 5390 } 5391 5392 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 5393 5394 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 5395 llvm::GlobalValue *GV = nullptr; 5396 5397 if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 5398 IdentifierInfo &II = Context.Idents.get(GV->getName()); 5399 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 5400 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 5401 5402 const VarDecl *VD = nullptr; 5403 for (const auto *Result : DC->lookup(&II)) 5404 if ((VD = dyn_cast<VarDecl>(Result))) 5405 break; 5406 5407 if (Triple.isOSBinFormatELF()) { 5408 if (!VD) 5409 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5410 } else { 5411 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5412 if (!VD || !VD->hasAttr<DLLExportAttr>()) 5413 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 5414 else 5415 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 5416 } 5417 5418 setDSOLocal(GV); 5419 } 5420 } 5421 5422 // Decay array -> ptr 5423 CFConstantStringClassRef = 5424 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 5425 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 5426 } 5427 5428 QualType CFTy = Context.getCFConstantStringType(); 5429 5430 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 5431 5432 ConstantInitBuilder Builder(*this); 5433 auto Fields = Builder.beginStruct(STy); 5434 5435 // Class pointer. 5436 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef)); 5437 5438 // Flags. 5439 if (IsSwiftABI) { 5440 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 5441 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 5442 } else { 5443 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 5444 } 5445 5446 // String pointer. 5447 llvm::Constant *C = nullptr; 5448 if (isUTF16) { 5449 auto Arr = llvm::makeArrayRef( 5450 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 5451 Entry.first().size() / 2); 5452 C = llvm::ConstantDataArray::get(VMContext, Arr); 5453 } else { 5454 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 5455 } 5456 5457 // Note: -fwritable-strings doesn't make the backing store strings of 5458 // CFStrings writable. (See <rdar://problem/10657500>) 5459 auto *GV = 5460 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 5461 llvm::GlobalValue::PrivateLinkage, C, ".str"); 5462 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5463 // Don't enforce the target's minimum global alignment, since the only use 5464 // of the string is via this class initializer. 5465 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 5466 : Context.getTypeAlignInChars(Context.CharTy); 5467 GV->setAlignment(Align.getAsAlign()); 5468 5469 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 5470 // Without it LLVM can merge the string with a non unnamed_addr one during 5471 // LTO. Doing that changes the section it ends in, which surprises ld64. 5472 if (Triple.isOSBinFormatMachO()) 5473 GV->setSection(isUTF16 ? "__TEXT,__ustring" 5474 : "__TEXT,__cstring,cstring_literals"); 5475 // Make sure the literal ends up in .rodata to allow for safe ICF and for 5476 // the static linker to adjust permissions to read-only later on. 5477 else if (Triple.isOSBinFormatELF()) 5478 GV->setSection(".rodata"); 5479 5480 // String. 5481 llvm::Constant *Str = 5482 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 5483 5484 if (isUTF16) 5485 // Cast the UTF16 string to the correct type. 5486 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 5487 Fields.add(Str); 5488 5489 // String length. 5490 llvm::IntegerType *LengthTy = 5491 llvm::IntegerType::get(getModule().getContext(), 5492 Context.getTargetInfo().getLongWidth()); 5493 if (IsSwiftABI) { 5494 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 5495 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 5496 LengthTy = Int32Ty; 5497 else 5498 LengthTy = IntPtrTy; 5499 } 5500 Fields.addInt(LengthTy, StringLength); 5501 5502 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 5503 // properly aligned on 32-bit platforms. 5504 CharUnits Alignment = 5505 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 5506 5507 // The struct. 5508 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 5509 /*isConstant=*/false, 5510 llvm::GlobalVariable::PrivateLinkage); 5511 GV->addAttribute("objc_arc_inert"); 5512 switch (Triple.getObjectFormat()) { 5513 case llvm::Triple::UnknownObjectFormat: 5514 llvm_unreachable("unknown file format"); 5515 case llvm::Triple::DXContainer: 5516 case llvm::Triple::GOFF: 5517 case llvm::Triple::SPIRV: 5518 case llvm::Triple::XCOFF: 5519 llvm_unreachable("unimplemented"); 5520 case llvm::Triple::COFF: 5521 case llvm::Triple::ELF: 5522 case llvm::Triple::Wasm: 5523 GV->setSection("cfstring"); 5524 break; 5525 case llvm::Triple::MachO: 5526 GV->setSection("__DATA,__cfstring"); 5527 break; 5528 } 5529 Entry.second = GV; 5530 5531 return ConstantAddress(GV, GV->getValueType(), Alignment); 5532 } 5533 5534 bool CodeGenModule::getExpressionLocationsEnabled() const { 5535 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 5536 } 5537 5538 QualType CodeGenModule::getObjCFastEnumerationStateType() { 5539 if (ObjCFastEnumerationStateType.isNull()) { 5540 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 5541 D->startDefinition(); 5542 5543 QualType FieldTypes[] = { 5544 Context.UnsignedLongTy, 5545 Context.getPointerType(Context.getObjCIdType()), 5546 Context.getPointerType(Context.UnsignedLongTy), 5547 Context.getConstantArrayType(Context.UnsignedLongTy, 5548 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 5549 }; 5550 5551 for (size_t i = 0; i < 4; ++i) { 5552 FieldDecl *Field = FieldDecl::Create(Context, 5553 D, 5554 SourceLocation(), 5555 SourceLocation(), nullptr, 5556 FieldTypes[i], /*TInfo=*/nullptr, 5557 /*BitWidth=*/nullptr, 5558 /*Mutable=*/false, 5559 ICIS_NoInit); 5560 Field->setAccess(AS_public); 5561 D->addDecl(Field); 5562 } 5563 5564 D->completeDefinition(); 5565 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 5566 } 5567 5568 return ObjCFastEnumerationStateType; 5569 } 5570 5571 llvm::Constant * 5572 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 5573 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 5574 5575 // Don't emit it as the address of the string, emit the string data itself 5576 // as an inline array. 5577 if (E->getCharByteWidth() == 1) { 5578 SmallString<64> Str(E->getString()); 5579 5580 // Resize the string to the right size, which is indicated by its type. 5581 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 5582 Str.resize(CAT->getSize().getZExtValue()); 5583 return llvm::ConstantDataArray::getString(VMContext, Str, false); 5584 } 5585 5586 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 5587 llvm::Type *ElemTy = AType->getElementType(); 5588 unsigned NumElements = AType->getNumElements(); 5589 5590 // Wide strings have either 2-byte or 4-byte elements. 5591 if (ElemTy->getPrimitiveSizeInBits() == 16) { 5592 SmallVector<uint16_t, 32> Elements; 5593 Elements.reserve(NumElements); 5594 5595 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5596 Elements.push_back(E->getCodeUnit(i)); 5597 Elements.resize(NumElements); 5598 return llvm::ConstantDataArray::get(VMContext, Elements); 5599 } 5600 5601 assert(ElemTy->getPrimitiveSizeInBits() == 32); 5602 SmallVector<uint32_t, 32> Elements; 5603 Elements.reserve(NumElements); 5604 5605 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5606 Elements.push_back(E->getCodeUnit(i)); 5607 Elements.resize(NumElements); 5608 return llvm::ConstantDataArray::get(VMContext, Elements); 5609 } 5610 5611 static llvm::GlobalVariable * 5612 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 5613 CodeGenModule &CGM, StringRef GlobalName, 5614 CharUnits Alignment) { 5615 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5616 CGM.GetGlobalConstantAddressSpace()); 5617 5618 llvm::Module &M = CGM.getModule(); 5619 // Create a global variable for this string 5620 auto *GV = new llvm::GlobalVariable( 5621 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 5622 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5623 GV->setAlignment(Alignment.getAsAlign()); 5624 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5625 if (GV->isWeakForLinker()) { 5626 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 5627 GV->setComdat(M.getOrInsertComdat(GV->getName())); 5628 } 5629 CGM.setDSOLocal(GV); 5630 5631 return GV; 5632 } 5633 5634 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 5635 /// constant array for the given string literal. 5636 ConstantAddress 5637 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 5638 StringRef Name) { 5639 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 5640 5641 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 5642 llvm::GlobalVariable **Entry = nullptr; 5643 if (!LangOpts.WritableStrings) { 5644 Entry = &ConstantStringMap[C]; 5645 if (auto GV = *Entry) { 5646 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5647 GV->setAlignment(Alignment.getAsAlign()); 5648 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5649 GV->getValueType(), Alignment); 5650 } 5651 } 5652 5653 SmallString<256> MangledNameBuffer; 5654 StringRef GlobalVariableName; 5655 llvm::GlobalValue::LinkageTypes LT; 5656 5657 // Mangle the string literal if that's how the ABI merges duplicate strings. 5658 // Don't do it if they are writable, since we don't want writes in one TU to 5659 // affect strings in another. 5660 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 5661 !LangOpts.WritableStrings) { 5662 llvm::raw_svector_ostream Out(MangledNameBuffer); 5663 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 5664 LT = llvm::GlobalValue::LinkOnceODRLinkage; 5665 GlobalVariableName = MangledNameBuffer; 5666 } else { 5667 LT = llvm::GlobalValue::PrivateLinkage; 5668 GlobalVariableName = Name; 5669 } 5670 5671 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 5672 5673 CGDebugInfo *DI = getModuleDebugInfo(); 5674 if (DI && getCodeGenOpts().hasReducedDebugInfo()) 5675 DI->AddStringLiteralDebugInfo(GV, S); 5676 5677 if (Entry) 5678 *Entry = GV; 5679 5680 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 5681 QualType()); 5682 5683 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5684 GV->getValueType(), Alignment); 5685 } 5686 5687 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 5688 /// array for the given ObjCEncodeExpr node. 5689 ConstantAddress 5690 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 5691 std::string Str; 5692 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 5693 5694 return GetAddrOfConstantCString(Str); 5695 } 5696 5697 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 5698 /// the literal and a terminating '\0' character. 5699 /// The result has pointer to array type. 5700 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 5701 const std::string &Str, const char *GlobalName) { 5702 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 5703 CharUnits Alignment = 5704 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 5705 5706 llvm::Constant *C = 5707 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 5708 5709 // Don't share any string literals if strings aren't constant. 5710 llvm::GlobalVariable **Entry = nullptr; 5711 if (!LangOpts.WritableStrings) { 5712 Entry = &ConstantStringMap[C]; 5713 if (auto GV = *Entry) { 5714 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5715 GV->setAlignment(Alignment.getAsAlign()); 5716 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5717 GV->getValueType(), Alignment); 5718 } 5719 } 5720 5721 // Get the default prefix if a name wasn't specified. 5722 if (!GlobalName) 5723 GlobalName = ".str"; 5724 // Create a global variable for this. 5725 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 5726 GlobalName, Alignment); 5727 if (Entry) 5728 *Entry = GV; 5729 5730 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5731 GV->getValueType(), Alignment); 5732 } 5733 5734 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 5735 const MaterializeTemporaryExpr *E, const Expr *Init) { 5736 assert((E->getStorageDuration() == SD_Static || 5737 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 5738 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 5739 5740 // If we're not materializing a subobject of the temporary, keep the 5741 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 5742 QualType MaterializedType = Init->getType(); 5743 if (Init == E->getSubExpr()) 5744 MaterializedType = E->getType(); 5745 5746 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 5747 5748 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 5749 if (!InsertResult.second) { 5750 // We've seen this before: either we already created it or we're in the 5751 // process of doing so. 5752 if (!InsertResult.first->second) { 5753 // We recursively re-entered this function, probably during emission of 5754 // the initializer. Create a placeholder. We'll clean this up in the 5755 // outer call, at the end of this function. 5756 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 5757 InsertResult.first->second = new llvm::GlobalVariable( 5758 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 5759 nullptr); 5760 } 5761 return ConstantAddress(InsertResult.first->second, 5762 llvm::cast<llvm::GlobalVariable>( 5763 InsertResult.first->second->stripPointerCasts()) 5764 ->getValueType(), 5765 Align); 5766 } 5767 5768 // FIXME: If an externally-visible declaration extends multiple temporaries, 5769 // we need to give each temporary the same name in every translation unit (and 5770 // we also need to make the temporaries externally-visible). 5771 SmallString<256> Name; 5772 llvm::raw_svector_ostream Out(Name); 5773 getCXXABI().getMangleContext().mangleReferenceTemporary( 5774 VD, E->getManglingNumber(), Out); 5775 5776 APValue *Value = nullptr; 5777 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 5778 // If the initializer of the extending declaration is a constant 5779 // initializer, we should have a cached constant initializer for this 5780 // temporary. Note that this might have a different value from the value 5781 // computed by evaluating the initializer if the surrounding constant 5782 // expression modifies the temporary. 5783 Value = E->getOrCreateValue(false); 5784 } 5785 5786 // Try evaluating it now, it might have a constant initializer. 5787 Expr::EvalResult EvalResult; 5788 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 5789 !EvalResult.hasSideEffects()) 5790 Value = &EvalResult.Val; 5791 5792 LangAS AddrSpace = 5793 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 5794 5795 Optional<ConstantEmitter> emitter; 5796 llvm::Constant *InitialValue = nullptr; 5797 bool Constant = false; 5798 llvm::Type *Type; 5799 if (Value) { 5800 // The temporary has a constant initializer, use it. 5801 emitter.emplace(*this); 5802 InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 5803 MaterializedType); 5804 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 5805 Type = InitialValue->getType(); 5806 } else { 5807 // No initializer, the initialization will be provided when we 5808 // initialize the declaration which performed lifetime extension. 5809 Type = getTypes().ConvertTypeForMem(MaterializedType); 5810 } 5811 5812 // Create a global variable for this lifetime-extended temporary. 5813 llvm::GlobalValue::LinkageTypes Linkage = 5814 getLLVMLinkageVarDefinition(VD, Constant); 5815 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 5816 const VarDecl *InitVD; 5817 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 5818 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 5819 // Temporaries defined inside a class get linkonce_odr linkage because the 5820 // class can be defined in multiple translation units. 5821 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 5822 } else { 5823 // There is no need for this temporary to have external linkage if the 5824 // VarDecl has external linkage. 5825 Linkage = llvm::GlobalVariable::InternalLinkage; 5826 } 5827 } 5828 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 5829 auto *GV = new llvm::GlobalVariable( 5830 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 5831 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 5832 if (emitter) emitter->finalize(GV); 5833 setGVProperties(GV, VD); 5834 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass) 5835 // The reference temporary should never be dllexport. 5836 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 5837 GV->setAlignment(Align.getAsAlign()); 5838 if (supportsCOMDAT() && GV->isWeakForLinker()) 5839 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 5840 if (VD->getTLSKind()) 5841 setTLSMode(GV, *VD); 5842 llvm::Constant *CV = GV; 5843 if (AddrSpace != LangAS::Default) 5844 CV = getTargetCodeGenInfo().performAddrSpaceCast( 5845 *this, GV, AddrSpace, LangAS::Default, 5846 Type->getPointerTo( 5847 getContext().getTargetAddressSpace(LangAS::Default))); 5848 5849 // Update the map with the new temporary. If we created a placeholder above, 5850 // replace it with the new global now. 5851 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 5852 if (Entry) { 5853 Entry->replaceAllUsesWith( 5854 llvm::ConstantExpr::getBitCast(CV, Entry->getType())); 5855 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 5856 } 5857 Entry = CV; 5858 5859 return ConstantAddress(CV, Type, Align); 5860 } 5861 5862 /// EmitObjCPropertyImplementations - Emit information for synthesized 5863 /// properties for an implementation. 5864 void CodeGenModule::EmitObjCPropertyImplementations(const 5865 ObjCImplementationDecl *D) { 5866 for (const auto *PID : D->property_impls()) { 5867 // Dynamic is just for type-checking. 5868 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 5869 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 5870 5871 // Determine which methods need to be implemented, some may have 5872 // been overridden. Note that ::isPropertyAccessor is not the method 5873 // we want, that just indicates if the decl came from a 5874 // property. What we want to know is if the method is defined in 5875 // this implementation. 5876 auto *Getter = PID->getGetterMethodDecl(); 5877 if (!Getter || Getter->isSynthesizedAccessorStub()) 5878 CodeGenFunction(*this).GenerateObjCGetter( 5879 const_cast<ObjCImplementationDecl *>(D), PID); 5880 auto *Setter = PID->getSetterMethodDecl(); 5881 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 5882 CodeGenFunction(*this).GenerateObjCSetter( 5883 const_cast<ObjCImplementationDecl *>(D), PID); 5884 } 5885 } 5886 } 5887 5888 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 5889 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 5890 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 5891 ivar; ivar = ivar->getNextIvar()) 5892 if (ivar->getType().isDestructedType()) 5893 return true; 5894 5895 return false; 5896 } 5897 5898 static bool AllTrivialInitializers(CodeGenModule &CGM, 5899 ObjCImplementationDecl *D) { 5900 CodeGenFunction CGF(CGM); 5901 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 5902 E = D->init_end(); B != E; ++B) { 5903 CXXCtorInitializer *CtorInitExp = *B; 5904 Expr *Init = CtorInitExp->getInit(); 5905 if (!CGF.isTrivialInitializer(Init)) 5906 return false; 5907 } 5908 return true; 5909 } 5910 5911 /// EmitObjCIvarInitializations - Emit information for ivar initialization 5912 /// for an implementation. 5913 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 5914 // We might need a .cxx_destruct even if we don't have any ivar initializers. 5915 if (needsDestructMethod(D)) { 5916 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 5917 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5918 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 5919 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5920 getContext().VoidTy, nullptr, D, 5921 /*isInstance=*/true, /*isVariadic=*/false, 5922 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5923 /*isImplicitlyDeclared=*/true, 5924 /*isDefined=*/false, ObjCMethodDecl::Required); 5925 D->addInstanceMethod(DTORMethod); 5926 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 5927 D->setHasDestructors(true); 5928 } 5929 5930 // If the implementation doesn't have any ivar initializers, we don't need 5931 // a .cxx_construct. 5932 if (D->getNumIvarInitializers() == 0 || 5933 AllTrivialInitializers(*this, D)) 5934 return; 5935 5936 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 5937 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5938 // The constructor returns 'self'. 5939 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 5940 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5941 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 5942 /*isVariadic=*/false, 5943 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5944 /*isImplicitlyDeclared=*/true, 5945 /*isDefined=*/false, ObjCMethodDecl::Required); 5946 D->addInstanceMethod(CTORMethod); 5947 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 5948 D->setHasNonZeroConstructors(true); 5949 } 5950 5951 // EmitLinkageSpec - Emit all declarations in a linkage spec. 5952 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 5953 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 5954 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 5955 ErrorUnsupported(LSD, "linkage spec"); 5956 return; 5957 } 5958 5959 EmitDeclContext(LSD); 5960 } 5961 5962 void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 5963 for (auto *I : DC->decls()) { 5964 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 5965 // are themselves considered "top-level", so EmitTopLevelDecl on an 5966 // ObjCImplDecl does not recursively visit them. We need to do that in 5967 // case they're nested inside another construct (LinkageSpecDecl / 5968 // ExportDecl) that does stop them from being considered "top-level". 5969 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 5970 for (auto *M : OID->methods()) 5971 EmitTopLevelDecl(M); 5972 } 5973 5974 EmitTopLevelDecl(I); 5975 } 5976 } 5977 5978 /// EmitTopLevelDecl - Emit code for a single top level declaration. 5979 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 5980 // Ignore dependent declarations. 5981 if (D->isTemplated()) 5982 return; 5983 5984 // Consteval function shouldn't be emitted. 5985 if (auto *FD = dyn_cast<FunctionDecl>(D)) 5986 if (FD->isConsteval()) 5987 return; 5988 5989 switch (D->getKind()) { 5990 case Decl::CXXConversion: 5991 case Decl::CXXMethod: 5992 case Decl::Function: 5993 EmitGlobal(cast<FunctionDecl>(D)); 5994 // Always provide some coverage mapping 5995 // even for the functions that aren't emitted. 5996 AddDeferredUnusedCoverageMapping(D); 5997 break; 5998 5999 case Decl::CXXDeductionGuide: 6000 // Function-like, but does not result in code emission. 6001 break; 6002 6003 case Decl::Var: 6004 case Decl::Decomposition: 6005 case Decl::VarTemplateSpecialization: 6006 EmitGlobal(cast<VarDecl>(D)); 6007 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 6008 for (auto *B : DD->bindings()) 6009 if (auto *HD = B->getHoldingVar()) 6010 EmitGlobal(HD); 6011 break; 6012 6013 // Indirect fields from global anonymous structs and unions can be 6014 // ignored; only the actual variable requires IR gen support. 6015 case Decl::IndirectField: 6016 break; 6017 6018 // C++ Decls 6019 case Decl::Namespace: 6020 EmitDeclContext(cast<NamespaceDecl>(D)); 6021 break; 6022 case Decl::ClassTemplateSpecialization: { 6023 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 6024 if (CGDebugInfo *DI = getModuleDebugInfo()) 6025 if (Spec->getSpecializationKind() == 6026 TSK_ExplicitInstantiationDefinition && 6027 Spec->hasDefinition()) 6028 DI->completeTemplateDefinition(*Spec); 6029 } LLVM_FALLTHROUGH; 6030 case Decl::CXXRecord: { 6031 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 6032 if (CGDebugInfo *DI = getModuleDebugInfo()) { 6033 if (CRD->hasDefinition()) 6034 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6035 if (auto *ES = D->getASTContext().getExternalSource()) 6036 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 6037 DI->completeUnusedClass(*CRD); 6038 } 6039 // Emit any static data members, they may be definitions. 6040 for (auto *I : CRD->decls()) 6041 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 6042 EmitTopLevelDecl(I); 6043 break; 6044 } 6045 // No code generation needed. 6046 case Decl::UsingShadow: 6047 case Decl::ClassTemplate: 6048 case Decl::VarTemplate: 6049 case Decl::Concept: 6050 case Decl::VarTemplatePartialSpecialization: 6051 case Decl::FunctionTemplate: 6052 case Decl::TypeAliasTemplate: 6053 case Decl::Block: 6054 case Decl::Empty: 6055 case Decl::Binding: 6056 break; 6057 case Decl::Using: // using X; [C++] 6058 if (CGDebugInfo *DI = getModuleDebugInfo()) 6059 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 6060 break; 6061 case Decl::UsingEnum: // using enum X; [C++] 6062 if (CGDebugInfo *DI = getModuleDebugInfo()) 6063 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 6064 break; 6065 case Decl::NamespaceAlias: 6066 if (CGDebugInfo *DI = getModuleDebugInfo()) 6067 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 6068 break; 6069 case Decl::UsingDirective: // using namespace X; [C++] 6070 if (CGDebugInfo *DI = getModuleDebugInfo()) 6071 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 6072 break; 6073 case Decl::CXXConstructor: 6074 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 6075 break; 6076 case Decl::CXXDestructor: 6077 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 6078 break; 6079 6080 case Decl::StaticAssert: 6081 // Nothing to do. 6082 break; 6083 6084 // Objective-C Decls 6085 6086 // Forward declarations, no (immediate) code generation. 6087 case Decl::ObjCInterface: 6088 case Decl::ObjCCategory: 6089 break; 6090 6091 case Decl::ObjCProtocol: { 6092 auto *Proto = cast<ObjCProtocolDecl>(D); 6093 if (Proto->isThisDeclarationADefinition()) 6094 ObjCRuntime->GenerateProtocol(Proto); 6095 break; 6096 } 6097 6098 case Decl::ObjCCategoryImpl: 6099 // Categories have properties but don't support synthesize so we 6100 // can ignore them here. 6101 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 6102 break; 6103 6104 case Decl::ObjCImplementation: { 6105 auto *OMD = cast<ObjCImplementationDecl>(D); 6106 EmitObjCPropertyImplementations(OMD); 6107 EmitObjCIvarInitializations(OMD); 6108 ObjCRuntime->GenerateClass(OMD); 6109 // Emit global variable debug information. 6110 if (CGDebugInfo *DI = getModuleDebugInfo()) 6111 if (getCodeGenOpts().hasReducedDebugInfo()) 6112 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 6113 OMD->getClassInterface()), OMD->getLocation()); 6114 break; 6115 } 6116 case Decl::ObjCMethod: { 6117 auto *OMD = cast<ObjCMethodDecl>(D); 6118 // If this is not a prototype, emit the body. 6119 if (OMD->getBody()) 6120 CodeGenFunction(*this).GenerateObjCMethod(OMD); 6121 break; 6122 } 6123 case Decl::ObjCCompatibleAlias: 6124 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 6125 break; 6126 6127 case Decl::PragmaComment: { 6128 const auto *PCD = cast<PragmaCommentDecl>(D); 6129 switch (PCD->getCommentKind()) { 6130 case PCK_Unknown: 6131 llvm_unreachable("unexpected pragma comment kind"); 6132 case PCK_Linker: 6133 AppendLinkerOptions(PCD->getArg()); 6134 break; 6135 case PCK_Lib: 6136 AddDependentLib(PCD->getArg()); 6137 break; 6138 case PCK_Compiler: 6139 case PCK_ExeStr: 6140 case PCK_User: 6141 break; // We ignore all of these. 6142 } 6143 break; 6144 } 6145 6146 case Decl::PragmaDetectMismatch: { 6147 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 6148 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 6149 break; 6150 } 6151 6152 case Decl::LinkageSpec: 6153 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 6154 break; 6155 6156 case Decl::FileScopeAsm: { 6157 // File-scope asm is ignored during device-side CUDA compilation. 6158 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6159 break; 6160 // File-scope asm is ignored during device-side OpenMP compilation. 6161 if (LangOpts.OpenMPIsDevice) 6162 break; 6163 // File-scope asm is ignored during device-side SYCL compilation. 6164 if (LangOpts.SYCLIsDevice) 6165 break; 6166 auto *AD = cast<FileScopeAsmDecl>(D); 6167 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 6168 break; 6169 } 6170 6171 case Decl::Import: { 6172 auto *Import = cast<ImportDecl>(D); 6173 6174 // If we've already imported this module, we're done. 6175 if (!ImportedModules.insert(Import->getImportedModule())) 6176 break; 6177 6178 // Emit debug information for direct imports. 6179 if (!Import->getImportedOwningModule()) { 6180 if (CGDebugInfo *DI = getModuleDebugInfo()) 6181 DI->EmitImportDecl(*Import); 6182 } 6183 6184 // Find all of the submodules and emit the module initializers. 6185 llvm::SmallPtrSet<clang::Module *, 16> Visited; 6186 SmallVector<clang::Module *, 16> Stack; 6187 Visited.insert(Import->getImportedModule()); 6188 Stack.push_back(Import->getImportedModule()); 6189 6190 while (!Stack.empty()) { 6191 clang::Module *Mod = Stack.pop_back_val(); 6192 if (!EmittedModuleInitializers.insert(Mod).second) 6193 continue; 6194 6195 for (auto *D : Context.getModuleInitializers(Mod)) 6196 EmitTopLevelDecl(D); 6197 6198 // Visit the submodules of this module. 6199 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 6200 SubEnd = Mod->submodule_end(); 6201 Sub != SubEnd; ++Sub) { 6202 // Skip explicit children; they need to be explicitly imported to emit 6203 // the initializers. 6204 if ((*Sub)->IsExplicit) 6205 continue; 6206 6207 if (Visited.insert(*Sub).second) 6208 Stack.push_back(*Sub); 6209 } 6210 } 6211 break; 6212 } 6213 6214 case Decl::Export: 6215 EmitDeclContext(cast<ExportDecl>(D)); 6216 break; 6217 6218 case Decl::OMPThreadPrivate: 6219 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 6220 break; 6221 6222 case Decl::OMPAllocate: 6223 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 6224 break; 6225 6226 case Decl::OMPDeclareReduction: 6227 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 6228 break; 6229 6230 case Decl::OMPDeclareMapper: 6231 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 6232 break; 6233 6234 case Decl::OMPRequires: 6235 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 6236 break; 6237 6238 case Decl::Typedef: 6239 case Decl::TypeAlias: // using foo = bar; [C++11] 6240 if (CGDebugInfo *DI = getModuleDebugInfo()) 6241 DI->EmitAndRetainType( 6242 getContext().getTypedefType(cast<TypedefNameDecl>(D))); 6243 break; 6244 6245 case Decl::Record: 6246 if (CGDebugInfo *DI = getModuleDebugInfo()) 6247 if (cast<RecordDecl>(D)->getDefinition()) 6248 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6249 break; 6250 6251 case Decl::Enum: 6252 if (CGDebugInfo *DI = getModuleDebugInfo()) 6253 if (cast<EnumDecl>(D)->getDefinition()) 6254 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 6255 break; 6256 6257 default: 6258 // Make sure we handled everything we should, every other kind is a 6259 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 6260 // function. Need to recode Decl::Kind to do that easily. 6261 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 6262 break; 6263 } 6264 } 6265 6266 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 6267 // Do we need to generate coverage mapping? 6268 if (!CodeGenOpts.CoverageMapping) 6269 return; 6270 switch (D->getKind()) { 6271 case Decl::CXXConversion: 6272 case Decl::CXXMethod: 6273 case Decl::Function: 6274 case Decl::ObjCMethod: 6275 case Decl::CXXConstructor: 6276 case Decl::CXXDestructor: { 6277 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 6278 break; 6279 SourceManager &SM = getContext().getSourceManager(); 6280 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 6281 break; 6282 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6283 if (I == DeferredEmptyCoverageMappingDecls.end()) 6284 DeferredEmptyCoverageMappingDecls[D] = true; 6285 break; 6286 } 6287 default: 6288 break; 6289 }; 6290 } 6291 6292 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 6293 // Do we need to generate coverage mapping? 6294 if (!CodeGenOpts.CoverageMapping) 6295 return; 6296 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 6297 if (Fn->isTemplateInstantiation()) 6298 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 6299 } 6300 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6301 if (I == DeferredEmptyCoverageMappingDecls.end()) 6302 DeferredEmptyCoverageMappingDecls[D] = false; 6303 else 6304 I->second = false; 6305 } 6306 6307 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 6308 // We call takeVector() here to avoid use-after-free. 6309 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 6310 // we deserialize function bodies to emit coverage info for them, and that 6311 // deserializes more declarations. How should we handle that case? 6312 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 6313 if (!Entry.second) 6314 continue; 6315 const Decl *D = Entry.first; 6316 switch (D->getKind()) { 6317 case Decl::CXXConversion: 6318 case Decl::CXXMethod: 6319 case Decl::Function: 6320 case Decl::ObjCMethod: { 6321 CodeGenPGO PGO(*this); 6322 GlobalDecl GD(cast<FunctionDecl>(D)); 6323 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6324 getFunctionLinkage(GD)); 6325 break; 6326 } 6327 case Decl::CXXConstructor: { 6328 CodeGenPGO PGO(*this); 6329 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 6330 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6331 getFunctionLinkage(GD)); 6332 break; 6333 } 6334 case Decl::CXXDestructor: { 6335 CodeGenPGO PGO(*this); 6336 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 6337 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6338 getFunctionLinkage(GD)); 6339 break; 6340 } 6341 default: 6342 break; 6343 }; 6344 } 6345 } 6346 6347 void CodeGenModule::EmitMainVoidAlias() { 6348 // In order to transition away from "__original_main" gracefully, emit an 6349 // alias for "main" in the no-argument case so that libc can detect when 6350 // new-style no-argument main is in used. 6351 if (llvm::Function *F = getModule().getFunction("main")) { 6352 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 6353 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) { 6354 auto *GA = llvm::GlobalAlias::create("__main_void", F); 6355 GA->setVisibility(llvm::GlobalValue::HiddenVisibility); 6356 } 6357 } 6358 } 6359 6360 /// Turns the given pointer into a constant. 6361 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 6362 const void *Ptr) { 6363 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 6364 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 6365 return llvm::ConstantInt::get(i64, PtrInt); 6366 } 6367 6368 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 6369 llvm::NamedMDNode *&GlobalMetadata, 6370 GlobalDecl D, 6371 llvm::GlobalValue *Addr) { 6372 if (!GlobalMetadata) 6373 GlobalMetadata = 6374 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 6375 6376 // TODO: should we report variant information for ctors/dtors? 6377 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 6378 llvm::ConstantAsMetadata::get(GetPointerConstant( 6379 CGM.getLLVMContext(), D.getDecl()))}; 6380 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 6381 } 6382 6383 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, 6384 llvm::GlobalValue *CppFunc) { 6385 // Store the list of ifuncs we need to replace uses in. 6386 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs; 6387 // List of ConstantExprs that we should be able to delete when we're done 6388 // here. 6389 llvm::SmallVector<llvm::ConstantExpr *> CEs; 6390 6391 // It isn't valid to replace the extern-C ifuncs if all we find is itself! 6392 if (Elem == CppFunc) 6393 return false; 6394 6395 // First make sure that all users of this are ifuncs (or ifuncs via a 6396 // bitcast), and collect the list of ifuncs and CEs so we can work on them 6397 // later. 6398 for (llvm::User *User : Elem->users()) { 6399 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an 6400 // ifunc directly. In any other case, just give up, as we don't know what we 6401 // could break by changing those. 6402 if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) { 6403 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast) 6404 return false; 6405 6406 for (llvm::User *CEUser : ConstExpr->users()) { 6407 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) { 6408 IFuncs.push_back(IFunc); 6409 } else { 6410 return false; 6411 } 6412 } 6413 CEs.push_back(ConstExpr); 6414 } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) { 6415 IFuncs.push_back(IFunc); 6416 } else { 6417 // This user is one we don't know how to handle, so fail redirection. This 6418 // will result in an ifunc retaining a resolver name that will ultimately 6419 // fail to be resolved to a defined function. 6420 return false; 6421 } 6422 } 6423 6424 // Now we know this is a valid case where we can do this alias replacement, we 6425 // need to remove all of the references to Elem (and the bitcasts!) so we can 6426 // delete it. 6427 for (llvm::GlobalIFunc *IFunc : IFuncs) 6428 IFunc->setResolver(nullptr); 6429 for (llvm::ConstantExpr *ConstExpr : CEs) 6430 ConstExpr->destroyConstant(); 6431 6432 // We should now be out of uses for the 'old' version of this function, so we 6433 // can erase it as well. 6434 Elem->eraseFromParent(); 6435 6436 for (llvm::GlobalIFunc *IFunc : IFuncs) { 6437 // The type of the resolver is always just a function-type that returns the 6438 // type of the IFunc, so create that here. If the type of the actual 6439 // resolver doesn't match, it just gets bitcast to the right thing. 6440 auto *ResolverTy = 6441 llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false); 6442 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 6443 CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false); 6444 IFunc->setResolver(Resolver); 6445 } 6446 return true; 6447 } 6448 6449 /// For each function which is declared within an extern "C" region and marked 6450 /// as 'used', but has internal linkage, create an alias from the unmangled 6451 /// name to the mangled name if possible. People expect to be able to refer 6452 /// to such functions with an unmangled name from inline assembly within the 6453 /// same translation unit. 6454 void CodeGenModule::EmitStaticExternCAliases() { 6455 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 6456 return; 6457 for (auto &I : StaticExternCValues) { 6458 IdentifierInfo *Name = I.first; 6459 llvm::GlobalValue *Val = I.second; 6460 6461 // If Val is null, that implies there were multiple declarations that each 6462 // had a claim to the unmangled name. In this case, generation of the alias 6463 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC. 6464 if (!Val) 6465 break; 6466 6467 llvm::GlobalValue *ExistingElem = 6468 getModule().getNamedValue(Name->getName()); 6469 6470 // If there is either not something already by this name, or we were able to 6471 // replace all uses from IFuncs, create the alias. 6472 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val)) 6473 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 6474 } 6475 } 6476 6477 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 6478 GlobalDecl &Result) const { 6479 auto Res = Manglings.find(MangledName); 6480 if (Res == Manglings.end()) 6481 return false; 6482 Result = Res->getValue(); 6483 return true; 6484 } 6485 6486 /// Emits metadata nodes associating all the global values in the 6487 /// current module with the Decls they came from. This is useful for 6488 /// projects using IR gen as a subroutine. 6489 /// 6490 /// Since there's currently no way to associate an MDNode directly 6491 /// with an llvm::GlobalValue, we create a global named metadata 6492 /// with the name 'clang.global.decl.ptrs'. 6493 void CodeGenModule::EmitDeclMetadata() { 6494 llvm::NamedMDNode *GlobalMetadata = nullptr; 6495 6496 for (auto &I : MangledDeclNames) { 6497 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 6498 // Some mangled names don't necessarily have an associated GlobalValue 6499 // in this module, e.g. if we mangled it for DebugInfo. 6500 if (Addr) 6501 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 6502 } 6503 } 6504 6505 /// Emits metadata nodes for all the local variables in the current 6506 /// function. 6507 void CodeGenFunction::EmitDeclMetadata() { 6508 if (LocalDeclMap.empty()) return; 6509 6510 llvm::LLVMContext &Context = getLLVMContext(); 6511 6512 // Find the unique metadata ID for this name. 6513 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 6514 6515 llvm::NamedMDNode *GlobalMetadata = nullptr; 6516 6517 for (auto &I : LocalDeclMap) { 6518 const Decl *D = I.first; 6519 llvm::Value *Addr = I.second.getPointer(); 6520 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 6521 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 6522 Alloca->setMetadata( 6523 DeclPtrKind, llvm::MDNode::get( 6524 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 6525 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 6526 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 6527 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 6528 } 6529 } 6530 } 6531 6532 void CodeGenModule::EmitVersionIdentMetadata() { 6533 llvm::NamedMDNode *IdentMetadata = 6534 TheModule.getOrInsertNamedMetadata("llvm.ident"); 6535 std::string Version = getClangFullVersion(); 6536 llvm::LLVMContext &Ctx = TheModule.getContext(); 6537 6538 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 6539 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 6540 } 6541 6542 void CodeGenModule::EmitCommandLineMetadata() { 6543 llvm::NamedMDNode *CommandLineMetadata = 6544 TheModule.getOrInsertNamedMetadata("llvm.commandline"); 6545 std::string CommandLine = getCodeGenOpts().RecordCommandLine; 6546 llvm::LLVMContext &Ctx = TheModule.getContext(); 6547 6548 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 6549 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 6550 } 6551 6552 void CodeGenModule::EmitCoverageFile() { 6553 if (getCodeGenOpts().CoverageDataFile.empty() && 6554 getCodeGenOpts().CoverageNotesFile.empty()) 6555 return; 6556 6557 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 6558 if (!CUNode) 6559 return; 6560 6561 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 6562 llvm::LLVMContext &Ctx = TheModule.getContext(); 6563 auto *CoverageDataFile = 6564 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 6565 auto *CoverageNotesFile = 6566 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 6567 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 6568 llvm::MDNode *CU = CUNode->getOperand(i); 6569 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 6570 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 6571 } 6572 } 6573 6574 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 6575 bool ForEH) { 6576 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 6577 // FIXME: should we even be calling this method if RTTI is disabled 6578 // and it's not for EH? 6579 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice || 6580 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 6581 getTriple().isNVPTX())) 6582 return llvm::Constant::getNullValue(Int8PtrTy); 6583 6584 if (ForEH && Ty->isObjCObjectPointerType() && 6585 LangOpts.ObjCRuntime.isGNUFamily()) 6586 return ObjCRuntime->GetEHType(Ty); 6587 6588 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 6589 } 6590 6591 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 6592 // Do not emit threadprivates in simd-only mode. 6593 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 6594 return; 6595 for (auto RefExpr : D->varlists()) { 6596 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 6597 bool PerformInit = 6598 VD->getAnyInitializer() && 6599 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 6600 /*ForRef=*/false); 6601 6602 Address Addr(GetAddrOfGlobalVar(VD), 6603 getTypes().ConvertTypeForMem(VD->getType()), 6604 getContext().getDeclAlign(VD)); 6605 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 6606 VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 6607 CXXGlobalInits.push_back(InitFunction); 6608 } 6609 } 6610 6611 llvm::Metadata * 6612 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 6613 StringRef Suffix) { 6614 if (auto *FnType = T->getAs<FunctionProtoType>()) 6615 T = getContext().getFunctionType( 6616 FnType->getReturnType(), FnType->getParamTypes(), 6617 FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 6618 6619 llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 6620 if (InternalId) 6621 return InternalId; 6622 6623 if (isExternallyVisible(T->getLinkage())) { 6624 std::string OutName; 6625 llvm::raw_string_ostream Out(OutName); 6626 getCXXABI().getMangleContext().mangleTypeName(T, Out); 6627 Out << Suffix; 6628 6629 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 6630 } else { 6631 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 6632 llvm::ArrayRef<llvm::Metadata *>()); 6633 } 6634 6635 return InternalId; 6636 } 6637 6638 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 6639 return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 6640 } 6641 6642 llvm::Metadata * 6643 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 6644 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 6645 } 6646 6647 // Generalize pointer types to a void pointer with the qualifiers of the 6648 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 6649 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 6650 // 'void *'. 6651 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 6652 if (!Ty->isPointerType()) 6653 return Ty; 6654 6655 return Ctx.getPointerType( 6656 QualType(Ctx.VoidTy).withCVRQualifiers( 6657 Ty->getPointeeType().getCVRQualifiers())); 6658 } 6659 6660 // Apply type generalization to a FunctionType's return and argument types 6661 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 6662 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 6663 SmallVector<QualType, 8> GeneralizedParams; 6664 for (auto &Param : FnType->param_types()) 6665 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 6666 6667 return Ctx.getFunctionType( 6668 GeneralizeType(Ctx, FnType->getReturnType()), 6669 GeneralizedParams, FnType->getExtProtoInfo()); 6670 } 6671 6672 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 6673 return Ctx.getFunctionNoProtoType( 6674 GeneralizeType(Ctx, FnType->getReturnType())); 6675 6676 llvm_unreachable("Encountered unknown FunctionType"); 6677 } 6678 6679 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 6680 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 6681 GeneralizedMetadataIdMap, ".generalized"); 6682 } 6683 6684 /// Returns whether this module needs the "all-vtables" type identifier. 6685 bool CodeGenModule::NeedAllVtablesTypeId() const { 6686 // Returns true if at least one of vtable-based CFI checkers is enabled and 6687 // is not in the trapping mode. 6688 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 6689 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 6690 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 6691 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 6692 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 6693 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 6694 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 6695 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 6696 } 6697 6698 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 6699 CharUnits Offset, 6700 const CXXRecordDecl *RD) { 6701 llvm::Metadata *MD = 6702 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 6703 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6704 6705 if (CodeGenOpts.SanitizeCfiCrossDso) 6706 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 6707 VTable->addTypeMetadata(Offset.getQuantity(), 6708 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 6709 6710 if (NeedAllVtablesTypeId()) { 6711 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 6712 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6713 } 6714 } 6715 6716 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 6717 if (!SanStats) 6718 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 6719 6720 return *SanStats; 6721 } 6722 6723 llvm::Value * 6724 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 6725 CodeGenFunction &CGF) { 6726 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 6727 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 6728 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 6729 auto *Call = CGF.EmitRuntimeCall( 6730 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 6731 return Call; 6732 } 6733 6734 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 6735 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 6736 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 6737 /* forPointeeType= */ true); 6738 } 6739 6740 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 6741 LValueBaseInfo *BaseInfo, 6742 TBAAAccessInfo *TBAAInfo, 6743 bool forPointeeType) { 6744 if (TBAAInfo) 6745 *TBAAInfo = getTBAAAccessInfo(T); 6746 6747 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 6748 // that doesn't return the information we need to compute BaseInfo. 6749 6750 // Honor alignment typedef attributes even on incomplete types. 6751 // We also honor them straight for C++ class types, even as pointees; 6752 // there's an expressivity gap here. 6753 if (auto TT = T->getAs<TypedefType>()) { 6754 if (auto Align = TT->getDecl()->getMaxAlignment()) { 6755 if (BaseInfo) 6756 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 6757 return getContext().toCharUnitsFromBits(Align); 6758 } 6759 } 6760 6761 bool AlignForArray = T->isArrayType(); 6762 6763 // Analyze the base element type, so we don't get confused by incomplete 6764 // array types. 6765 T = getContext().getBaseElementType(T); 6766 6767 if (T->isIncompleteType()) { 6768 // We could try to replicate the logic from 6769 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 6770 // type is incomplete, so it's impossible to test. We could try to reuse 6771 // getTypeAlignIfKnown, but that doesn't return the information we need 6772 // to set BaseInfo. So just ignore the possibility that the alignment is 6773 // greater than one. 6774 if (BaseInfo) 6775 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6776 return CharUnits::One(); 6777 } 6778 6779 if (BaseInfo) 6780 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6781 6782 CharUnits Alignment; 6783 const CXXRecordDecl *RD; 6784 if (T.getQualifiers().hasUnaligned()) { 6785 Alignment = CharUnits::One(); 6786 } else if (forPointeeType && !AlignForArray && 6787 (RD = T->getAsCXXRecordDecl())) { 6788 // For C++ class pointees, we don't know whether we're pointing at a 6789 // base or a complete object, so we generally need to use the 6790 // non-virtual alignment. 6791 Alignment = getClassPointerAlignment(RD); 6792 } else { 6793 Alignment = getContext().getTypeAlignInChars(T); 6794 } 6795 6796 // Cap to the global maximum type alignment unless the alignment 6797 // was somehow explicit on the type. 6798 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 6799 if (Alignment.getQuantity() > MaxAlign && 6800 !getContext().isAlignmentRequired(T)) 6801 Alignment = CharUnits::fromQuantity(MaxAlign); 6802 } 6803 return Alignment; 6804 } 6805 6806 bool CodeGenModule::stopAutoInit() { 6807 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 6808 if (StopAfter) { 6809 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 6810 // used 6811 if (NumAutoVarInit >= StopAfter) { 6812 return true; 6813 } 6814 if (!NumAutoVarInit) { 6815 unsigned DiagID = getDiags().getCustomDiagID( 6816 DiagnosticsEngine::Warning, 6817 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 6818 "number of times ftrivial-auto-var-init=%1 gets applied."); 6819 getDiags().Report(DiagID) 6820 << StopAfter 6821 << (getContext().getLangOpts().getTrivialAutoVarInit() == 6822 LangOptions::TrivialAutoVarInitKind::Zero 6823 ? "zero" 6824 : "pattern"); 6825 } 6826 ++NumAutoVarInit; 6827 } 6828 return false; 6829 } 6830 6831 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, 6832 const Decl *D) const { 6833 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers 6834 // postfix beginning with '.' since the symbol name can be demangled. 6835 if (LangOpts.HIP) 6836 OS << (isa<VarDecl>(D) ? ".static." : ".intern."); 6837 else 6838 OS << (isa<VarDecl>(D) ? "__static__" : "__intern__"); 6839 6840 // If the CUID is not specified we try to generate a unique postfix. 6841 if (getLangOpts().CUID.empty()) { 6842 SourceManager &SM = getContext().getSourceManager(); 6843 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation()); 6844 assert(PLoc.isValid() && "Source location is expected to be valid."); 6845 6846 // Get the hash of the user defined macros. 6847 llvm::MD5 Hash; 6848 llvm::MD5::MD5Result Result; 6849 for (const auto &Arg : PreprocessorOpts.Macros) 6850 Hash.update(Arg.first); 6851 Hash.final(Result); 6852 6853 // Get the UniqueID for the file containing the decl. 6854 llvm::sys::fs::UniqueID ID; 6855 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { 6856 PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false); 6857 assert(PLoc.isValid() && "Source location is expected to be valid."); 6858 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) 6859 SM.getDiagnostics().Report(diag::err_cannot_open_file) 6860 << PLoc.getFilename() << EC.message(); 6861 } 6862 OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice()) 6863 << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8); 6864 } else { 6865 OS << getContext().getCUIDHash(); 6866 } 6867 } 6868