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>() || 1218 shouldMapVisibilityToDLLExport(D)) && 1219 !GV->isDeclarationForLinker()) 1220 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1221 } 1222 } 1223 1224 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1225 GlobalDecl GD) const { 1226 setDLLImportDLLExport(GV, GD); 1227 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 1228 } 1229 1230 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1231 const NamedDecl *D) const { 1232 setDLLImportDLLExport(GV, D); 1233 setGVPropertiesAux(GV, D); 1234 } 1235 1236 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 1237 const NamedDecl *D) const { 1238 setGlobalVisibility(GV, D); 1239 setDSOLocal(GV); 1240 GV->setPartition(CodeGenOpts.SymbolPartition); 1241 } 1242 1243 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 1244 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 1245 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 1246 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 1247 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 1248 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 1249 } 1250 1251 llvm::GlobalVariable::ThreadLocalMode 1252 CodeGenModule::GetDefaultLLVMTLSModel() const { 1253 switch (CodeGenOpts.getDefaultTLSModel()) { 1254 case CodeGenOptions::GeneralDynamicTLSModel: 1255 return llvm::GlobalVariable::GeneralDynamicTLSModel; 1256 case CodeGenOptions::LocalDynamicTLSModel: 1257 return llvm::GlobalVariable::LocalDynamicTLSModel; 1258 case CodeGenOptions::InitialExecTLSModel: 1259 return llvm::GlobalVariable::InitialExecTLSModel; 1260 case CodeGenOptions::LocalExecTLSModel: 1261 return llvm::GlobalVariable::LocalExecTLSModel; 1262 } 1263 llvm_unreachable("Invalid TLS model!"); 1264 } 1265 1266 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 1267 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 1268 1269 llvm::GlobalValue::ThreadLocalMode TLM; 1270 TLM = GetDefaultLLVMTLSModel(); 1271 1272 // Override the TLS model if it is explicitly specified. 1273 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 1274 TLM = GetLLVMTLSModel(Attr->getModel()); 1275 } 1276 1277 GV->setThreadLocalMode(TLM); 1278 } 1279 1280 static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 1281 StringRef Name) { 1282 const TargetInfo &Target = CGM.getTarget(); 1283 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 1284 } 1285 1286 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 1287 const CPUSpecificAttr *Attr, 1288 unsigned CPUIndex, 1289 raw_ostream &Out) { 1290 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 1291 // supported. 1292 if (Attr) 1293 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 1294 else if (CGM.getTarget().supportsIFunc()) 1295 Out << ".resolver"; 1296 } 1297 1298 static void AppendTargetMangling(const CodeGenModule &CGM, 1299 const TargetAttr *Attr, raw_ostream &Out) { 1300 if (Attr->isDefaultVersion()) 1301 return; 1302 1303 Out << '.'; 1304 const TargetInfo &Target = CGM.getTarget(); 1305 ParsedTargetAttr Info = 1306 Attr->parse([&Target](StringRef LHS, StringRef RHS) { 1307 // Multiversioning doesn't allow "no-${feature}", so we can 1308 // only have "+" prefixes here. 1309 assert(LHS.startswith("+") && RHS.startswith("+") && 1310 "Features should always have a prefix."); 1311 return Target.multiVersionSortPriority(LHS.substr(1)) > 1312 Target.multiVersionSortPriority(RHS.substr(1)); 1313 }); 1314 1315 bool IsFirst = true; 1316 1317 if (!Info.Architecture.empty()) { 1318 IsFirst = false; 1319 Out << "arch_" << Info.Architecture; 1320 } 1321 1322 for (StringRef Feat : Info.Features) { 1323 if (!IsFirst) 1324 Out << '_'; 1325 IsFirst = false; 1326 Out << Feat.substr(1); 1327 } 1328 } 1329 1330 // Returns true if GD is a function decl with internal linkage and 1331 // needs a unique suffix after the mangled name. 1332 static bool isUniqueInternalLinkageDecl(GlobalDecl GD, 1333 CodeGenModule &CGM) { 1334 const Decl *D = GD.getDecl(); 1335 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) && 1336 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); 1337 } 1338 1339 static void AppendTargetClonesMangling(const CodeGenModule &CGM, 1340 const TargetClonesAttr *Attr, 1341 unsigned VersionIndex, 1342 raw_ostream &Out) { 1343 Out << '.'; 1344 StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 1345 if (FeatureStr.startswith("arch=")) 1346 Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1); 1347 else 1348 Out << FeatureStr; 1349 1350 Out << '.' << Attr->getMangledIndex(VersionIndex); 1351 } 1352 1353 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, 1354 const NamedDecl *ND, 1355 bool OmitMultiVersionMangling = false) { 1356 SmallString<256> Buffer; 1357 llvm::raw_svector_ostream Out(Buffer); 1358 MangleContext &MC = CGM.getCXXABI().getMangleContext(); 1359 if (!CGM.getModuleNameHash().empty()) 1360 MC.needsUniqueInternalLinkageNames(); 1361 bool ShouldMangle = MC.shouldMangleDeclName(ND); 1362 if (ShouldMangle) 1363 MC.mangleName(GD.getWithDecl(ND), Out); 1364 else { 1365 IdentifierInfo *II = ND->getIdentifier(); 1366 assert(II && "Attempt to mangle unnamed decl."); 1367 const auto *FD = dyn_cast<FunctionDecl>(ND); 1368 1369 if (FD && 1370 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 1371 Out << "__regcall3__" << II->getName(); 1372 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && 1373 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { 1374 Out << "__device_stub__" << II->getName(); 1375 } else { 1376 Out << II->getName(); 1377 } 1378 } 1379 1380 // Check if the module name hash should be appended for internal linkage 1381 // symbols. This should come before multi-version target suffixes are 1382 // appended. This is to keep the name and module hash suffix of the 1383 // internal linkage function together. The unique suffix should only be 1384 // added when name mangling is done to make sure that the final name can 1385 // be properly demangled. For example, for C functions without prototypes, 1386 // name mangling is not done and the unique suffix should not be appeneded 1387 // then. 1388 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { 1389 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && 1390 "Hash computed when not explicitly requested"); 1391 Out << CGM.getModuleNameHash(); 1392 } 1393 1394 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 1395 if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 1396 switch (FD->getMultiVersionKind()) { 1397 case MultiVersionKind::CPUDispatch: 1398 case MultiVersionKind::CPUSpecific: 1399 AppendCPUSpecificCPUDispatchMangling(CGM, 1400 FD->getAttr<CPUSpecificAttr>(), 1401 GD.getMultiVersionIndex(), Out); 1402 break; 1403 case MultiVersionKind::Target: 1404 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 1405 break; 1406 case MultiVersionKind::TargetClones: 1407 AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), 1408 GD.getMultiVersionIndex(), Out); 1409 break; 1410 case MultiVersionKind::None: 1411 llvm_unreachable("None multiversion type isn't valid here"); 1412 } 1413 } 1414 1415 // Make unique name for device side static file-scope variable for HIP. 1416 if (CGM.getContext().shouldExternalize(ND) && 1417 CGM.getLangOpts().GPURelocatableDeviceCode && 1418 CGM.getLangOpts().CUDAIsDevice) 1419 CGM.printPostfixForExternalizedDecl(Out, ND); 1420 1421 return std::string(Out.str()); 1422 } 1423 1424 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 1425 const FunctionDecl *FD, 1426 StringRef &CurName) { 1427 if (!FD->isMultiVersion()) 1428 return; 1429 1430 // Get the name of what this would be without the 'target' attribute. This 1431 // allows us to lookup the version that was emitted when this wasn't a 1432 // multiversion function. 1433 std::string NonTargetName = 1434 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 1435 GlobalDecl OtherGD; 1436 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 1437 assert(OtherGD.getCanonicalDecl() 1438 .getDecl() 1439 ->getAsFunction() 1440 ->isMultiVersion() && 1441 "Other GD should now be a multiversioned function"); 1442 // OtherFD is the version of this function that was mangled BEFORE 1443 // becoming a MultiVersion function. It potentially needs to be updated. 1444 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 1445 .getDecl() 1446 ->getAsFunction() 1447 ->getMostRecentDecl(); 1448 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 1449 // This is so that if the initial version was already the 'default' 1450 // version, we don't try to update it. 1451 if (OtherName != NonTargetName) { 1452 // Remove instead of erase, since others may have stored the StringRef 1453 // to this. 1454 const auto ExistingRecord = Manglings.find(NonTargetName); 1455 if (ExistingRecord != std::end(Manglings)) 1456 Manglings.remove(&(*ExistingRecord)); 1457 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 1458 StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] = 1459 Result.first->first(); 1460 // If this is the current decl is being created, make sure we update the name. 1461 if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl()) 1462 CurName = OtherNameRef; 1463 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 1464 Entry->setName(OtherName); 1465 } 1466 } 1467 } 1468 1469 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 1470 GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 1471 1472 // Some ABIs don't have constructor variants. Make sure that base and 1473 // complete constructors get mangled the same. 1474 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 1475 if (!getTarget().getCXXABI().hasConstructorVariants()) { 1476 CXXCtorType OrigCtorType = GD.getCtorType(); 1477 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 1478 if (OrigCtorType == Ctor_Base) 1479 CanonicalGD = GlobalDecl(CD, Ctor_Complete); 1480 } 1481 } 1482 1483 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a 1484 // static device variable depends on whether the variable is referenced by 1485 // a host or device host function. Therefore the mangled name cannot be 1486 // cached. 1487 if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) { 1488 auto FoundName = MangledDeclNames.find(CanonicalGD); 1489 if (FoundName != MangledDeclNames.end()) 1490 return FoundName->second; 1491 } 1492 1493 // Keep the first result in the case of a mangling collision. 1494 const auto *ND = cast<NamedDecl>(GD.getDecl()); 1495 std::string MangledName = getMangledNameImpl(*this, GD, ND); 1496 1497 // Ensure either we have different ABIs between host and device compilations, 1498 // says host compilation following MSVC ABI but device compilation follows 1499 // Itanium C++ ABI or, if they follow the same ABI, kernel names after 1500 // mangling should be the same after name stubbing. The later checking is 1501 // very important as the device kernel name being mangled in host-compilation 1502 // is used to resolve the device binaries to be executed. Inconsistent naming 1503 // result in undefined behavior. Even though we cannot check that naming 1504 // directly between host- and device-compilations, the host- and 1505 // device-mangling in host compilation could help catching certain ones. 1506 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || 1507 getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice || 1508 (getContext().getAuxTargetInfo() && 1509 (getContext().getAuxTargetInfo()->getCXXABI() != 1510 getContext().getTargetInfo().getCXXABI())) || 1511 getCUDARuntime().getDeviceSideName(ND) == 1512 getMangledNameImpl( 1513 *this, 1514 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), 1515 ND)); 1516 1517 auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 1518 return MangledDeclNames[CanonicalGD] = Result.first->first(); 1519 } 1520 1521 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 1522 const BlockDecl *BD) { 1523 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 1524 const Decl *D = GD.getDecl(); 1525 1526 SmallString<256> Buffer; 1527 llvm::raw_svector_ostream Out(Buffer); 1528 if (!D) 1529 MangleCtx.mangleGlobalBlock(BD, 1530 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 1531 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 1532 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 1533 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 1534 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 1535 else 1536 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 1537 1538 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 1539 return Result.first->first(); 1540 } 1541 1542 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) { 1543 auto it = MangledDeclNames.begin(); 1544 while (it != MangledDeclNames.end()) { 1545 if (it->second == Name) 1546 return it->first; 1547 it++; 1548 } 1549 return GlobalDecl(); 1550 } 1551 1552 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 1553 return getModule().getNamedValue(Name); 1554 } 1555 1556 /// AddGlobalCtor - Add a function to the list that will be called before 1557 /// main() runs. 1558 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 1559 llvm::Constant *AssociatedData) { 1560 // FIXME: Type coercion of void()* types. 1561 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 1562 } 1563 1564 /// AddGlobalDtor - Add a function to the list that will be called 1565 /// when the module is unloaded. 1566 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, 1567 bool IsDtorAttrFunc) { 1568 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && 1569 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { 1570 DtorsUsingAtExit[Priority].push_back(Dtor); 1571 return; 1572 } 1573 1574 // FIXME: Type coercion of void()* types. 1575 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 1576 } 1577 1578 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 1579 if (Fns.empty()) return; 1580 1581 // Ctor function type is void()*. 1582 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 1583 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 1584 TheModule.getDataLayout().getProgramAddressSpace()); 1585 1586 // Get the type of a ctor entry, { i32, void ()*, i8* }. 1587 llvm::StructType *CtorStructTy = llvm::StructType::get( 1588 Int32Ty, CtorPFTy, VoidPtrTy); 1589 1590 // Construct the constructor and destructor arrays. 1591 ConstantInitBuilder builder(*this); 1592 auto ctors = builder.beginArray(CtorStructTy); 1593 for (const auto &I : Fns) { 1594 auto ctor = ctors.beginStruct(CtorStructTy); 1595 ctor.addInt(Int32Ty, I.Priority); 1596 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 1597 if (I.AssociatedData) 1598 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 1599 else 1600 ctor.addNullPointer(VoidPtrTy); 1601 ctor.finishAndAddTo(ctors); 1602 } 1603 1604 auto list = 1605 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 1606 /*constant*/ false, 1607 llvm::GlobalValue::AppendingLinkage); 1608 1609 // The LTO linker doesn't seem to like it when we set an alignment 1610 // on appending variables. Take it off as a workaround. 1611 list->setAlignment(llvm::None); 1612 1613 Fns.clear(); 1614 } 1615 1616 llvm::GlobalValue::LinkageTypes 1617 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 1618 const auto *D = cast<FunctionDecl>(GD.getDecl()); 1619 1620 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 1621 1622 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 1623 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 1624 1625 if (isa<CXXConstructorDecl>(D) && 1626 cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 1627 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1628 // Our approach to inheriting constructors is fundamentally different from 1629 // that used by the MS ABI, so keep our inheriting constructor thunks 1630 // internal rather than trying to pick an unambiguous mangling for them. 1631 return llvm::GlobalValue::InternalLinkage; 1632 } 1633 1634 return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false); 1635 } 1636 1637 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 1638 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 1639 if (!MDS) return nullptr; 1640 1641 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 1642 } 1643 1644 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 1645 const CGFunctionInfo &Info, 1646 llvm::Function *F, bool IsThunk) { 1647 unsigned CallingConv; 1648 llvm::AttributeList PAL; 1649 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, 1650 /*AttrOnCallSite=*/false, IsThunk); 1651 F->setAttributes(PAL); 1652 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 1653 } 1654 1655 static void removeImageAccessQualifier(std::string& TyName) { 1656 std::string ReadOnlyQual("__read_only"); 1657 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 1658 if (ReadOnlyPos != std::string::npos) 1659 // "+ 1" for the space after access qualifier. 1660 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 1661 else { 1662 std::string WriteOnlyQual("__write_only"); 1663 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 1664 if (WriteOnlyPos != std::string::npos) 1665 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 1666 else { 1667 std::string ReadWriteQual("__read_write"); 1668 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 1669 if (ReadWritePos != std::string::npos) 1670 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 1671 } 1672 } 1673 } 1674 1675 // Returns the address space id that should be produced to the 1676 // kernel_arg_addr_space metadata. This is always fixed to the ids 1677 // as specified in the SPIR 2.0 specification in order to differentiate 1678 // for example in clGetKernelArgInfo() implementation between the address 1679 // spaces with targets without unique mapping to the OpenCL address spaces 1680 // (basically all single AS CPUs). 1681 static unsigned ArgInfoAddressSpace(LangAS AS) { 1682 switch (AS) { 1683 case LangAS::opencl_global: 1684 return 1; 1685 case LangAS::opencl_constant: 1686 return 2; 1687 case LangAS::opencl_local: 1688 return 3; 1689 case LangAS::opencl_generic: 1690 return 4; // Not in SPIR 2.0 specs. 1691 case LangAS::opencl_global_device: 1692 return 5; 1693 case LangAS::opencl_global_host: 1694 return 6; 1695 default: 1696 return 0; // Assume private. 1697 } 1698 } 1699 1700 void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn, 1701 const FunctionDecl *FD, 1702 CodeGenFunction *CGF) { 1703 assert(((FD && CGF) || (!FD && !CGF)) && 1704 "Incorrect use - FD and CGF should either be both null or not!"); 1705 // Create MDNodes that represent the kernel arg metadata. 1706 // Each MDNode is a list in the form of "key", N number of values which is 1707 // the same number of values as their are kernel arguments. 1708 1709 const PrintingPolicy &Policy = Context.getPrintingPolicy(); 1710 1711 // MDNode for the kernel argument address space qualifiers. 1712 SmallVector<llvm::Metadata *, 8> addressQuals; 1713 1714 // MDNode for the kernel argument access qualifiers (images only). 1715 SmallVector<llvm::Metadata *, 8> accessQuals; 1716 1717 // MDNode for the kernel argument type names. 1718 SmallVector<llvm::Metadata *, 8> argTypeNames; 1719 1720 // MDNode for the kernel argument base type names. 1721 SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 1722 1723 // MDNode for the kernel argument type qualifiers. 1724 SmallVector<llvm::Metadata *, 8> argTypeQuals; 1725 1726 // MDNode for the kernel argument names. 1727 SmallVector<llvm::Metadata *, 8> argNames; 1728 1729 if (FD && CGF) 1730 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 1731 const ParmVarDecl *parm = FD->getParamDecl(i); 1732 // Get argument name. 1733 argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 1734 1735 if (!getLangOpts().OpenCL) 1736 continue; 1737 QualType ty = parm->getType(); 1738 std::string typeQuals; 1739 1740 // Get image and pipe access qualifier: 1741 if (ty->isImageType() || ty->isPipeType()) { 1742 const Decl *PDecl = parm; 1743 if (auto *TD = dyn_cast<TypedefType>(ty)) 1744 PDecl = TD->getDecl(); 1745 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 1746 if (A && A->isWriteOnly()) 1747 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 1748 else if (A && A->isReadWrite()) 1749 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 1750 else 1751 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 1752 } else 1753 accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 1754 1755 auto getTypeSpelling = [&](QualType Ty) { 1756 auto typeName = Ty.getUnqualifiedType().getAsString(Policy); 1757 1758 if (Ty.isCanonical()) { 1759 StringRef typeNameRef = typeName; 1760 // Turn "unsigned type" to "utype" 1761 if (typeNameRef.consume_front("unsigned ")) 1762 return std::string("u") + typeNameRef.str(); 1763 if (typeNameRef.consume_front("signed ")) 1764 return typeNameRef.str(); 1765 } 1766 1767 return typeName; 1768 }; 1769 1770 if (ty->isPointerType()) { 1771 QualType pointeeTy = ty->getPointeeType(); 1772 1773 // Get address qualifier. 1774 addressQuals.push_back( 1775 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 1776 ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 1777 1778 // Get argument type name. 1779 std::string typeName = getTypeSpelling(pointeeTy) + "*"; 1780 std::string baseTypeName = 1781 getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 1782 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1783 argBaseTypeNames.push_back( 1784 llvm::MDString::get(VMContext, baseTypeName)); 1785 1786 // Get argument type qualifiers: 1787 if (ty.isRestrictQualified()) 1788 typeQuals = "restrict"; 1789 if (pointeeTy.isConstQualified() || 1790 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 1791 typeQuals += typeQuals.empty() ? "const" : " const"; 1792 if (pointeeTy.isVolatileQualified()) 1793 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 1794 } else { 1795 uint32_t AddrSpc = 0; 1796 bool isPipe = ty->isPipeType(); 1797 if (ty->isImageType() || isPipe) 1798 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 1799 1800 addressQuals.push_back( 1801 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 1802 1803 // Get argument type name. 1804 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; 1805 std::string typeName = getTypeSpelling(ty); 1806 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); 1807 1808 // Remove access qualifiers on images 1809 // (as they are inseparable from type in clang implementation, 1810 // but OpenCL spec provides a special query to get access qualifier 1811 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 1812 if (ty->isImageType()) { 1813 removeImageAccessQualifier(typeName); 1814 removeImageAccessQualifier(baseTypeName); 1815 } 1816 1817 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1818 argBaseTypeNames.push_back( 1819 llvm::MDString::get(VMContext, baseTypeName)); 1820 1821 if (isPipe) 1822 typeQuals = "pipe"; 1823 } 1824 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 1825 } 1826 1827 if (getLangOpts().OpenCL) { 1828 Fn->setMetadata("kernel_arg_addr_space", 1829 llvm::MDNode::get(VMContext, addressQuals)); 1830 Fn->setMetadata("kernel_arg_access_qual", 1831 llvm::MDNode::get(VMContext, accessQuals)); 1832 Fn->setMetadata("kernel_arg_type", 1833 llvm::MDNode::get(VMContext, argTypeNames)); 1834 Fn->setMetadata("kernel_arg_base_type", 1835 llvm::MDNode::get(VMContext, argBaseTypeNames)); 1836 Fn->setMetadata("kernel_arg_type_qual", 1837 llvm::MDNode::get(VMContext, argTypeQuals)); 1838 } 1839 if (getCodeGenOpts().EmitOpenCLArgMetadata || 1840 getCodeGenOpts().HIPSaveKernelArgName) 1841 Fn->setMetadata("kernel_arg_name", 1842 llvm::MDNode::get(VMContext, argNames)); 1843 } 1844 1845 /// Determines whether the language options require us to model 1846 /// unwind exceptions. We treat -fexceptions as mandating this 1847 /// except under the fragile ObjC ABI with only ObjC exceptions 1848 /// enabled. This means, for example, that C with -fexceptions 1849 /// enables this. 1850 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 1851 // If exceptions are completely disabled, obviously this is false. 1852 if (!LangOpts.Exceptions) return false; 1853 1854 // If C++ exceptions are enabled, this is true. 1855 if (LangOpts.CXXExceptions) return true; 1856 1857 // If ObjC exceptions are enabled, this depends on the ABI. 1858 if (LangOpts.ObjCExceptions) { 1859 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 1860 } 1861 1862 return true; 1863 } 1864 1865 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 1866 const CXXMethodDecl *MD) { 1867 // Check that the type metadata can ever actually be used by a call. 1868 if (!CGM.getCodeGenOpts().LTOUnit || 1869 !CGM.HasHiddenLTOVisibility(MD->getParent())) 1870 return false; 1871 1872 // Only functions whose address can be taken with a member function pointer 1873 // need this sort of type metadata. 1874 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) && 1875 !isa<CXXDestructorDecl>(MD); 1876 } 1877 1878 std::vector<const CXXRecordDecl *> 1879 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 1880 llvm::SetVector<const CXXRecordDecl *> MostBases; 1881 1882 std::function<void (const CXXRecordDecl *)> CollectMostBases; 1883 CollectMostBases = [&](const CXXRecordDecl *RD) { 1884 if (RD->getNumBases() == 0) 1885 MostBases.insert(RD); 1886 for (const CXXBaseSpecifier &B : RD->bases()) 1887 CollectMostBases(B.getType()->getAsCXXRecordDecl()); 1888 }; 1889 CollectMostBases(RD); 1890 return MostBases.takeVector(); 1891 } 1892 1893 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 1894 llvm::Function *F) { 1895 llvm::AttrBuilder B(F->getContext()); 1896 1897 if (CodeGenOpts.UnwindTables) 1898 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 1899 1900 if (CodeGenOpts.StackClashProtector) 1901 B.addAttribute("probe-stack", "inline-asm"); 1902 1903 if (!hasUnwindExceptions(LangOpts)) 1904 B.addAttribute(llvm::Attribute::NoUnwind); 1905 1906 if (!D || !D->hasAttr<NoStackProtectorAttr>()) { 1907 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 1908 B.addAttribute(llvm::Attribute::StackProtect); 1909 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 1910 B.addAttribute(llvm::Attribute::StackProtectStrong); 1911 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 1912 B.addAttribute(llvm::Attribute::StackProtectReq); 1913 } 1914 1915 if (!D) { 1916 // If we don't have a declaration to control inlining, the function isn't 1917 // explicitly marked as alwaysinline for semantic reasons, and inlining is 1918 // disabled, mark the function as noinline. 1919 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 1920 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 1921 B.addAttribute(llvm::Attribute::NoInline); 1922 1923 F->addFnAttrs(B); 1924 return; 1925 } 1926 1927 // Track whether we need to add the optnone LLVM attribute, 1928 // starting with the default for this optimization level. 1929 bool ShouldAddOptNone = 1930 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 1931 // We can't add optnone in the following cases, it won't pass the verifier. 1932 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 1933 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 1934 1935 // Add optnone, but do so only if the function isn't always_inline. 1936 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && 1937 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1938 B.addAttribute(llvm::Attribute::OptimizeNone); 1939 1940 // OptimizeNone implies noinline; we should not be inlining such functions. 1941 B.addAttribute(llvm::Attribute::NoInline); 1942 1943 // We still need to handle naked functions even though optnone subsumes 1944 // much of their semantics. 1945 if (D->hasAttr<NakedAttr>()) 1946 B.addAttribute(llvm::Attribute::Naked); 1947 1948 // OptimizeNone wins over OptimizeForSize and MinSize. 1949 F->removeFnAttr(llvm::Attribute::OptimizeForSize); 1950 F->removeFnAttr(llvm::Attribute::MinSize); 1951 } else if (D->hasAttr<NakedAttr>()) { 1952 // Naked implies noinline: we should not be inlining such functions. 1953 B.addAttribute(llvm::Attribute::Naked); 1954 B.addAttribute(llvm::Attribute::NoInline); 1955 } else if (D->hasAttr<NoDuplicateAttr>()) { 1956 B.addAttribute(llvm::Attribute::NoDuplicate); 1957 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1958 // Add noinline if the function isn't always_inline. 1959 B.addAttribute(llvm::Attribute::NoInline); 1960 } else if (D->hasAttr<AlwaysInlineAttr>() && 1961 !F->hasFnAttribute(llvm::Attribute::NoInline)) { 1962 // (noinline wins over always_inline, and we can't specify both in IR) 1963 B.addAttribute(llvm::Attribute::AlwaysInline); 1964 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 1965 // If we're not inlining, then force everything that isn't always_inline to 1966 // carry an explicit noinline attribute. 1967 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 1968 B.addAttribute(llvm::Attribute::NoInline); 1969 } else { 1970 // Otherwise, propagate the inline hint attribute and potentially use its 1971 // absence to mark things as noinline. 1972 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1973 // Search function and template pattern redeclarations for inline. 1974 auto CheckForInline = [](const FunctionDecl *FD) { 1975 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 1976 return Redecl->isInlineSpecified(); 1977 }; 1978 if (any_of(FD->redecls(), CheckRedeclForInline)) 1979 return true; 1980 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 1981 if (!Pattern) 1982 return false; 1983 return any_of(Pattern->redecls(), CheckRedeclForInline); 1984 }; 1985 if (CheckForInline(FD)) { 1986 B.addAttribute(llvm::Attribute::InlineHint); 1987 } else if (CodeGenOpts.getInlining() == 1988 CodeGenOptions::OnlyHintInlining && 1989 !FD->isInlined() && 1990 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1991 B.addAttribute(llvm::Attribute::NoInline); 1992 } 1993 } 1994 } 1995 1996 // Add other optimization related attributes if we are optimizing this 1997 // function. 1998 if (!D->hasAttr<OptimizeNoneAttr>()) { 1999 if (D->hasAttr<ColdAttr>()) { 2000 if (!ShouldAddOptNone) 2001 B.addAttribute(llvm::Attribute::OptimizeForSize); 2002 B.addAttribute(llvm::Attribute::Cold); 2003 } 2004 if (D->hasAttr<HotAttr>()) 2005 B.addAttribute(llvm::Attribute::Hot); 2006 if (D->hasAttr<MinSizeAttr>()) 2007 B.addAttribute(llvm::Attribute::MinSize); 2008 } 2009 2010 F->addFnAttrs(B); 2011 2012 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 2013 if (alignment) 2014 F->setAlignment(llvm::Align(alignment)); 2015 2016 if (!D->hasAttr<AlignedAttr>()) 2017 if (LangOpts.FunctionAlignment) 2018 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 2019 2020 // Some C++ ABIs require 2-byte alignment for member functions, in order to 2021 // reserve a bit for differentiating between virtual and non-virtual member 2022 // functions. If the current target's C++ ABI requires this and this is a 2023 // member function, set its alignment accordingly. 2024 if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 2025 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 2026 F->setAlignment(llvm::Align(2)); 2027 } 2028 2029 // In the cross-dso CFI mode with canonical jump tables, we want !type 2030 // attributes on definitions only. 2031 if (CodeGenOpts.SanitizeCfiCrossDso && 2032 CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 2033 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 2034 // Skip available_externally functions. They won't be codegen'ed in the 2035 // current module anyway. 2036 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 2037 CreateFunctionTypeMetadataForIcall(FD, F); 2038 } 2039 } 2040 2041 // Emit type metadata on member functions for member function pointer checks. 2042 // These are only ever necessary on definitions; we're guaranteed that the 2043 // definition will be present in the LTO unit as a result of LTO visibility. 2044 auto *MD = dyn_cast<CXXMethodDecl>(D); 2045 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 2046 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 2047 llvm::Metadata *Id = 2048 CreateMetadataIdentifierForType(Context.getMemberPointerType( 2049 MD->getType(), Context.getRecordType(Base).getTypePtr())); 2050 F->addTypeMetadata(0, Id); 2051 } 2052 } 2053 } 2054 2055 void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D, 2056 llvm::Function *F) { 2057 if (D->hasAttr<StrictFPAttr>()) { 2058 llvm::AttrBuilder FuncAttrs(F->getContext()); 2059 FuncAttrs.addAttribute("strictfp"); 2060 F->addFnAttrs(FuncAttrs); 2061 } 2062 } 2063 2064 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 2065 const Decl *D = GD.getDecl(); 2066 if (isa_and_nonnull<NamedDecl>(D)) 2067 setGVProperties(GV, GD); 2068 else 2069 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 2070 2071 if (D && D->hasAttr<UsedAttr>()) 2072 addUsedOrCompilerUsedGlobal(GV); 2073 2074 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) { 2075 const auto *VD = cast<VarDecl>(D); 2076 if (VD->getType().isConstQualified() && 2077 VD->getStorageDuration() == SD_Static) 2078 addUsedOrCompilerUsedGlobal(GV); 2079 } 2080 } 2081 2082 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 2083 llvm::AttrBuilder &Attrs) { 2084 // Add target-cpu and target-features attributes to functions. If 2085 // we have a decl for the function and it has a target attribute then 2086 // parse that and add it to the feature set. 2087 StringRef TargetCPU = getTarget().getTargetOpts().CPU; 2088 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 2089 std::vector<std::string> Features; 2090 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 2091 FD = FD ? FD->getMostRecentDecl() : FD; 2092 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 2093 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 2094 const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; 2095 bool AddedAttr = false; 2096 if (TD || SD || TC) { 2097 llvm::StringMap<bool> FeatureMap; 2098 getContext().getFunctionFeatureMap(FeatureMap, GD); 2099 2100 // Produce the canonical string for this set of features. 2101 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 2102 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 2103 2104 // Now add the target-cpu and target-features to the function. 2105 // While we populated the feature map above, we still need to 2106 // get and parse the target attribute so we can get the cpu for 2107 // the function. 2108 if (TD) { 2109 ParsedTargetAttr ParsedAttr = TD->parse(); 2110 if (!ParsedAttr.Architecture.empty() && 2111 getTarget().isValidCPUName(ParsedAttr.Architecture)) { 2112 TargetCPU = ParsedAttr.Architecture; 2113 TuneCPU = ""; // Clear the tune CPU. 2114 } 2115 if (!ParsedAttr.Tune.empty() && 2116 getTarget().isValidCPUName(ParsedAttr.Tune)) 2117 TuneCPU = ParsedAttr.Tune; 2118 } 2119 2120 if (SD) { 2121 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can 2122 // favor this processor. 2123 TuneCPU = getTarget().getCPUSpecificTuneName( 2124 SD->getCPUName(GD.getMultiVersionIndex())->getName()); 2125 } 2126 } else { 2127 // Otherwise just add the existing target cpu and target features to the 2128 // function. 2129 Features = getTarget().getTargetOpts().Features; 2130 } 2131 2132 if (!TargetCPU.empty()) { 2133 Attrs.addAttribute("target-cpu", TargetCPU); 2134 AddedAttr = true; 2135 } 2136 if (!TuneCPU.empty()) { 2137 Attrs.addAttribute("tune-cpu", TuneCPU); 2138 AddedAttr = true; 2139 } 2140 if (!Features.empty()) { 2141 llvm::sort(Features); 2142 Attrs.addAttribute("target-features", llvm::join(Features, ",")); 2143 AddedAttr = true; 2144 } 2145 2146 return AddedAttr; 2147 } 2148 2149 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 2150 llvm::GlobalObject *GO) { 2151 const Decl *D = GD.getDecl(); 2152 SetCommonAttributes(GD, GO); 2153 2154 if (D) { 2155 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2156 if (D->hasAttr<RetainAttr>()) 2157 addUsedGlobal(GV); 2158 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 2159 GV->addAttribute("bss-section", SA->getName()); 2160 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 2161 GV->addAttribute("data-section", SA->getName()); 2162 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 2163 GV->addAttribute("rodata-section", SA->getName()); 2164 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2165 GV->addAttribute("relro-section", SA->getName()); 2166 } 2167 2168 if (auto *F = dyn_cast<llvm::Function>(GO)) { 2169 if (D->hasAttr<RetainAttr>()) 2170 addUsedGlobal(F); 2171 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 2172 if (!D->getAttr<SectionAttr>()) 2173 F->addFnAttr("implicit-section-name", SA->getName()); 2174 2175 llvm::AttrBuilder Attrs(F->getContext()); 2176 if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 2177 // We know that GetCPUAndFeaturesAttributes will always have the 2178 // newest set, since it has the newest possible FunctionDecl, so the 2179 // new ones should replace the old. 2180 llvm::AttributeMask RemoveAttrs; 2181 RemoveAttrs.addAttribute("target-cpu"); 2182 RemoveAttrs.addAttribute("target-features"); 2183 RemoveAttrs.addAttribute("tune-cpu"); 2184 F->removeFnAttrs(RemoveAttrs); 2185 F->addFnAttrs(Attrs); 2186 } 2187 } 2188 2189 if (const auto *CSA = D->getAttr<CodeSegAttr>()) 2190 GO->setSection(CSA->getName()); 2191 else if (const auto *SA = D->getAttr<SectionAttr>()) 2192 GO->setSection(SA->getName()); 2193 } 2194 2195 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 2196 } 2197 2198 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 2199 llvm::Function *F, 2200 const CGFunctionInfo &FI) { 2201 const Decl *D = GD.getDecl(); 2202 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 2203 SetLLVMFunctionAttributesForDefinition(D, F); 2204 2205 F->setLinkage(llvm::Function::InternalLinkage); 2206 2207 setNonAliasAttributes(GD, F); 2208 } 2209 2210 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 2211 // Set linkage and visibility in case we never see a definition. 2212 LinkageInfo LV = ND->getLinkageAndVisibility(); 2213 // Don't set internal linkage on declarations. 2214 // "extern_weak" is overloaded in LLVM; we probably should have 2215 // separate linkage types for this. 2216 if (isExternallyVisible(LV.getLinkage()) && 2217 (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 2218 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 2219 } 2220 2221 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 2222 llvm::Function *F) { 2223 // Only if we are checking indirect calls. 2224 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 2225 return; 2226 2227 // Non-static class methods are handled via vtable or member function pointer 2228 // checks elsewhere. 2229 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2230 return; 2231 2232 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 2233 F->addTypeMetadata(0, MD); 2234 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 2235 2236 // Emit a hash-based bit set entry for cross-DSO calls. 2237 if (CodeGenOpts.SanitizeCfiCrossDso) 2238 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 2239 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 2240 } 2241 2242 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 2243 bool IsIncompleteFunction, 2244 bool IsThunk) { 2245 2246 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 2247 // If this is an intrinsic function, set the function's attributes 2248 // to the intrinsic's attributes. 2249 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 2250 return; 2251 } 2252 2253 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2254 2255 if (!IsIncompleteFunction) 2256 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2257 IsThunk); 2258 2259 // Add the Returned attribute for "this", except for iOS 5 and earlier 2260 // where substantial code, including the libstdc++ dylib, was compiled with 2261 // GCC and does not actually return "this". 2262 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 2263 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 2264 assert(!F->arg_empty() && 2265 F->arg_begin()->getType() 2266 ->canLosslesslyBitCastTo(F->getReturnType()) && 2267 "unexpected this return"); 2268 F->addParamAttr(0, llvm::Attribute::Returned); 2269 } 2270 2271 // Only a few attributes are set on declarations; these may later be 2272 // overridden by a definition. 2273 2274 setLinkageForGV(F, FD); 2275 setGVProperties(F, FD); 2276 2277 // Setup target-specific attributes. 2278 if (!IsIncompleteFunction && F->isDeclaration()) 2279 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 2280 2281 if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 2282 F->setSection(CSA->getName()); 2283 else if (const auto *SA = FD->getAttr<SectionAttr>()) 2284 F->setSection(SA->getName()); 2285 2286 if (const auto *EA = FD->getAttr<ErrorAttr>()) { 2287 if (EA->isError()) 2288 F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); 2289 else if (EA->isWarning()) 2290 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); 2291 } 2292 2293 // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2294 if (FD->isInlineBuiltinDeclaration()) { 2295 const FunctionDecl *FDBody; 2296 bool HasBody = FD->hasBody(FDBody); 2297 (void)HasBody; 2298 assert(HasBody && "Inline builtin declarations should always have an " 2299 "available body!"); 2300 if (shouldEmitFunction(FDBody)) 2301 F->addFnAttr(llvm::Attribute::NoBuiltin); 2302 } 2303 2304 if (FD->isReplaceableGlobalAllocationFunction()) { 2305 // A replaceable global allocation function does not act like a builtin by 2306 // default, only if it is invoked by a new-expression or delete-expression. 2307 F->addFnAttr(llvm::Attribute::NoBuiltin); 2308 } 2309 2310 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 2311 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2312 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 2313 if (MD->isVirtual()) 2314 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2315 2316 // Don't emit entries for function declarations in the cross-DSO mode. This 2317 // is handled with better precision by the receiving DSO. But if jump tables 2318 // are non-canonical then we need type metadata in order to produce the local 2319 // jump table. 2320 if (!CodeGenOpts.SanitizeCfiCrossDso || 2321 !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 2322 CreateFunctionTypeMetadataForIcall(FD, F); 2323 2324 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 2325 getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 2326 2327 if (const auto *CB = FD->getAttr<CallbackAttr>()) { 2328 // Annotate the callback behavior as metadata: 2329 // - The callback callee (as argument number). 2330 // - The callback payloads (as argument numbers). 2331 llvm::LLVMContext &Ctx = F->getContext(); 2332 llvm::MDBuilder MDB(Ctx); 2333 2334 // The payload indices are all but the first one in the encoding. The first 2335 // identifies the callback callee. 2336 int CalleeIdx = *CB->encoding_begin(); 2337 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 2338 F->addMetadata(llvm::LLVMContext::MD_callback, 2339 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 2340 CalleeIdx, PayloadIndices, 2341 /* VarArgsArePassed */ false)})); 2342 } 2343 } 2344 2345 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2346 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2347 "Only globals with definition can force usage."); 2348 LLVMUsed.emplace_back(GV); 2349 } 2350 2351 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 2352 assert(!GV->isDeclaration() && 2353 "Only globals with definition can force usage."); 2354 LLVMCompilerUsed.emplace_back(GV); 2355 } 2356 2357 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { 2358 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2359 "Only globals with definition can force usage."); 2360 if (getTriple().isOSBinFormatELF()) 2361 LLVMCompilerUsed.emplace_back(GV); 2362 else 2363 LLVMUsed.emplace_back(GV); 2364 } 2365 2366 static void emitUsed(CodeGenModule &CGM, StringRef Name, 2367 std::vector<llvm::WeakTrackingVH> &List) { 2368 // Don't create llvm.used if there is no need. 2369 if (List.empty()) 2370 return; 2371 2372 // Convert List to what ConstantArray needs. 2373 SmallVector<llvm::Constant*, 8> UsedArray; 2374 UsedArray.resize(List.size()); 2375 for (unsigned i = 0, e = List.size(); i != e; ++i) { 2376 UsedArray[i] = 2377 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2378 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 2379 } 2380 2381 if (UsedArray.empty()) 2382 return; 2383 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 2384 2385 auto *GV = new llvm::GlobalVariable( 2386 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 2387 llvm::ConstantArray::get(ATy, UsedArray), Name); 2388 2389 GV->setSection("llvm.metadata"); 2390 } 2391 2392 void CodeGenModule::emitLLVMUsed() { 2393 emitUsed(*this, "llvm.used", LLVMUsed); 2394 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 2395 } 2396 2397 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 2398 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 2399 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2400 } 2401 2402 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 2403 llvm::SmallString<32> Opt; 2404 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2405 if (Opt.empty()) 2406 return; 2407 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2408 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2409 } 2410 2411 void CodeGenModule::AddDependentLib(StringRef Lib) { 2412 auto &C = getLLVMContext(); 2413 if (getTarget().getTriple().isOSBinFormatELF()) { 2414 ELFDependentLibraries.push_back( 2415 llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 2416 return; 2417 } 2418 2419 llvm::SmallString<24> Opt; 2420 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 2421 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2422 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 2423 } 2424 2425 /// Add link options implied by the given module, including modules 2426 /// it depends on, using a postorder walk. 2427 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 2428 SmallVectorImpl<llvm::MDNode *> &Metadata, 2429 llvm::SmallPtrSet<Module *, 16> &Visited) { 2430 // Import this module's parent. 2431 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 2432 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 2433 } 2434 2435 // Import this module's dependencies. 2436 for (Module *Import : llvm::reverse(Mod->Imports)) { 2437 if (Visited.insert(Import).second) 2438 addLinkOptionsPostorder(CGM, Import, Metadata, Visited); 2439 } 2440 2441 // Add linker options to link against the libraries/frameworks 2442 // described by this module. 2443 llvm::LLVMContext &Context = CGM.getLLVMContext(); 2444 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 2445 2446 // For modules that use export_as for linking, use that module 2447 // name instead. 2448 if (Mod->UseExportAsModuleLinkName) 2449 return; 2450 2451 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { 2452 // Link against a framework. Frameworks are currently Darwin only, so we 2453 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 2454 if (LL.IsFramework) { 2455 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"), 2456 llvm::MDString::get(Context, LL.Library)}; 2457 2458 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2459 continue; 2460 } 2461 2462 // Link against a library. 2463 if (IsELF) { 2464 llvm::Metadata *Args[2] = { 2465 llvm::MDString::get(Context, "lib"), 2466 llvm::MDString::get(Context, LL.Library), 2467 }; 2468 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2469 } else { 2470 llvm::SmallString<24> Opt; 2471 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); 2472 auto *OptString = llvm::MDString::get(Context, Opt); 2473 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 2474 } 2475 } 2476 } 2477 2478 void CodeGenModule::EmitModuleLinkOptions() { 2479 // Collect the set of all of the modules we want to visit to emit link 2480 // options, which is essentially the imported modules and all of their 2481 // non-explicit child modules. 2482 llvm::SetVector<clang::Module *> LinkModules; 2483 llvm::SmallPtrSet<clang::Module *, 16> Visited; 2484 SmallVector<clang::Module *, 16> Stack; 2485 2486 // Seed the stack with imported modules. 2487 for (Module *M : ImportedModules) { 2488 // Do not add any link flags when an implementation TU of a module imports 2489 // a header of that same module. 2490 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 2491 !getLangOpts().isCompilingModule()) 2492 continue; 2493 if (Visited.insert(M).second) 2494 Stack.push_back(M); 2495 } 2496 2497 // Find all of the modules to import, making a little effort to prune 2498 // non-leaf modules. 2499 while (!Stack.empty()) { 2500 clang::Module *Mod = Stack.pop_back_val(); 2501 2502 bool AnyChildren = false; 2503 2504 // Visit the submodules of this module. 2505 for (const auto &SM : Mod->submodules()) { 2506 // Skip explicit children; they need to be explicitly imported to be 2507 // linked against. 2508 if (SM->IsExplicit) 2509 continue; 2510 2511 if (Visited.insert(SM).second) { 2512 Stack.push_back(SM); 2513 AnyChildren = true; 2514 } 2515 } 2516 2517 // We didn't find any children, so add this module to the list of 2518 // modules to link against. 2519 if (!AnyChildren) { 2520 LinkModules.insert(Mod); 2521 } 2522 } 2523 2524 // Add link options for all of the imported modules in reverse topological 2525 // order. We don't do anything to try to order import link flags with respect 2526 // to linker options inserted by things like #pragma comment(). 2527 SmallVector<llvm::MDNode *, 16> MetadataArgs; 2528 Visited.clear(); 2529 for (Module *M : LinkModules) 2530 if (Visited.insert(M).second) 2531 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 2532 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 2533 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 2534 2535 // Add the linker options metadata flag. 2536 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 2537 for (auto *MD : LinkerOptionsMetadata) 2538 NMD->addOperand(MD); 2539 } 2540 2541 void CodeGenModule::EmitDeferred() { 2542 // Emit deferred declare target declarations. 2543 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 2544 getOpenMPRuntime().emitDeferredTargetDecls(); 2545 2546 // Emit code for any potentially referenced deferred decls. Since a 2547 // previously unused static decl may become used during the generation of code 2548 // for a static function, iterate until no changes are made. 2549 2550 if (!DeferredVTables.empty()) { 2551 EmitDeferredVTables(); 2552 2553 // Emitting a vtable doesn't directly cause more vtables to 2554 // become deferred, although it can cause functions to be 2555 // emitted that then need those vtables. 2556 assert(DeferredVTables.empty()); 2557 } 2558 2559 // Emit CUDA/HIP static device variables referenced by host code only. 2560 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still 2561 // needed for further handling. 2562 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 2563 llvm::append_range(DeferredDeclsToEmit, 2564 getContext().CUDADeviceVarODRUsedByHost); 2565 2566 // Stop if we're out of both deferred vtables and deferred declarations. 2567 if (DeferredDeclsToEmit.empty()) 2568 return; 2569 2570 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 2571 // work, it will not interfere with this. 2572 std::vector<GlobalDecl> CurDeclsToEmit; 2573 CurDeclsToEmit.swap(DeferredDeclsToEmit); 2574 2575 for (GlobalDecl &D : CurDeclsToEmit) { 2576 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 2577 // to get GlobalValue with exactly the type we need, not something that 2578 // might had been created for another decl with the same mangled name but 2579 // different type. 2580 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 2581 GetAddrOfGlobal(D, ForDefinition)); 2582 2583 // In case of different address spaces, we may still get a cast, even with 2584 // IsForDefinition equal to true. Query mangled names table to get 2585 // GlobalValue. 2586 if (!GV) 2587 GV = GetGlobalValue(getMangledName(D)); 2588 2589 // Make sure GetGlobalValue returned non-null. 2590 assert(GV); 2591 2592 // Check to see if we've already emitted this. This is necessary 2593 // for a couple of reasons: first, decls can end up in the 2594 // deferred-decls queue multiple times, and second, decls can end 2595 // up with definitions in unusual ways (e.g. by an extern inline 2596 // function acquiring a strong function redefinition). Just 2597 // ignore these cases. 2598 if (!GV->isDeclaration()) 2599 continue; 2600 2601 // If this is OpenMP, check if it is legal to emit this global normally. 2602 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 2603 continue; 2604 2605 // Otherwise, emit the definition and move on to the next one. 2606 EmitGlobalDefinition(D, GV); 2607 2608 // If we found out that we need to emit more decls, do that recursively. 2609 // This has the advantage that the decls are emitted in a DFS and related 2610 // ones are close together, which is convenient for testing. 2611 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 2612 EmitDeferred(); 2613 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 2614 } 2615 } 2616 } 2617 2618 void CodeGenModule::EmitVTablesOpportunistically() { 2619 // Try to emit external vtables as available_externally if they have emitted 2620 // all inlined virtual functions. It runs after EmitDeferred() and therefore 2621 // is not allowed to create new references to things that need to be emitted 2622 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 2623 2624 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 2625 && "Only emit opportunistic vtables with optimizations"); 2626 2627 for (const CXXRecordDecl *RD : OpportunisticVTables) { 2628 assert(getVTables().isVTableExternal(RD) && 2629 "This queue should only contain external vtables"); 2630 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 2631 VTables.GenerateClassData(RD); 2632 } 2633 OpportunisticVTables.clear(); 2634 } 2635 2636 void CodeGenModule::EmitGlobalAnnotations() { 2637 if (Annotations.empty()) 2638 return; 2639 2640 // Create a new global variable for the ConstantStruct in the Module. 2641 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 2642 Annotations[0]->getType(), Annotations.size()), Annotations); 2643 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 2644 llvm::GlobalValue::AppendingLinkage, 2645 Array, "llvm.global.annotations"); 2646 gv->setSection(AnnotationSection); 2647 } 2648 2649 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 2650 llvm::Constant *&AStr = AnnotationStrings[Str]; 2651 if (AStr) 2652 return AStr; 2653 2654 // Not found yet, create a new global. 2655 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 2656 auto *gv = 2657 new llvm::GlobalVariable(getModule(), s->getType(), true, 2658 llvm::GlobalValue::PrivateLinkage, s, ".str"); 2659 gv->setSection(AnnotationSection); 2660 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2661 AStr = gv; 2662 return gv; 2663 } 2664 2665 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 2666 SourceManager &SM = getContext().getSourceManager(); 2667 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2668 if (PLoc.isValid()) 2669 return EmitAnnotationString(PLoc.getFilename()); 2670 return EmitAnnotationString(SM.getBufferName(Loc)); 2671 } 2672 2673 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 2674 SourceManager &SM = getContext().getSourceManager(); 2675 PresumedLoc PLoc = SM.getPresumedLoc(L); 2676 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 2677 SM.getExpansionLineNumber(L); 2678 return llvm::ConstantInt::get(Int32Ty, LineNo); 2679 } 2680 2681 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 2682 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 2683 if (Exprs.empty()) 2684 return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy); 2685 2686 llvm::FoldingSetNodeID ID; 2687 for (Expr *E : Exprs) { 2688 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 2689 } 2690 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 2691 if (Lookup) 2692 return Lookup; 2693 2694 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 2695 LLVMArgs.reserve(Exprs.size()); 2696 ConstantEmitter ConstEmiter(*this); 2697 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 2698 const auto *CE = cast<clang::ConstantExpr>(E); 2699 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 2700 CE->getType()); 2701 }); 2702 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 2703 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 2704 llvm::GlobalValue::PrivateLinkage, Struct, 2705 ".args"); 2706 GV->setSection(AnnotationSection); 2707 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2708 auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy); 2709 2710 Lookup = Bitcasted; 2711 return Bitcasted; 2712 } 2713 2714 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 2715 const AnnotateAttr *AA, 2716 SourceLocation L) { 2717 // Get the globals for file name, annotation, and the line number. 2718 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 2719 *UnitGV = EmitAnnotationUnit(L), 2720 *LineNoCst = EmitAnnotationLineNo(L), 2721 *Args = EmitAnnotationArgs(AA); 2722 2723 llvm::Constant *GVInGlobalsAS = GV; 2724 if (GV->getAddressSpace() != 2725 getDataLayout().getDefaultGlobalsAddressSpace()) { 2726 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( 2727 GV, GV->getValueType()->getPointerTo( 2728 getDataLayout().getDefaultGlobalsAddressSpace())); 2729 } 2730 2731 // Create the ConstantStruct for the global annotation. 2732 llvm::Constant *Fields[] = { 2733 llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy), 2734 llvm::ConstantExpr::getBitCast(AnnoGV, GlobalsInt8PtrTy), 2735 llvm::ConstantExpr::getBitCast(UnitGV, GlobalsInt8PtrTy), 2736 LineNoCst, 2737 Args, 2738 }; 2739 return llvm::ConstantStruct::getAnon(Fields); 2740 } 2741 2742 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 2743 llvm::GlobalValue *GV) { 2744 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2745 // Get the struct elements for these annotations. 2746 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2747 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 2748 } 2749 2750 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 2751 SourceLocation Loc) const { 2752 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2753 // NoSanitize by function name. 2754 if (NoSanitizeL.containsFunction(Kind, Fn->getName())) 2755 return true; 2756 // NoSanitize by location. 2757 if (Loc.isValid()) 2758 return NoSanitizeL.containsLocation(Kind, Loc); 2759 // If location is unknown, this may be a compiler-generated function. Assume 2760 // it's located in the main file. 2761 auto &SM = Context.getSourceManager(); 2762 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2763 return NoSanitizeL.containsFile(Kind, MainFile->getName()); 2764 } 2765 return false; 2766 } 2767 2768 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, 2769 llvm::GlobalVariable *GV, 2770 SourceLocation Loc, QualType Ty, 2771 StringRef Category) const { 2772 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2773 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category)) 2774 return true; 2775 if (NoSanitizeL.containsLocation(Kind, 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(Kind, 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) 2830 return *V; 2831 // Next, check the source location. 2832 if (Loc.isValid()) { 2833 Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind); 2834 if (V) 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) 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 (!isa<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 !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) { 3795 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3796 setDSOLocal(Entry); 3797 } 3798 3799 // If there are two attempts to define the same mangled name, issue an 3800 // error. 3801 if (IsForDefinition && !Entry->isDeclaration()) { 3802 GlobalDecl OtherGD; 3803 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 3804 // to make sure that we issue an error only once. 3805 if (lookupRepresentativeDecl(MangledName, OtherGD) && 3806 (GD.getCanonicalDecl().getDecl() != 3807 OtherGD.getCanonicalDecl().getDecl()) && 3808 DiagnosedConflictingDefinitions.insert(GD).second) { 3809 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3810 << MangledName; 3811 getDiags().Report(OtherGD.getDecl()->getLocation(), 3812 diag::note_previous_definition); 3813 } 3814 } 3815 3816 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 3817 (Entry->getValueType() == Ty)) { 3818 return Entry; 3819 } 3820 3821 // Make sure the result is of the correct type. 3822 // (If function is requested for a definition, we always need to create a new 3823 // function, not just return a bitcast.) 3824 if (!IsForDefinition) 3825 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 3826 } 3827 3828 // This function doesn't have a complete type (for example, the return 3829 // type is an incomplete struct). Use a fake type instead, and make 3830 // sure not to try to set attributes. 3831 bool IsIncompleteFunction = false; 3832 3833 llvm::FunctionType *FTy; 3834 if (isa<llvm::FunctionType>(Ty)) { 3835 FTy = cast<llvm::FunctionType>(Ty); 3836 } else { 3837 FTy = llvm::FunctionType::get(VoidTy, false); 3838 IsIncompleteFunction = true; 3839 } 3840 3841 llvm::Function *F = 3842 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 3843 Entry ? StringRef() : MangledName, &getModule()); 3844 3845 // If we already created a function with the same mangled name (but different 3846 // type) before, take its name and add it to the list of functions to be 3847 // replaced with F at the end of CodeGen. 3848 // 3849 // This happens if there is a prototype for a function (e.g. "int f()") and 3850 // then a definition of a different type (e.g. "int f(int x)"). 3851 if (Entry) { 3852 F->takeName(Entry); 3853 3854 // This might be an implementation of a function without a prototype, in 3855 // which case, try to do special replacement of calls which match the new 3856 // prototype. The really key thing here is that we also potentially drop 3857 // arguments from the call site so as to make a direct call, which makes the 3858 // inliner happier and suppresses a number of optimizer warnings (!) about 3859 // dropping arguments. 3860 if (!Entry->use_empty()) { 3861 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 3862 Entry->removeDeadConstantUsers(); 3863 } 3864 3865 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 3866 F, Entry->getValueType()->getPointerTo()); 3867 addGlobalValReplacement(Entry, BC); 3868 } 3869 3870 assert(F->getName() == MangledName && "name was uniqued!"); 3871 if (D) 3872 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 3873 if (ExtraAttrs.hasFnAttrs()) { 3874 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); 3875 F->addFnAttrs(B); 3876 } 3877 3878 if (!DontDefer) { 3879 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 3880 // each other bottoming out with the base dtor. Therefore we emit non-base 3881 // dtors on usage, even if there is no dtor definition in the TU. 3882 if (D && isa<CXXDestructorDecl>(D) && 3883 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 3884 GD.getDtorType())) 3885 addDeferredDeclToEmit(GD); 3886 3887 // This is the first use or definition of a mangled name. If there is a 3888 // deferred decl with this name, remember that we need to emit it at the end 3889 // of the file. 3890 auto DDI = DeferredDecls.find(MangledName); 3891 if (DDI != DeferredDecls.end()) { 3892 // Move the potentially referenced deferred decl to the 3893 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 3894 // don't need it anymore). 3895 addDeferredDeclToEmit(DDI->second); 3896 DeferredDecls.erase(DDI); 3897 3898 // Otherwise, there are cases we have to worry about where we're 3899 // using a declaration for which we must emit a definition but where 3900 // we might not find a top-level definition: 3901 // - member functions defined inline in their classes 3902 // - friend functions defined inline in some class 3903 // - special member functions with implicit definitions 3904 // If we ever change our AST traversal to walk into class methods, 3905 // this will be unnecessary. 3906 // 3907 // We also don't emit a definition for a function if it's going to be an 3908 // entry in a vtable, unless it's already marked as used. 3909 } else if (getLangOpts().CPlusPlus && D) { 3910 // Look for a declaration that's lexically in a record. 3911 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 3912 FD = FD->getPreviousDecl()) { 3913 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 3914 if (FD->doesThisDeclarationHaveABody()) { 3915 addDeferredDeclToEmit(GD.getWithDecl(FD)); 3916 break; 3917 } 3918 } 3919 } 3920 } 3921 } 3922 3923 // Make sure the result is of the requested type. 3924 if (!IsIncompleteFunction) { 3925 assert(F->getFunctionType() == Ty); 3926 return F; 3927 } 3928 3929 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3930 return llvm::ConstantExpr::getBitCast(F, PTy); 3931 } 3932 3933 /// GetAddrOfFunction - Return the address of the given function. If Ty is 3934 /// non-null, then this function will use the specified type if it has to 3935 /// create it (this occurs when we see a definition of the function). 3936 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 3937 llvm::Type *Ty, 3938 bool ForVTable, 3939 bool DontDefer, 3940 ForDefinition_t IsForDefinition) { 3941 assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() && 3942 "consteval function should never be emitted"); 3943 // If there was no specific requested type, just convert it now. 3944 if (!Ty) { 3945 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3946 Ty = getTypes().ConvertType(FD->getType()); 3947 } 3948 3949 // Devirtualized destructor calls may come through here instead of via 3950 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 3951 // of the complete destructor when necessary. 3952 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 3953 if (getTarget().getCXXABI().isMicrosoft() && 3954 GD.getDtorType() == Dtor_Complete && 3955 DD->getParent()->getNumVBases() == 0) 3956 GD = GlobalDecl(DD, Dtor_Base); 3957 } 3958 3959 StringRef MangledName = getMangledName(GD); 3960 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 3961 /*IsThunk=*/false, llvm::AttributeList(), 3962 IsForDefinition); 3963 // Returns kernel handle for HIP kernel stub function. 3964 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && 3965 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { 3966 auto *Handle = getCUDARuntime().getKernelHandle( 3967 cast<llvm::Function>(F->stripPointerCasts()), GD); 3968 if (IsForDefinition) 3969 return F; 3970 return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo()); 3971 } 3972 return F; 3973 } 3974 3975 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { 3976 llvm::GlobalValue *F = 3977 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts()); 3978 3979 return llvm::ConstantExpr::getBitCast(llvm::NoCFIValue::get(F), 3980 llvm::Type::getInt8PtrTy(VMContext)); 3981 } 3982 3983 static const FunctionDecl * 3984 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 3985 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 3986 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3987 3988 IdentifierInfo &CII = C.Idents.get(Name); 3989 for (const auto *Result : DC->lookup(&CII)) 3990 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 3991 return FD; 3992 3993 if (!C.getLangOpts().CPlusPlus) 3994 return nullptr; 3995 3996 // Demangle the premangled name from getTerminateFn() 3997 IdentifierInfo &CXXII = 3998 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 3999 ? C.Idents.get("terminate") 4000 : C.Idents.get(Name); 4001 4002 for (const auto &N : {"__cxxabiv1", "std"}) { 4003 IdentifierInfo &NS = C.Idents.get(N); 4004 for (const auto *Result : DC->lookup(&NS)) { 4005 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 4006 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 4007 for (const auto *Result : LSD->lookup(&NS)) 4008 if ((ND = dyn_cast<NamespaceDecl>(Result))) 4009 break; 4010 4011 if (ND) 4012 for (const auto *Result : ND->lookup(&CXXII)) 4013 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4014 return FD; 4015 } 4016 } 4017 4018 return nullptr; 4019 } 4020 4021 /// CreateRuntimeFunction - Create a new runtime function with the specified 4022 /// type and name. 4023 llvm::FunctionCallee 4024 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 4025 llvm::AttributeList ExtraAttrs, bool Local, 4026 bool AssumeConvergent) { 4027 if (AssumeConvergent) { 4028 ExtraAttrs = 4029 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 4030 } 4031 4032 llvm::Constant *C = 4033 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 4034 /*DontDefer=*/false, /*IsThunk=*/false, 4035 ExtraAttrs); 4036 4037 if (auto *F = dyn_cast<llvm::Function>(C)) { 4038 if (F->empty()) { 4039 F->setCallingConv(getRuntimeCC()); 4040 4041 // In Windows Itanium environments, try to mark runtime functions 4042 // dllimport. For Mingw and MSVC, don't. We don't really know if the user 4043 // will link their standard library statically or dynamically. Marking 4044 // functions imported when they are not imported can cause linker errors 4045 // and warnings. 4046 if (!Local && getTriple().isWindowsItaniumEnvironment() && 4047 !getCodeGenOpts().LTOVisibilityPublicStd) { 4048 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 4049 if (!FD || FD->hasAttr<DLLImportAttr>()) { 4050 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 4051 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 4052 } 4053 } 4054 setDSOLocal(F); 4055 } 4056 } 4057 4058 return {FTy, C}; 4059 } 4060 4061 /// isTypeConstant - Determine whether an object of this type can be emitted 4062 /// as a constant. 4063 /// 4064 /// If ExcludeCtor is true, the duration when the object's constructor runs 4065 /// will not be considered. The caller will need to verify that the object is 4066 /// not written to during its construction. 4067 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 4068 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 4069 return false; 4070 4071 if (Context.getLangOpts().CPlusPlus) { 4072 if (const CXXRecordDecl *Record 4073 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 4074 return ExcludeCtor && !Record->hasMutableFields() && 4075 Record->hasTrivialDestructor(); 4076 } 4077 4078 return true; 4079 } 4080 4081 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 4082 /// create and return an llvm GlobalVariable with the specified type and address 4083 /// space. If there is something in the module with the specified name, return 4084 /// it potentially bitcasted to the right type. 4085 /// 4086 /// If D is non-null, it specifies a decl that correspond to this. This is used 4087 /// to set the attributes on the global when it is first created. 4088 /// 4089 /// If IsForDefinition is true, it is guaranteed that an actual global with 4090 /// type Ty will be returned, not conversion of a variable with the same 4091 /// mangled name but some other type. 4092 llvm::Constant * 4093 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4094 LangAS AddrSpace, const VarDecl *D, 4095 ForDefinition_t IsForDefinition) { 4096 // Lookup the entry, lazily creating it if necessary. 4097 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4098 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 4099 if (Entry) { 4100 if (WeakRefReferences.erase(Entry)) { 4101 if (D && !D->hasAttr<WeakAttr>()) 4102 Entry->setLinkage(llvm::Function::ExternalLinkage); 4103 } 4104 4105 // Handle dropped DLL attributes. 4106 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 4107 !shouldMapVisibilityToDLLExport(D)) 4108 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4109 4110 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 4111 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 4112 4113 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 4114 return Entry; 4115 4116 // If there are two attempts to define the same mangled name, issue an 4117 // error. 4118 if (IsForDefinition && !Entry->isDeclaration()) { 4119 GlobalDecl OtherGD; 4120 const VarDecl *OtherD; 4121 4122 // Check that D is not yet in DiagnosedConflictingDefinitions is required 4123 // to make sure that we issue an error only once. 4124 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 4125 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 4126 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 4127 OtherD->hasInit() && 4128 DiagnosedConflictingDefinitions.insert(D).second) { 4129 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4130 << MangledName; 4131 getDiags().Report(OtherGD.getDecl()->getLocation(), 4132 diag::note_previous_definition); 4133 } 4134 } 4135 4136 // Make sure the result is of the correct type. 4137 if (Entry->getType()->getAddressSpace() != TargetAS) { 4138 return llvm::ConstantExpr::getAddrSpaceCast(Entry, 4139 Ty->getPointerTo(TargetAS)); 4140 } 4141 4142 // (If global is requested for a definition, we always need to create a new 4143 // global, not just return a bitcast.) 4144 if (!IsForDefinition) 4145 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS)); 4146 } 4147 4148 auto DAddrSpace = GetGlobalVarAddressSpace(D); 4149 4150 auto *GV = new llvm::GlobalVariable( 4151 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 4152 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 4153 getContext().getTargetAddressSpace(DAddrSpace)); 4154 4155 // If we already created a global with the same mangled name (but different 4156 // type) before, take its name and remove it from its parent. 4157 if (Entry) { 4158 GV->takeName(Entry); 4159 4160 if (!Entry->use_empty()) { 4161 llvm::Constant *NewPtrForOldDecl = 4162 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 4163 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4164 } 4165 4166 Entry->eraseFromParent(); 4167 } 4168 4169 // This is the first use or definition of a mangled name. If there is a 4170 // deferred decl with this name, remember that we need to emit it at the end 4171 // of the file. 4172 auto DDI = DeferredDecls.find(MangledName); 4173 if (DDI != DeferredDecls.end()) { 4174 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 4175 // list, and remove it from DeferredDecls (since we don't need it anymore). 4176 addDeferredDeclToEmit(DDI->second); 4177 DeferredDecls.erase(DDI); 4178 } 4179 4180 // Handle things which are present even on external declarations. 4181 if (D) { 4182 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 4183 getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 4184 4185 // FIXME: This code is overly simple and should be merged with other global 4186 // handling. 4187 GV->setConstant(isTypeConstant(D->getType(), false)); 4188 4189 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4190 4191 setLinkageForGV(GV, D); 4192 4193 if (D->getTLSKind()) { 4194 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4195 CXXThreadLocals.push_back(D); 4196 setTLSMode(GV, *D); 4197 } 4198 4199 setGVProperties(GV, D); 4200 4201 // If required by the ABI, treat declarations of static data members with 4202 // inline initializers as definitions. 4203 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 4204 EmitGlobalVarDefinition(D); 4205 } 4206 4207 // Emit section information for extern variables. 4208 if (D->hasExternalStorage()) { 4209 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 4210 GV->setSection(SA->getName()); 4211 } 4212 4213 // Handle XCore specific ABI requirements. 4214 if (getTriple().getArch() == llvm::Triple::xcore && 4215 D->getLanguageLinkage() == CLanguageLinkage && 4216 D->getType().isConstant(Context) && 4217 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 4218 GV->setSection(".cp.rodata"); 4219 4220 // Check if we a have a const declaration with an initializer, we may be 4221 // able to emit it as available_externally to expose it's value to the 4222 // optimizer. 4223 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 4224 D->getType().isConstQualified() && !GV->hasInitializer() && 4225 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 4226 const auto *Record = 4227 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 4228 bool HasMutableFields = Record && Record->hasMutableFields(); 4229 if (!HasMutableFields) { 4230 const VarDecl *InitDecl; 4231 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4232 if (InitExpr) { 4233 ConstantEmitter emitter(*this); 4234 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 4235 if (Init) { 4236 auto *InitType = Init->getType(); 4237 if (GV->getValueType() != InitType) { 4238 // The type of the initializer does not match the definition. 4239 // This happens when an initializer has a different type from 4240 // the type of the global (because of padding at the end of a 4241 // structure for instance). 4242 GV->setName(StringRef()); 4243 // Make a new global with the correct type, this is now guaranteed 4244 // to work. 4245 auto *NewGV = cast<llvm::GlobalVariable>( 4246 GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4247 ->stripPointerCasts()); 4248 4249 // Erase the old global, since it is no longer used. 4250 GV->eraseFromParent(); 4251 GV = NewGV; 4252 } else { 4253 GV->setInitializer(Init); 4254 GV->setConstant(true); 4255 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 4256 } 4257 emitter.finalize(GV); 4258 } 4259 } 4260 } 4261 } 4262 } 4263 4264 if (GV->isDeclaration()) { 4265 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4266 // External HIP managed variables needed to be recorded for transformation 4267 // in both device and host compilations. 4268 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4269 D->hasExternalStorage()) 4270 getCUDARuntime().handleVarRegistration(D, *GV); 4271 } 4272 4273 LangAS ExpectedAS = 4274 D ? D->getType().getAddressSpace() 4275 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4276 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4277 if (DAddrSpace != ExpectedAS) { 4278 return getTargetCodeGenInfo().performAddrSpaceCast( 4279 *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS)); 4280 } 4281 4282 return GV; 4283 } 4284 4285 llvm::Constant * 4286 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 4287 const Decl *D = GD.getDecl(); 4288 4289 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 4290 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 4291 /*DontDefer=*/false, IsForDefinition); 4292 4293 if (isa<CXXMethodDecl>(D)) { 4294 auto FInfo = 4295 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 4296 auto Ty = getTypes().GetFunctionType(*FInfo); 4297 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4298 IsForDefinition); 4299 } 4300 4301 if (isa<FunctionDecl>(D)) { 4302 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4303 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4304 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4305 IsForDefinition); 4306 } 4307 4308 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 4309 } 4310 4311 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 4312 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 4313 unsigned Alignment) { 4314 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 4315 llvm::GlobalVariable *OldGV = nullptr; 4316 4317 if (GV) { 4318 // Check if the variable has the right type. 4319 if (GV->getValueType() == Ty) 4320 return GV; 4321 4322 // Because C++ name mangling, the only way we can end up with an already 4323 // existing global with the same name is if it has been declared extern "C". 4324 assert(GV->isDeclaration() && "Declaration has wrong type!"); 4325 OldGV = GV; 4326 } 4327 4328 // Create a new variable. 4329 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 4330 Linkage, nullptr, Name); 4331 4332 if (OldGV) { 4333 // Replace occurrences of the old variable if needed. 4334 GV->takeName(OldGV); 4335 4336 if (!OldGV->use_empty()) { 4337 llvm::Constant *NewPtrForOldDecl = 4338 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 4339 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 4340 } 4341 4342 OldGV->eraseFromParent(); 4343 } 4344 4345 if (supportsCOMDAT() && GV->isWeakForLinker() && 4346 !GV->hasAvailableExternallyLinkage()) 4347 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 4348 4349 GV->setAlignment(llvm::MaybeAlign(Alignment)); 4350 4351 return GV; 4352 } 4353 4354 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 4355 /// given global variable. If Ty is non-null and if the global doesn't exist, 4356 /// then it will be created with the specified type instead of whatever the 4357 /// normal requested type would be. If IsForDefinition is true, it is guaranteed 4358 /// that an actual global with type Ty will be returned, not conversion of a 4359 /// variable with the same mangled name but some other type. 4360 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 4361 llvm::Type *Ty, 4362 ForDefinition_t IsForDefinition) { 4363 assert(D->hasGlobalStorage() && "Not a global variable"); 4364 QualType ASTTy = D->getType(); 4365 if (!Ty) 4366 Ty = getTypes().ConvertTypeForMem(ASTTy); 4367 4368 StringRef MangledName = getMangledName(D); 4369 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 4370 IsForDefinition); 4371 } 4372 4373 /// CreateRuntimeVariable - Create a new runtime global variable with the 4374 /// specified type and name. 4375 llvm::Constant * 4376 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 4377 StringRef Name) { 4378 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 4379 : LangAS::Default; 4380 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 4381 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 4382 return Ret; 4383 } 4384 4385 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 4386 assert(!D->getInit() && "Cannot emit definite definitions here!"); 4387 4388 StringRef MangledName = getMangledName(D); 4389 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 4390 4391 // We already have a definition, not declaration, with the same mangled name. 4392 // Emitting of declaration is not required (and actually overwrites emitted 4393 // definition). 4394 if (GV && !GV->isDeclaration()) 4395 return; 4396 4397 // If we have not seen a reference to this variable yet, place it into the 4398 // deferred declarations table to be emitted if needed later. 4399 if (!MustBeEmitted(D) && !GV) { 4400 DeferredDecls[MangledName] = D; 4401 return; 4402 } 4403 4404 // The tentative definition is the only definition. 4405 EmitGlobalVarDefinition(D); 4406 } 4407 4408 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 4409 EmitExternalVarDeclaration(D); 4410 } 4411 4412 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 4413 return Context.toCharUnitsFromBits( 4414 getDataLayout().getTypeStoreSizeInBits(Ty)); 4415 } 4416 4417 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 4418 if (LangOpts.OpenCL) { 4419 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 4420 assert(AS == LangAS::opencl_global || 4421 AS == LangAS::opencl_global_device || 4422 AS == LangAS::opencl_global_host || 4423 AS == LangAS::opencl_constant || 4424 AS == LangAS::opencl_local || 4425 AS >= LangAS::FirstTargetAddressSpace); 4426 return AS; 4427 } 4428 4429 if (LangOpts.SYCLIsDevice && 4430 (!D || D->getType().getAddressSpace() == LangAS::Default)) 4431 return LangAS::sycl_global; 4432 4433 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 4434 if (D && D->hasAttr<CUDAConstantAttr>()) 4435 return LangAS::cuda_constant; 4436 else if (D && D->hasAttr<CUDASharedAttr>()) 4437 return LangAS::cuda_shared; 4438 else if (D && D->hasAttr<CUDADeviceAttr>()) 4439 return LangAS::cuda_device; 4440 else if (D && D->getType().isConstQualified()) 4441 return LangAS::cuda_constant; 4442 else 4443 return LangAS::cuda_device; 4444 } 4445 4446 if (LangOpts.OpenMP) { 4447 LangAS AS; 4448 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 4449 return AS; 4450 } 4451 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 4452 } 4453 4454 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 4455 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 4456 if (LangOpts.OpenCL) 4457 return LangAS::opencl_constant; 4458 if (LangOpts.SYCLIsDevice) 4459 return LangAS::sycl_global; 4460 if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) 4461 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) 4462 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up 4463 // with OpVariable instructions with Generic storage class which is not 4464 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V 4465 // UniformConstant storage class is not viable as pointers to it may not be 4466 // casted to Generic pointers which are used to model HIP's "flat" pointers. 4467 return LangAS::cuda_device; 4468 if (auto AS = getTarget().getConstantAddressSpace()) 4469 return *AS; 4470 return LangAS::Default; 4471 } 4472 4473 // In address space agnostic languages, string literals are in default address 4474 // space in AST. However, certain targets (e.g. amdgcn) request them to be 4475 // emitted in constant address space in LLVM IR. To be consistent with other 4476 // parts of AST, string literal global variables in constant address space 4477 // need to be casted to default address space before being put into address 4478 // map and referenced by other part of CodeGen. 4479 // In OpenCL, string literals are in constant address space in AST, therefore 4480 // they should not be casted to default address space. 4481 static llvm::Constant * 4482 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 4483 llvm::GlobalVariable *GV) { 4484 llvm::Constant *Cast = GV; 4485 if (!CGM.getLangOpts().OpenCL) { 4486 auto AS = CGM.GetGlobalConstantAddressSpace(); 4487 if (AS != LangAS::Default) 4488 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 4489 CGM, GV, AS, LangAS::Default, 4490 GV->getValueType()->getPointerTo( 4491 CGM.getContext().getTargetAddressSpace(LangAS::Default))); 4492 } 4493 return Cast; 4494 } 4495 4496 template<typename SomeDecl> 4497 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 4498 llvm::GlobalValue *GV) { 4499 if (!getLangOpts().CPlusPlus) 4500 return; 4501 4502 // Must have 'used' attribute, or else inline assembly can't rely on 4503 // the name existing. 4504 if (!D->template hasAttr<UsedAttr>()) 4505 return; 4506 4507 // Must have internal linkage and an ordinary name. 4508 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 4509 return; 4510 4511 // Must be in an extern "C" context. Entities declared directly within 4512 // a record are not extern "C" even if the record is in such a context. 4513 const SomeDecl *First = D->getFirstDecl(); 4514 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 4515 return; 4516 4517 // OK, this is an internal linkage entity inside an extern "C" linkage 4518 // specification. Make a note of that so we can give it the "expected" 4519 // mangled name if nothing else is using that name. 4520 std::pair<StaticExternCMap::iterator, bool> R = 4521 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 4522 4523 // If we have multiple internal linkage entities with the same name 4524 // in extern "C" regions, none of them gets that name. 4525 if (!R.second) 4526 R.first->second = nullptr; 4527 } 4528 4529 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 4530 if (!CGM.supportsCOMDAT()) 4531 return false; 4532 4533 if (D.hasAttr<SelectAnyAttr>()) 4534 return true; 4535 4536 GVALinkage Linkage; 4537 if (auto *VD = dyn_cast<VarDecl>(&D)) 4538 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 4539 else 4540 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 4541 4542 switch (Linkage) { 4543 case GVA_Internal: 4544 case GVA_AvailableExternally: 4545 case GVA_StrongExternal: 4546 return false; 4547 case GVA_DiscardableODR: 4548 case GVA_StrongODR: 4549 return true; 4550 } 4551 llvm_unreachable("No such linkage"); 4552 } 4553 4554 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 4555 llvm::GlobalObject &GO) { 4556 if (!shouldBeInCOMDAT(*this, D)) 4557 return; 4558 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 4559 } 4560 4561 /// Pass IsTentative as true if you want to create a tentative definition. 4562 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 4563 bool IsTentative) { 4564 // OpenCL global variables of sampler type are translated to function calls, 4565 // therefore no need to be translated. 4566 QualType ASTTy = D->getType(); 4567 if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 4568 return; 4569 4570 // If this is OpenMP device, check if it is legal to emit this global 4571 // normally. 4572 if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 4573 OpenMPRuntime->emitTargetGlobalVariable(D)) 4574 return; 4575 4576 llvm::TrackingVH<llvm::Constant> Init; 4577 bool NeedsGlobalCtor = false; 4578 bool NeedsGlobalDtor = 4579 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 4580 4581 const VarDecl *InitDecl; 4582 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4583 4584 Optional<ConstantEmitter> emitter; 4585 4586 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 4587 // as part of their declaration." Sema has already checked for 4588 // error cases, so we just need to set Init to UndefValue. 4589 bool IsCUDASharedVar = 4590 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 4591 // Shadows of initialized device-side global variables are also left 4592 // undefined. 4593 // Managed Variables should be initialized on both host side and device side. 4594 bool IsCUDAShadowVar = 4595 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4596 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 4597 D->hasAttr<CUDASharedAttr>()); 4598 bool IsCUDADeviceShadowVar = 4599 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4600 (D->getType()->isCUDADeviceBuiltinSurfaceType() || 4601 D->getType()->isCUDADeviceBuiltinTextureType()); 4602 if (getLangOpts().CUDA && 4603 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 4604 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4605 else if (D->hasAttr<LoaderUninitializedAttr>()) 4606 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4607 else if (!InitExpr) { 4608 // This is a tentative definition; tentative definitions are 4609 // implicitly initialized with { 0 }. 4610 // 4611 // Note that tentative definitions are only emitted at the end of 4612 // a translation unit, so they should never have incomplete 4613 // type. In addition, EmitTentativeDefinition makes sure that we 4614 // never attempt to emit a tentative definition if a real one 4615 // exists. A use may still exists, however, so we still may need 4616 // to do a RAUW. 4617 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 4618 Init = EmitNullConstant(D->getType()); 4619 } else { 4620 initializedGlobalDecl = GlobalDecl(D); 4621 emitter.emplace(*this); 4622 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 4623 if (!Initializer) { 4624 QualType T = InitExpr->getType(); 4625 if (D->getType()->isReferenceType()) 4626 T = D->getType(); 4627 4628 if (getLangOpts().CPlusPlus) { 4629 if (InitDecl->hasFlexibleArrayInit(getContext())) 4630 ErrorUnsupported(D, "flexible array initializer"); 4631 Init = EmitNullConstant(T); 4632 NeedsGlobalCtor = true; 4633 } else { 4634 ErrorUnsupported(D, "static initializer"); 4635 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 4636 } 4637 } else { 4638 Init = Initializer; 4639 // We don't need an initializer, so remove the entry for the delayed 4640 // initializer position (just in case this entry was delayed) if we 4641 // also don't need to register a destructor. 4642 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 4643 DelayedCXXInitPosition.erase(D); 4644 4645 #ifndef NDEBUG 4646 CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) + 4647 InitDecl->getFlexibleArrayInitChars(getContext()); 4648 CharUnits CstSize = CharUnits::fromQuantity( 4649 getDataLayout().getTypeAllocSize(Init->getType())); 4650 assert(VarSize == CstSize && "Emitted constant has unexpected size"); 4651 #endif 4652 } 4653 } 4654 4655 llvm::Type* InitType = Init->getType(); 4656 llvm::Constant *Entry = 4657 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 4658 4659 // Strip off pointer casts if we got them. 4660 Entry = Entry->stripPointerCasts(); 4661 4662 // Entry is now either a Function or GlobalVariable. 4663 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 4664 4665 // We have a definition after a declaration with the wrong type. 4666 // We must make a new GlobalVariable* and update everything that used OldGV 4667 // (a declaration or tentative definition) with the new GlobalVariable* 4668 // (which will be a definition). 4669 // 4670 // This happens if there is a prototype for a global (e.g. 4671 // "extern int x[];") and then a definition of a different type (e.g. 4672 // "int x[10];"). This also happens when an initializer has a different type 4673 // from the type of the global (this happens with unions). 4674 if (!GV || GV->getValueType() != InitType || 4675 GV->getType()->getAddressSpace() != 4676 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 4677 4678 // Move the old entry aside so that we'll create a new one. 4679 Entry->setName(StringRef()); 4680 4681 // Make a new global with the correct type, this is now guaranteed to work. 4682 GV = cast<llvm::GlobalVariable>( 4683 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4684 ->stripPointerCasts()); 4685 4686 // Replace all uses of the old global with the new global 4687 llvm::Constant *NewPtrForOldDecl = 4688 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 4689 Entry->getType()); 4690 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4691 4692 // Erase the old global, since it is no longer used. 4693 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 4694 } 4695 4696 MaybeHandleStaticInExternC(D, GV); 4697 4698 if (D->hasAttr<AnnotateAttr>()) 4699 AddGlobalAnnotations(D, GV); 4700 4701 // Set the llvm linkage type as appropriate. 4702 llvm::GlobalValue::LinkageTypes Linkage = 4703 getLLVMLinkageVarDefinition(D, GV->isConstant()); 4704 4705 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 4706 // the device. [...]" 4707 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 4708 // __device__, declares a variable that: [...] 4709 // Is accessible from all the threads within the grid and from the host 4710 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 4711 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 4712 if (GV && LangOpts.CUDA) { 4713 if (LangOpts.CUDAIsDevice) { 4714 if (Linkage != llvm::GlobalValue::InternalLinkage && 4715 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 4716 D->getType()->isCUDADeviceBuiltinSurfaceType() || 4717 D->getType()->isCUDADeviceBuiltinTextureType())) 4718 GV->setExternallyInitialized(true); 4719 } else { 4720 getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 4721 } 4722 getCUDARuntime().handleVarRegistration(D, *GV); 4723 } 4724 4725 GV->setInitializer(Init); 4726 if (emitter) 4727 emitter->finalize(GV); 4728 4729 // If it is safe to mark the global 'constant', do so now. 4730 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 4731 isTypeConstant(D->getType(), true)); 4732 4733 // If it is in a read-only section, mark it 'constant'. 4734 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4735 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 4736 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 4737 GV->setConstant(true); 4738 } 4739 4740 CharUnits AlignVal = getContext().getDeclAlign(D); 4741 // Check for alignment specifed in an 'omp allocate' directive. 4742 if (llvm::Optional<CharUnits> AlignValFromAllocate = 4743 getOMPAllocateAlignment(D)) 4744 AlignVal = *AlignValFromAllocate; 4745 GV->setAlignment(AlignVal.getAsAlign()); 4746 4747 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 4748 // function is only defined alongside the variable, not also alongside 4749 // callers. Normally, all accesses to a thread_local go through the 4750 // thread-wrapper in order to ensure initialization has occurred, underlying 4751 // variable will never be used other than the thread-wrapper, so it can be 4752 // converted to internal linkage. 4753 // 4754 // However, if the variable has the 'constinit' attribute, it _can_ be 4755 // referenced directly, without calling the thread-wrapper, so the linkage 4756 // must not be changed. 4757 // 4758 // Additionally, if the variable isn't plain external linkage, e.g. if it's 4759 // weak or linkonce, the de-duplication semantics are important to preserve, 4760 // so we don't change the linkage. 4761 if (D->getTLSKind() == VarDecl::TLS_Dynamic && 4762 Linkage == llvm::GlobalValue::ExternalLinkage && 4763 Context.getTargetInfo().getTriple().isOSDarwin() && 4764 !D->hasAttr<ConstInitAttr>()) 4765 Linkage = llvm::GlobalValue::InternalLinkage; 4766 4767 GV->setLinkage(Linkage); 4768 if (D->hasAttr<DLLImportAttr>()) 4769 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 4770 else if (D->hasAttr<DLLExportAttr>()) 4771 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 4772 else 4773 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 4774 4775 if (Linkage == llvm::GlobalVariable::CommonLinkage) { 4776 // common vars aren't constant even if declared const. 4777 GV->setConstant(false); 4778 // Tentative definition of global variables may be initialized with 4779 // non-zero null pointers. In this case they should have weak linkage 4780 // since common linkage must have zero initializer and must not have 4781 // explicit section therefore cannot have non-zero initial value. 4782 if (!GV->getInitializer()->isNullValue()) 4783 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 4784 } 4785 4786 setNonAliasAttributes(D, GV); 4787 4788 if (D->getTLSKind() && !GV->isThreadLocal()) { 4789 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4790 CXXThreadLocals.push_back(D); 4791 setTLSMode(GV, *D); 4792 } 4793 4794 maybeSetTrivialComdat(*D, *GV); 4795 4796 // Emit the initializer function if necessary. 4797 if (NeedsGlobalCtor || NeedsGlobalDtor) 4798 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 4799 4800 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor); 4801 4802 // Emit global variable debug information. 4803 if (CGDebugInfo *DI = getModuleDebugInfo()) 4804 if (getCodeGenOpts().hasReducedDebugInfo()) 4805 DI->EmitGlobalVariable(GV, D); 4806 } 4807 4808 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 4809 if (CGDebugInfo *DI = getModuleDebugInfo()) 4810 if (getCodeGenOpts().hasReducedDebugInfo()) { 4811 QualType ASTTy = D->getType(); 4812 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 4813 llvm::Constant *GV = 4814 GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 4815 DI->EmitExternalVariable( 4816 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 4817 } 4818 } 4819 4820 static bool isVarDeclStrongDefinition(const ASTContext &Context, 4821 CodeGenModule &CGM, const VarDecl *D, 4822 bool NoCommon) { 4823 // Don't give variables common linkage if -fno-common was specified unless it 4824 // was overridden by a NoCommon attribute. 4825 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 4826 return true; 4827 4828 // C11 6.9.2/2: 4829 // A declaration of an identifier for an object that has file scope without 4830 // an initializer, and without a storage-class specifier or with the 4831 // storage-class specifier static, constitutes a tentative definition. 4832 if (D->getInit() || D->hasExternalStorage()) 4833 return true; 4834 4835 // A variable cannot be both common and exist in a section. 4836 if (D->hasAttr<SectionAttr>()) 4837 return true; 4838 4839 // A variable cannot be both common and exist in a section. 4840 // We don't try to determine which is the right section in the front-end. 4841 // If no specialized section name is applicable, it will resort to default. 4842 if (D->hasAttr<PragmaClangBSSSectionAttr>() || 4843 D->hasAttr<PragmaClangDataSectionAttr>() || 4844 D->hasAttr<PragmaClangRelroSectionAttr>() || 4845 D->hasAttr<PragmaClangRodataSectionAttr>()) 4846 return true; 4847 4848 // Thread local vars aren't considered common linkage. 4849 if (D->getTLSKind()) 4850 return true; 4851 4852 // Tentative definitions marked with WeakImportAttr are true definitions. 4853 if (D->hasAttr<WeakImportAttr>()) 4854 return true; 4855 4856 // A variable cannot be both common and exist in a comdat. 4857 if (shouldBeInCOMDAT(CGM, *D)) 4858 return true; 4859 4860 // Declarations with a required alignment do not have common linkage in MSVC 4861 // mode. 4862 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4863 if (D->hasAttr<AlignedAttr>()) 4864 return true; 4865 QualType VarType = D->getType(); 4866 if (Context.isAlignmentRequired(VarType)) 4867 return true; 4868 4869 if (const auto *RT = VarType->getAs<RecordType>()) { 4870 const RecordDecl *RD = RT->getDecl(); 4871 for (const FieldDecl *FD : RD->fields()) { 4872 if (FD->isBitField()) 4873 continue; 4874 if (FD->hasAttr<AlignedAttr>()) 4875 return true; 4876 if (Context.isAlignmentRequired(FD->getType())) 4877 return true; 4878 } 4879 } 4880 } 4881 4882 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 4883 // common symbols, so symbols with greater alignment requirements cannot be 4884 // common. 4885 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 4886 // alignments for common symbols via the aligncomm directive, so this 4887 // restriction only applies to MSVC environments. 4888 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 4889 Context.getTypeAlignIfKnown(D->getType()) > 4890 Context.toBits(CharUnits::fromQuantity(32))) 4891 return true; 4892 4893 return false; 4894 } 4895 4896 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 4897 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 4898 if (Linkage == GVA_Internal) 4899 return llvm::Function::InternalLinkage; 4900 4901 if (D->hasAttr<WeakAttr>()) 4902 return llvm::GlobalVariable::WeakAnyLinkage; 4903 4904 if (const auto *FD = D->getAsFunction()) 4905 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 4906 return llvm::GlobalVariable::LinkOnceAnyLinkage; 4907 4908 // We are guaranteed to have a strong definition somewhere else, 4909 // so we can use available_externally linkage. 4910 if (Linkage == GVA_AvailableExternally) 4911 return llvm::GlobalValue::AvailableExternallyLinkage; 4912 4913 // Note that Apple's kernel linker doesn't support symbol 4914 // coalescing, so we need to avoid linkonce and weak linkages there. 4915 // Normally, this means we just map to internal, but for explicit 4916 // instantiations we'll map to external. 4917 4918 // In C++, the compiler has to emit a definition in every translation unit 4919 // that references the function. We should use linkonce_odr because 4920 // a) if all references in this translation unit are optimized away, we 4921 // don't need to codegen it. b) if the function persists, it needs to be 4922 // merged with other definitions. c) C++ has the ODR, so we know the 4923 // definition is dependable. 4924 if (Linkage == GVA_DiscardableODR) 4925 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 4926 : llvm::Function::InternalLinkage; 4927 4928 // An explicit instantiation of a template has weak linkage, since 4929 // explicit instantiations can occur in multiple translation units 4930 // and must all be equivalent. However, we are not allowed to 4931 // throw away these explicit instantiations. 4932 // 4933 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 4934 // so say that CUDA templates are either external (for kernels) or internal. 4935 // This lets llvm perform aggressive inter-procedural optimizations. For 4936 // -fgpu-rdc case, device function calls across multiple TU's are allowed, 4937 // therefore we need to follow the normal linkage paradigm. 4938 if (Linkage == GVA_StrongODR) { 4939 if (getLangOpts().AppleKext) 4940 return llvm::Function::ExternalLinkage; 4941 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 4942 !getLangOpts().GPURelocatableDeviceCode) 4943 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 4944 : llvm::Function::InternalLinkage; 4945 return llvm::Function::WeakODRLinkage; 4946 } 4947 4948 // C++ doesn't have tentative definitions and thus cannot have common 4949 // linkage. 4950 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 4951 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 4952 CodeGenOpts.NoCommon)) 4953 return llvm::GlobalVariable::CommonLinkage; 4954 4955 // selectany symbols are externally visible, so use weak instead of 4956 // linkonce. MSVC optimizes away references to const selectany globals, so 4957 // all definitions should be the same and ODR linkage should be used. 4958 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 4959 if (D->hasAttr<SelectAnyAttr>()) 4960 return llvm::GlobalVariable::WeakODRLinkage; 4961 4962 // Otherwise, we have strong external linkage. 4963 assert(Linkage == GVA_StrongExternal); 4964 return llvm::GlobalVariable::ExternalLinkage; 4965 } 4966 4967 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 4968 const VarDecl *VD, bool IsConstant) { 4969 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 4970 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 4971 } 4972 4973 /// Replace the uses of a function that was declared with a non-proto type. 4974 /// We want to silently drop extra arguments from call sites 4975 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 4976 llvm::Function *newFn) { 4977 // Fast path. 4978 if (old->use_empty()) return; 4979 4980 llvm::Type *newRetTy = newFn->getReturnType(); 4981 SmallVector<llvm::Value*, 4> newArgs; 4982 4983 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 4984 ui != ue; ) { 4985 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 4986 llvm::User *user = use->getUser(); 4987 4988 // Recognize and replace uses of bitcasts. Most calls to 4989 // unprototyped functions will use bitcasts. 4990 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 4991 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 4992 replaceUsesOfNonProtoConstant(bitcast, newFn); 4993 continue; 4994 } 4995 4996 // Recognize calls to the function. 4997 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 4998 if (!callSite) continue; 4999 if (!callSite->isCallee(&*use)) 5000 continue; 5001 5002 // If the return types don't match exactly, then we can't 5003 // transform this call unless it's dead. 5004 if (callSite->getType() != newRetTy && !callSite->use_empty()) 5005 continue; 5006 5007 // Get the call site's attribute list. 5008 SmallVector<llvm::AttributeSet, 8> newArgAttrs; 5009 llvm::AttributeList oldAttrs = callSite->getAttributes(); 5010 5011 // If the function was passed too few arguments, don't transform. 5012 unsigned newNumArgs = newFn->arg_size(); 5013 if (callSite->arg_size() < newNumArgs) 5014 continue; 5015 5016 // If extra arguments were passed, we silently drop them. 5017 // If any of the types mismatch, we don't transform. 5018 unsigned argNo = 0; 5019 bool dontTransform = false; 5020 for (llvm::Argument &A : newFn->args()) { 5021 if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 5022 dontTransform = true; 5023 break; 5024 } 5025 5026 // Add any parameter attributes. 5027 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 5028 argNo++; 5029 } 5030 if (dontTransform) 5031 continue; 5032 5033 // Okay, we can transform this. Create the new call instruction and copy 5034 // over the required information. 5035 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 5036 5037 // Copy over any operand bundles. 5038 SmallVector<llvm::OperandBundleDef, 1> newBundles; 5039 callSite->getOperandBundlesAsDefs(newBundles); 5040 5041 llvm::CallBase *newCall; 5042 if (isa<llvm::CallInst>(callSite)) { 5043 newCall = 5044 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 5045 } else { 5046 auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 5047 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 5048 oldInvoke->getUnwindDest(), newArgs, 5049 newBundles, "", callSite); 5050 } 5051 newArgs.clear(); // for the next iteration 5052 5053 if (!newCall->getType()->isVoidTy()) 5054 newCall->takeName(callSite); 5055 newCall->setAttributes( 5056 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 5057 oldAttrs.getRetAttrs(), newArgAttrs)); 5058 newCall->setCallingConv(callSite->getCallingConv()); 5059 5060 // Finally, remove the old call, replacing any uses with the new one. 5061 if (!callSite->use_empty()) 5062 callSite->replaceAllUsesWith(newCall); 5063 5064 // Copy debug location attached to CI. 5065 if (callSite->getDebugLoc()) 5066 newCall->setDebugLoc(callSite->getDebugLoc()); 5067 5068 callSite->eraseFromParent(); 5069 } 5070 } 5071 5072 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 5073 /// implement a function with no prototype, e.g. "int foo() {}". If there are 5074 /// existing call uses of the old function in the module, this adjusts them to 5075 /// call the new function directly. 5076 /// 5077 /// This is not just a cleanup: the always_inline pass requires direct calls to 5078 /// functions to be able to inline them. If there is a bitcast in the way, it 5079 /// won't inline them. Instcombine normally deletes these calls, but it isn't 5080 /// run at -O0. 5081 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 5082 llvm::Function *NewFn) { 5083 // If we're redefining a global as a function, don't transform it. 5084 if (!isa<llvm::Function>(Old)) return; 5085 5086 replaceUsesOfNonProtoConstant(Old, NewFn); 5087 } 5088 5089 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 5090 auto DK = VD->isThisDeclarationADefinition(); 5091 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 5092 return; 5093 5094 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 5095 // If we have a definition, this might be a deferred decl. If the 5096 // instantiation is explicit, make sure we emit it at the end. 5097 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 5098 GetAddrOfGlobalVar(VD); 5099 5100 EmitTopLevelDecl(VD); 5101 } 5102 5103 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 5104 llvm::GlobalValue *GV) { 5105 const auto *D = cast<FunctionDecl>(GD.getDecl()); 5106 5107 // Compute the function info and LLVM type. 5108 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 5109 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 5110 5111 // Get or create the prototype for the function. 5112 if (!GV || (GV->getValueType() != Ty)) 5113 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 5114 /*DontDefer=*/true, 5115 ForDefinition)); 5116 5117 // Already emitted. 5118 if (!GV->isDeclaration()) 5119 return; 5120 5121 // We need to set linkage and visibility on the function before 5122 // generating code for it because various parts of IR generation 5123 // want to propagate this information down (e.g. to local static 5124 // declarations). 5125 auto *Fn = cast<llvm::Function>(GV); 5126 setFunctionLinkage(GD, Fn); 5127 5128 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 5129 setGVProperties(Fn, GD); 5130 5131 MaybeHandleStaticInExternC(D, Fn); 5132 5133 maybeSetTrivialComdat(*D, *Fn); 5134 5135 // Set CodeGen attributes that represent floating point environment. 5136 setLLVMFunctionFEnvAttributes(D, Fn); 5137 5138 CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 5139 5140 setNonAliasAttributes(GD, Fn); 5141 SetLLVMFunctionAttributesForDefinition(D, Fn); 5142 5143 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 5144 AddGlobalCtor(Fn, CA->getPriority()); 5145 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5146 AddGlobalDtor(Fn, DA->getPriority(), true); 5147 if (D->hasAttr<AnnotateAttr>()) 5148 AddGlobalAnnotations(D, Fn); 5149 } 5150 5151 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 5152 const auto *D = cast<ValueDecl>(GD.getDecl()); 5153 const AliasAttr *AA = D->getAttr<AliasAttr>(); 5154 assert(AA && "Not an alias?"); 5155 5156 StringRef MangledName = getMangledName(GD); 5157 5158 if (AA->getAliasee() == MangledName) { 5159 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5160 return; 5161 } 5162 5163 // If there is a definition in the module, then it wins over the alias. 5164 // This is dubious, but allow it to be safe. Just ignore the alias. 5165 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5166 if (Entry && !Entry->isDeclaration()) 5167 return; 5168 5169 Aliases.push_back(GD); 5170 5171 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5172 5173 // Create a reference to the named value. This ensures that it is emitted 5174 // if a deferred decl. 5175 llvm::Constant *Aliasee; 5176 llvm::GlobalValue::LinkageTypes LT; 5177 if (isa<llvm::FunctionType>(DeclTy)) { 5178 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 5179 /*ForVTable=*/false); 5180 LT = getFunctionLinkage(GD); 5181 } else { 5182 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 5183 /*D=*/nullptr); 5184 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 5185 LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified()); 5186 else 5187 LT = getFunctionLinkage(GD); 5188 } 5189 5190 // Create the new alias itself, but don't set a name yet. 5191 unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 5192 auto *GA = 5193 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 5194 5195 if (Entry) { 5196 if (GA->getAliasee() == Entry) { 5197 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5198 return; 5199 } 5200 5201 assert(Entry->isDeclaration()); 5202 5203 // If there is a declaration in the module, then we had an extern followed 5204 // by the alias, as in: 5205 // extern int test6(); 5206 // ... 5207 // int test6() __attribute__((alias("test7"))); 5208 // 5209 // Remove it and replace uses of it with the alias. 5210 GA->takeName(Entry); 5211 5212 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 5213 Entry->getType())); 5214 Entry->eraseFromParent(); 5215 } else { 5216 GA->setName(MangledName); 5217 } 5218 5219 // Set attributes which are particular to an alias; this is a 5220 // specialization of the attributes which may be set on a global 5221 // variable/function. 5222 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 5223 D->isWeakImported()) { 5224 GA->setLinkage(llvm::Function::WeakAnyLinkage); 5225 } 5226 5227 if (const auto *VD = dyn_cast<VarDecl>(D)) 5228 if (VD->getTLSKind()) 5229 setTLSMode(GA, *VD); 5230 5231 SetCommonAttributes(GD, GA); 5232 5233 // Emit global alias debug information. 5234 if (isa<VarDecl>(D)) 5235 if (CGDebugInfo *DI = getModuleDebugInfo()) 5236 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()), GD); 5237 } 5238 5239 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 5240 const auto *D = cast<ValueDecl>(GD.getDecl()); 5241 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 5242 assert(IFA && "Not an ifunc?"); 5243 5244 StringRef MangledName = getMangledName(GD); 5245 5246 if (IFA->getResolver() == MangledName) { 5247 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5248 return; 5249 } 5250 5251 // Report an error if some definition overrides ifunc. 5252 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5253 if (Entry && !Entry->isDeclaration()) { 5254 GlobalDecl OtherGD; 5255 if (lookupRepresentativeDecl(MangledName, OtherGD) && 5256 DiagnosedConflictingDefinitions.insert(GD).second) { 5257 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 5258 << MangledName; 5259 Diags.Report(OtherGD.getDecl()->getLocation(), 5260 diag::note_previous_definition); 5261 } 5262 return; 5263 } 5264 5265 Aliases.push_back(GD); 5266 5267 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5268 llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 5269 llvm::Constant *Resolver = 5270 GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 5271 /*ForVTable=*/false); 5272 llvm::GlobalIFunc *GIF = 5273 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 5274 "", Resolver, &getModule()); 5275 if (Entry) { 5276 if (GIF->getResolver() == Entry) { 5277 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5278 return; 5279 } 5280 assert(Entry->isDeclaration()); 5281 5282 // If there is a declaration in the module, then we had an extern followed 5283 // by the ifunc, as in: 5284 // extern int test(); 5285 // ... 5286 // int test() __attribute__((ifunc("resolver"))); 5287 // 5288 // Remove it and replace uses of it with the ifunc. 5289 GIF->takeName(Entry); 5290 5291 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 5292 Entry->getType())); 5293 Entry->eraseFromParent(); 5294 } else 5295 GIF->setName(MangledName); 5296 5297 SetCommonAttributes(GD, GIF); 5298 } 5299 5300 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 5301 ArrayRef<llvm::Type*> Tys) { 5302 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 5303 Tys); 5304 } 5305 5306 static llvm::StringMapEntry<llvm::GlobalVariable *> & 5307 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 5308 const StringLiteral *Literal, bool TargetIsLSB, 5309 bool &IsUTF16, unsigned &StringLength) { 5310 StringRef String = Literal->getString(); 5311 unsigned NumBytes = String.size(); 5312 5313 // Check for simple case. 5314 if (!Literal->containsNonAsciiOrNull()) { 5315 StringLength = NumBytes; 5316 return *Map.insert(std::make_pair(String, nullptr)).first; 5317 } 5318 5319 // Otherwise, convert the UTF8 literals into a string of shorts. 5320 IsUTF16 = true; 5321 5322 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 5323 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5324 llvm::UTF16 *ToPtr = &ToBuf[0]; 5325 5326 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5327 ToPtr + NumBytes, llvm::strictConversion); 5328 5329 // ConvertUTF8toUTF16 returns the length in ToPtr. 5330 StringLength = ToPtr - &ToBuf[0]; 5331 5332 // Add an explicit null. 5333 *ToPtr = 0; 5334 return *Map.insert(std::make_pair( 5335 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 5336 (StringLength + 1) * 2), 5337 nullptr)).first; 5338 } 5339 5340 ConstantAddress 5341 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 5342 unsigned StringLength = 0; 5343 bool isUTF16 = false; 5344 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 5345 GetConstantCFStringEntry(CFConstantStringMap, Literal, 5346 getDataLayout().isLittleEndian(), isUTF16, 5347 StringLength); 5348 5349 if (auto *C = Entry.second) 5350 return ConstantAddress( 5351 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 5352 5353 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 5354 llvm::Constant *Zeros[] = { Zero, Zero }; 5355 5356 const ASTContext &Context = getContext(); 5357 const llvm::Triple &Triple = getTriple(); 5358 5359 const auto CFRuntime = getLangOpts().CFRuntime; 5360 const bool IsSwiftABI = 5361 static_cast<unsigned>(CFRuntime) >= 5362 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 5363 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 5364 5365 // If we don't already have it, get __CFConstantStringClassReference. 5366 if (!CFConstantStringClassRef) { 5367 const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 5368 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 5369 Ty = llvm::ArrayType::get(Ty, 0); 5370 5371 switch (CFRuntime) { 5372 default: break; 5373 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH; 5374 case LangOptions::CoreFoundationABI::Swift5_0: 5375 CFConstantStringClassName = 5376 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 5377 : "$s10Foundation19_NSCFConstantStringCN"; 5378 Ty = IntPtrTy; 5379 break; 5380 case LangOptions::CoreFoundationABI::Swift4_2: 5381 CFConstantStringClassName = 5382 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 5383 : "$S10Foundation19_NSCFConstantStringCN"; 5384 Ty = IntPtrTy; 5385 break; 5386 case LangOptions::CoreFoundationABI::Swift4_1: 5387 CFConstantStringClassName = 5388 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 5389 : "__T010Foundation19_NSCFConstantStringCN"; 5390 Ty = IntPtrTy; 5391 break; 5392 } 5393 5394 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 5395 5396 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 5397 llvm::GlobalValue *GV = nullptr; 5398 5399 if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 5400 IdentifierInfo &II = Context.Idents.get(GV->getName()); 5401 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 5402 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 5403 5404 const VarDecl *VD = nullptr; 5405 for (const auto *Result : DC->lookup(&II)) 5406 if ((VD = dyn_cast<VarDecl>(Result))) 5407 break; 5408 5409 if (Triple.isOSBinFormatELF()) { 5410 if (!VD) 5411 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5412 } else { 5413 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5414 if (!VD || !VD->hasAttr<DLLExportAttr>()) 5415 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 5416 else 5417 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 5418 } 5419 5420 setDSOLocal(GV); 5421 } 5422 } 5423 5424 // Decay array -> ptr 5425 CFConstantStringClassRef = 5426 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 5427 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 5428 } 5429 5430 QualType CFTy = Context.getCFConstantStringType(); 5431 5432 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 5433 5434 ConstantInitBuilder Builder(*this); 5435 auto Fields = Builder.beginStruct(STy); 5436 5437 // Class pointer. 5438 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef)); 5439 5440 // Flags. 5441 if (IsSwiftABI) { 5442 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 5443 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 5444 } else { 5445 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 5446 } 5447 5448 // String pointer. 5449 llvm::Constant *C = nullptr; 5450 if (isUTF16) { 5451 auto Arr = llvm::makeArrayRef( 5452 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 5453 Entry.first().size() / 2); 5454 C = llvm::ConstantDataArray::get(VMContext, Arr); 5455 } else { 5456 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 5457 } 5458 5459 // Note: -fwritable-strings doesn't make the backing store strings of 5460 // CFStrings writable. (See <rdar://problem/10657500>) 5461 auto *GV = 5462 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 5463 llvm::GlobalValue::PrivateLinkage, C, ".str"); 5464 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5465 // Don't enforce the target's minimum global alignment, since the only use 5466 // of the string is via this class initializer. 5467 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 5468 : Context.getTypeAlignInChars(Context.CharTy); 5469 GV->setAlignment(Align.getAsAlign()); 5470 5471 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 5472 // Without it LLVM can merge the string with a non unnamed_addr one during 5473 // LTO. Doing that changes the section it ends in, which surprises ld64. 5474 if (Triple.isOSBinFormatMachO()) 5475 GV->setSection(isUTF16 ? "__TEXT,__ustring" 5476 : "__TEXT,__cstring,cstring_literals"); 5477 // Make sure the literal ends up in .rodata to allow for safe ICF and for 5478 // the static linker to adjust permissions to read-only later on. 5479 else if (Triple.isOSBinFormatELF()) 5480 GV->setSection(".rodata"); 5481 5482 // String. 5483 llvm::Constant *Str = 5484 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 5485 5486 if (isUTF16) 5487 // Cast the UTF16 string to the correct type. 5488 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 5489 Fields.add(Str); 5490 5491 // String length. 5492 llvm::IntegerType *LengthTy = 5493 llvm::IntegerType::get(getModule().getContext(), 5494 Context.getTargetInfo().getLongWidth()); 5495 if (IsSwiftABI) { 5496 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 5497 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 5498 LengthTy = Int32Ty; 5499 else 5500 LengthTy = IntPtrTy; 5501 } 5502 Fields.addInt(LengthTy, StringLength); 5503 5504 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 5505 // properly aligned on 32-bit platforms. 5506 CharUnits Alignment = 5507 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 5508 5509 // The struct. 5510 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 5511 /*isConstant=*/false, 5512 llvm::GlobalVariable::PrivateLinkage); 5513 GV->addAttribute("objc_arc_inert"); 5514 switch (Triple.getObjectFormat()) { 5515 case llvm::Triple::UnknownObjectFormat: 5516 llvm_unreachable("unknown file format"); 5517 case llvm::Triple::DXContainer: 5518 case llvm::Triple::GOFF: 5519 case llvm::Triple::SPIRV: 5520 case llvm::Triple::XCOFF: 5521 llvm_unreachable("unimplemented"); 5522 case llvm::Triple::COFF: 5523 case llvm::Triple::ELF: 5524 case llvm::Triple::Wasm: 5525 GV->setSection("cfstring"); 5526 break; 5527 case llvm::Triple::MachO: 5528 GV->setSection("__DATA,__cfstring"); 5529 break; 5530 } 5531 Entry.second = GV; 5532 5533 return ConstantAddress(GV, GV->getValueType(), Alignment); 5534 } 5535 5536 bool CodeGenModule::getExpressionLocationsEnabled() const { 5537 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 5538 } 5539 5540 QualType CodeGenModule::getObjCFastEnumerationStateType() { 5541 if (ObjCFastEnumerationStateType.isNull()) { 5542 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 5543 D->startDefinition(); 5544 5545 QualType FieldTypes[] = { 5546 Context.UnsignedLongTy, 5547 Context.getPointerType(Context.getObjCIdType()), 5548 Context.getPointerType(Context.UnsignedLongTy), 5549 Context.getConstantArrayType(Context.UnsignedLongTy, 5550 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 5551 }; 5552 5553 for (size_t i = 0; i < 4; ++i) { 5554 FieldDecl *Field = FieldDecl::Create(Context, 5555 D, 5556 SourceLocation(), 5557 SourceLocation(), nullptr, 5558 FieldTypes[i], /*TInfo=*/nullptr, 5559 /*BitWidth=*/nullptr, 5560 /*Mutable=*/false, 5561 ICIS_NoInit); 5562 Field->setAccess(AS_public); 5563 D->addDecl(Field); 5564 } 5565 5566 D->completeDefinition(); 5567 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 5568 } 5569 5570 return ObjCFastEnumerationStateType; 5571 } 5572 5573 llvm::Constant * 5574 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 5575 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 5576 5577 // Don't emit it as the address of the string, emit the string data itself 5578 // as an inline array. 5579 if (E->getCharByteWidth() == 1) { 5580 SmallString<64> Str(E->getString()); 5581 5582 // Resize the string to the right size, which is indicated by its type. 5583 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 5584 Str.resize(CAT->getSize().getZExtValue()); 5585 return llvm::ConstantDataArray::getString(VMContext, Str, false); 5586 } 5587 5588 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 5589 llvm::Type *ElemTy = AType->getElementType(); 5590 unsigned NumElements = AType->getNumElements(); 5591 5592 // Wide strings have either 2-byte or 4-byte elements. 5593 if (ElemTy->getPrimitiveSizeInBits() == 16) { 5594 SmallVector<uint16_t, 32> Elements; 5595 Elements.reserve(NumElements); 5596 5597 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5598 Elements.push_back(E->getCodeUnit(i)); 5599 Elements.resize(NumElements); 5600 return llvm::ConstantDataArray::get(VMContext, Elements); 5601 } 5602 5603 assert(ElemTy->getPrimitiveSizeInBits() == 32); 5604 SmallVector<uint32_t, 32> Elements; 5605 Elements.reserve(NumElements); 5606 5607 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5608 Elements.push_back(E->getCodeUnit(i)); 5609 Elements.resize(NumElements); 5610 return llvm::ConstantDataArray::get(VMContext, Elements); 5611 } 5612 5613 static llvm::GlobalVariable * 5614 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 5615 CodeGenModule &CGM, StringRef GlobalName, 5616 CharUnits Alignment) { 5617 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5618 CGM.GetGlobalConstantAddressSpace()); 5619 5620 llvm::Module &M = CGM.getModule(); 5621 // Create a global variable for this string 5622 auto *GV = new llvm::GlobalVariable( 5623 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 5624 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5625 GV->setAlignment(Alignment.getAsAlign()); 5626 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5627 if (GV->isWeakForLinker()) { 5628 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 5629 GV->setComdat(M.getOrInsertComdat(GV->getName())); 5630 } 5631 CGM.setDSOLocal(GV); 5632 5633 return GV; 5634 } 5635 5636 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 5637 /// constant array for the given string literal. 5638 ConstantAddress 5639 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 5640 StringRef Name) { 5641 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 5642 5643 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 5644 llvm::GlobalVariable **Entry = nullptr; 5645 if (!LangOpts.WritableStrings) { 5646 Entry = &ConstantStringMap[C]; 5647 if (auto GV = *Entry) { 5648 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5649 GV->setAlignment(Alignment.getAsAlign()); 5650 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5651 GV->getValueType(), Alignment); 5652 } 5653 } 5654 5655 SmallString<256> MangledNameBuffer; 5656 StringRef GlobalVariableName; 5657 llvm::GlobalValue::LinkageTypes LT; 5658 5659 // Mangle the string literal if that's how the ABI merges duplicate strings. 5660 // Don't do it if they are writable, since we don't want writes in one TU to 5661 // affect strings in another. 5662 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 5663 !LangOpts.WritableStrings) { 5664 llvm::raw_svector_ostream Out(MangledNameBuffer); 5665 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 5666 LT = llvm::GlobalValue::LinkOnceODRLinkage; 5667 GlobalVariableName = MangledNameBuffer; 5668 } else { 5669 LT = llvm::GlobalValue::PrivateLinkage; 5670 GlobalVariableName = Name; 5671 } 5672 5673 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 5674 5675 CGDebugInfo *DI = getModuleDebugInfo(); 5676 if (DI && getCodeGenOpts().hasReducedDebugInfo()) 5677 DI->AddStringLiteralDebugInfo(GV, S); 5678 5679 if (Entry) 5680 *Entry = GV; 5681 5682 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>"); 5683 5684 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5685 GV->getValueType(), Alignment); 5686 } 5687 5688 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 5689 /// array for the given ObjCEncodeExpr node. 5690 ConstantAddress 5691 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 5692 std::string Str; 5693 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 5694 5695 return GetAddrOfConstantCString(Str); 5696 } 5697 5698 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 5699 /// the literal and a terminating '\0' character. 5700 /// The result has pointer to array type. 5701 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 5702 const std::string &Str, const char *GlobalName) { 5703 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 5704 CharUnits Alignment = 5705 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 5706 5707 llvm::Constant *C = 5708 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 5709 5710 // Don't share any string literals if strings aren't constant. 5711 llvm::GlobalVariable **Entry = nullptr; 5712 if (!LangOpts.WritableStrings) { 5713 Entry = &ConstantStringMap[C]; 5714 if (auto GV = *Entry) { 5715 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5716 GV->setAlignment(Alignment.getAsAlign()); 5717 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5718 GV->getValueType(), Alignment); 5719 } 5720 } 5721 5722 // Get the default prefix if a name wasn't specified. 5723 if (!GlobalName) 5724 GlobalName = ".str"; 5725 // Create a global variable for this. 5726 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 5727 GlobalName, Alignment); 5728 if (Entry) 5729 *Entry = GV; 5730 5731 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5732 GV->getValueType(), Alignment); 5733 } 5734 5735 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 5736 const MaterializeTemporaryExpr *E, const Expr *Init) { 5737 assert((E->getStorageDuration() == SD_Static || 5738 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 5739 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 5740 5741 // If we're not materializing a subobject of the temporary, keep the 5742 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 5743 QualType MaterializedType = Init->getType(); 5744 if (Init == E->getSubExpr()) 5745 MaterializedType = E->getType(); 5746 5747 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 5748 5749 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 5750 if (!InsertResult.second) { 5751 // We've seen this before: either we already created it or we're in the 5752 // process of doing so. 5753 if (!InsertResult.first->second) { 5754 // We recursively re-entered this function, probably during emission of 5755 // the initializer. Create a placeholder. We'll clean this up in the 5756 // outer call, at the end of this function. 5757 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 5758 InsertResult.first->second = new llvm::GlobalVariable( 5759 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 5760 nullptr); 5761 } 5762 return ConstantAddress(InsertResult.first->second, 5763 llvm::cast<llvm::GlobalVariable>( 5764 InsertResult.first->second->stripPointerCasts()) 5765 ->getValueType(), 5766 Align); 5767 } 5768 5769 // FIXME: If an externally-visible declaration extends multiple temporaries, 5770 // we need to give each temporary the same name in every translation unit (and 5771 // we also need to make the temporaries externally-visible). 5772 SmallString<256> Name; 5773 llvm::raw_svector_ostream Out(Name); 5774 getCXXABI().getMangleContext().mangleReferenceTemporary( 5775 VD, E->getManglingNumber(), Out); 5776 5777 APValue *Value = nullptr; 5778 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 5779 // If the initializer of the extending declaration is a constant 5780 // initializer, we should have a cached constant initializer for this 5781 // temporary. Note that this might have a different value from the value 5782 // computed by evaluating the initializer if the surrounding constant 5783 // expression modifies the temporary. 5784 Value = E->getOrCreateValue(false); 5785 } 5786 5787 // Try evaluating it now, it might have a constant initializer. 5788 Expr::EvalResult EvalResult; 5789 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 5790 !EvalResult.hasSideEffects()) 5791 Value = &EvalResult.Val; 5792 5793 LangAS AddrSpace = 5794 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 5795 5796 Optional<ConstantEmitter> emitter; 5797 llvm::Constant *InitialValue = nullptr; 5798 bool Constant = false; 5799 llvm::Type *Type; 5800 if (Value) { 5801 // The temporary has a constant initializer, use it. 5802 emitter.emplace(*this); 5803 InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 5804 MaterializedType); 5805 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 5806 Type = InitialValue->getType(); 5807 } else { 5808 // No initializer, the initialization will be provided when we 5809 // initialize the declaration which performed lifetime extension. 5810 Type = getTypes().ConvertTypeForMem(MaterializedType); 5811 } 5812 5813 // Create a global variable for this lifetime-extended temporary. 5814 llvm::GlobalValue::LinkageTypes Linkage = 5815 getLLVMLinkageVarDefinition(VD, Constant); 5816 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 5817 const VarDecl *InitVD; 5818 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 5819 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 5820 // Temporaries defined inside a class get linkonce_odr linkage because the 5821 // class can be defined in multiple translation units. 5822 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 5823 } else { 5824 // There is no need for this temporary to have external linkage if the 5825 // VarDecl has external linkage. 5826 Linkage = llvm::GlobalVariable::InternalLinkage; 5827 } 5828 } 5829 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 5830 auto *GV = new llvm::GlobalVariable( 5831 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 5832 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 5833 if (emitter) emitter->finalize(GV); 5834 setGVProperties(GV, VD); 5835 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass) 5836 // The reference temporary should never be dllexport. 5837 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 5838 GV->setAlignment(Align.getAsAlign()); 5839 if (supportsCOMDAT() && GV->isWeakForLinker()) 5840 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 5841 if (VD->getTLSKind()) 5842 setTLSMode(GV, *VD); 5843 llvm::Constant *CV = GV; 5844 if (AddrSpace != LangAS::Default) 5845 CV = getTargetCodeGenInfo().performAddrSpaceCast( 5846 *this, GV, AddrSpace, LangAS::Default, 5847 Type->getPointerTo( 5848 getContext().getTargetAddressSpace(LangAS::Default))); 5849 5850 // Update the map with the new temporary. If we created a placeholder above, 5851 // replace it with the new global now. 5852 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 5853 if (Entry) { 5854 Entry->replaceAllUsesWith( 5855 llvm::ConstantExpr::getBitCast(CV, Entry->getType())); 5856 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 5857 } 5858 Entry = CV; 5859 5860 return ConstantAddress(CV, Type, Align); 5861 } 5862 5863 /// EmitObjCPropertyImplementations - Emit information for synthesized 5864 /// properties for an implementation. 5865 void CodeGenModule::EmitObjCPropertyImplementations(const 5866 ObjCImplementationDecl *D) { 5867 for (const auto *PID : D->property_impls()) { 5868 // Dynamic is just for type-checking. 5869 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 5870 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 5871 5872 // Determine which methods need to be implemented, some may have 5873 // been overridden. Note that ::isPropertyAccessor is not the method 5874 // we want, that just indicates if the decl came from a 5875 // property. What we want to know is if the method is defined in 5876 // this implementation. 5877 auto *Getter = PID->getGetterMethodDecl(); 5878 if (!Getter || Getter->isSynthesizedAccessorStub()) 5879 CodeGenFunction(*this).GenerateObjCGetter( 5880 const_cast<ObjCImplementationDecl *>(D), PID); 5881 auto *Setter = PID->getSetterMethodDecl(); 5882 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 5883 CodeGenFunction(*this).GenerateObjCSetter( 5884 const_cast<ObjCImplementationDecl *>(D), PID); 5885 } 5886 } 5887 } 5888 5889 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 5890 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 5891 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 5892 ivar; ivar = ivar->getNextIvar()) 5893 if (ivar->getType().isDestructedType()) 5894 return true; 5895 5896 return false; 5897 } 5898 5899 static bool AllTrivialInitializers(CodeGenModule &CGM, 5900 ObjCImplementationDecl *D) { 5901 CodeGenFunction CGF(CGM); 5902 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 5903 E = D->init_end(); B != E; ++B) { 5904 CXXCtorInitializer *CtorInitExp = *B; 5905 Expr *Init = CtorInitExp->getInit(); 5906 if (!CGF.isTrivialInitializer(Init)) 5907 return false; 5908 } 5909 return true; 5910 } 5911 5912 /// EmitObjCIvarInitializations - Emit information for ivar initialization 5913 /// for an implementation. 5914 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 5915 // We might need a .cxx_destruct even if we don't have any ivar initializers. 5916 if (needsDestructMethod(D)) { 5917 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 5918 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5919 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 5920 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5921 getContext().VoidTy, nullptr, D, 5922 /*isInstance=*/true, /*isVariadic=*/false, 5923 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5924 /*isImplicitlyDeclared=*/true, 5925 /*isDefined=*/false, ObjCMethodDecl::Required); 5926 D->addInstanceMethod(DTORMethod); 5927 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 5928 D->setHasDestructors(true); 5929 } 5930 5931 // If the implementation doesn't have any ivar initializers, we don't need 5932 // a .cxx_construct. 5933 if (D->getNumIvarInitializers() == 0 || 5934 AllTrivialInitializers(*this, D)) 5935 return; 5936 5937 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 5938 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5939 // The constructor returns 'self'. 5940 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 5941 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5942 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 5943 /*isVariadic=*/false, 5944 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5945 /*isImplicitlyDeclared=*/true, 5946 /*isDefined=*/false, ObjCMethodDecl::Required); 5947 D->addInstanceMethod(CTORMethod); 5948 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 5949 D->setHasNonZeroConstructors(true); 5950 } 5951 5952 // EmitLinkageSpec - Emit all declarations in a linkage spec. 5953 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 5954 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 5955 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 5956 ErrorUnsupported(LSD, "linkage spec"); 5957 return; 5958 } 5959 5960 EmitDeclContext(LSD); 5961 } 5962 5963 void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 5964 for (auto *I : DC->decls()) { 5965 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 5966 // are themselves considered "top-level", so EmitTopLevelDecl on an 5967 // ObjCImplDecl does not recursively visit them. We need to do that in 5968 // case they're nested inside another construct (LinkageSpecDecl / 5969 // ExportDecl) that does stop them from being considered "top-level". 5970 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 5971 for (auto *M : OID->methods()) 5972 EmitTopLevelDecl(M); 5973 } 5974 5975 EmitTopLevelDecl(I); 5976 } 5977 } 5978 5979 /// EmitTopLevelDecl - Emit code for a single top level declaration. 5980 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 5981 // Ignore dependent declarations. 5982 if (D->isTemplated()) 5983 return; 5984 5985 // Consteval function shouldn't be emitted. 5986 if (auto *FD = dyn_cast<FunctionDecl>(D)) 5987 if (FD->isConsteval()) 5988 return; 5989 5990 switch (D->getKind()) { 5991 case Decl::CXXConversion: 5992 case Decl::CXXMethod: 5993 case Decl::Function: 5994 EmitGlobal(cast<FunctionDecl>(D)); 5995 // Always provide some coverage mapping 5996 // even for the functions that aren't emitted. 5997 AddDeferredUnusedCoverageMapping(D); 5998 break; 5999 6000 case Decl::CXXDeductionGuide: 6001 // Function-like, but does not result in code emission. 6002 break; 6003 6004 case Decl::Var: 6005 case Decl::Decomposition: 6006 case Decl::VarTemplateSpecialization: 6007 EmitGlobal(cast<VarDecl>(D)); 6008 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 6009 for (auto *B : DD->bindings()) 6010 if (auto *HD = B->getHoldingVar()) 6011 EmitGlobal(HD); 6012 break; 6013 6014 // Indirect fields from global anonymous structs and unions can be 6015 // ignored; only the actual variable requires IR gen support. 6016 case Decl::IndirectField: 6017 break; 6018 6019 // C++ Decls 6020 case Decl::Namespace: 6021 EmitDeclContext(cast<NamespaceDecl>(D)); 6022 break; 6023 case Decl::ClassTemplateSpecialization: { 6024 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 6025 if (CGDebugInfo *DI = getModuleDebugInfo()) 6026 if (Spec->getSpecializationKind() == 6027 TSK_ExplicitInstantiationDefinition && 6028 Spec->hasDefinition()) 6029 DI->completeTemplateDefinition(*Spec); 6030 } LLVM_FALLTHROUGH; 6031 case Decl::CXXRecord: { 6032 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 6033 if (CGDebugInfo *DI = getModuleDebugInfo()) { 6034 if (CRD->hasDefinition()) 6035 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6036 if (auto *ES = D->getASTContext().getExternalSource()) 6037 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 6038 DI->completeUnusedClass(*CRD); 6039 } 6040 // Emit any static data members, they may be definitions. 6041 for (auto *I : CRD->decls()) 6042 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 6043 EmitTopLevelDecl(I); 6044 break; 6045 } 6046 // No code generation needed. 6047 case Decl::UsingShadow: 6048 case Decl::ClassTemplate: 6049 case Decl::VarTemplate: 6050 case Decl::Concept: 6051 case Decl::VarTemplatePartialSpecialization: 6052 case Decl::FunctionTemplate: 6053 case Decl::TypeAliasTemplate: 6054 case Decl::Block: 6055 case Decl::Empty: 6056 case Decl::Binding: 6057 break; 6058 case Decl::Using: // using X; [C++] 6059 if (CGDebugInfo *DI = getModuleDebugInfo()) 6060 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 6061 break; 6062 case Decl::UsingEnum: // using enum X; [C++] 6063 if (CGDebugInfo *DI = getModuleDebugInfo()) 6064 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 6065 break; 6066 case Decl::NamespaceAlias: 6067 if (CGDebugInfo *DI = getModuleDebugInfo()) 6068 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 6069 break; 6070 case Decl::UsingDirective: // using namespace X; [C++] 6071 if (CGDebugInfo *DI = getModuleDebugInfo()) 6072 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 6073 break; 6074 case Decl::CXXConstructor: 6075 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 6076 break; 6077 case Decl::CXXDestructor: 6078 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 6079 break; 6080 6081 case Decl::StaticAssert: 6082 // Nothing to do. 6083 break; 6084 6085 // Objective-C Decls 6086 6087 // Forward declarations, no (immediate) code generation. 6088 case Decl::ObjCInterface: 6089 case Decl::ObjCCategory: 6090 break; 6091 6092 case Decl::ObjCProtocol: { 6093 auto *Proto = cast<ObjCProtocolDecl>(D); 6094 if (Proto->isThisDeclarationADefinition()) 6095 ObjCRuntime->GenerateProtocol(Proto); 6096 break; 6097 } 6098 6099 case Decl::ObjCCategoryImpl: 6100 // Categories have properties but don't support synthesize so we 6101 // can ignore them here. 6102 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 6103 break; 6104 6105 case Decl::ObjCImplementation: { 6106 auto *OMD = cast<ObjCImplementationDecl>(D); 6107 EmitObjCPropertyImplementations(OMD); 6108 EmitObjCIvarInitializations(OMD); 6109 ObjCRuntime->GenerateClass(OMD); 6110 // Emit global variable debug information. 6111 if (CGDebugInfo *DI = getModuleDebugInfo()) 6112 if (getCodeGenOpts().hasReducedDebugInfo()) 6113 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 6114 OMD->getClassInterface()), OMD->getLocation()); 6115 break; 6116 } 6117 case Decl::ObjCMethod: { 6118 auto *OMD = cast<ObjCMethodDecl>(D); 6119 // If this is not a prototype, emit the body. 6120 if (OMD->getBody()) 6121 CodeGenFunction(*this).GenerateObjCMethod(OMD); 6122 break; 6123 } 6124 case Decl::ObjCCompatibleAlias: 6125 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 6126 break; 6127 6128 case Decl::PragmaComment: { 6129 const auto *PCD = cast<PragmaCommentDecl>(D); 6130 switch (PCD->getCommentKind()) { 6131 case PCK_Unknown: 6132 llvm_unreachable("unexpected pragma comment kind"); 6133 case PCK_Linker: 6134 AppendLinkerOptions(PCD->getArg()); 6135 break; 6136 case PCK_Lib: 6137 AddDependentLib(PCD->getArg()); 6138 break; 6139 case PCK_Compiler: 6140 case PCK_ExeStr: 6141 case PCK_User: 6142 break; // We ignore all of these. 6143 } 6144 break; 6145 } 6146 6147 case Decl::PragmaDetectMismatch: { 6148 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 6149 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 6150 break; 6151 } 6152 6153 case Decl::LinkageSpec: 6154 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 6155 break; 6156 6157 case Decl::FileScopeAsm: { 6158 // File-scope asm is ignored during device-side CUDA compilation. 6159 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6160 break; 6161 // File-scope asm is ignored during device-side OpenMP compilation. 6162 if (LangOpts.OpenMPIsDevice) 6163 break; 6164 // File-scope asm is ignored during device-side SYCL compilation. 6165 if (LangOpts.SYCLIsDevice) 6166 break; 6167 auto *AD = cast<FileScopeAsmDecl>(D); 6168 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 6169 break; 6170 } 6171 6172 case Decl::Import: { 6173 auto *Import = cast<ImportDecl>(D); 6174 6175 // If we've already imported this module, we're done. 6176 if (!ImportedModules.insert(Import->getImportedModule())) 6177 break; 6178 6179 // Emit debug information for direct imports. 6180 if (!Import->getImportedOwningModule()) { 6181 if (CGDebugInfo *DI = getModuleDebugInfo()) 6182 DI->EmitImportDecl(*Import); 6183 } 6184 6185 // Find all of the submodules and emit the module initializers. 6186 llvm::SmallPtrSet<clang::Module *, 16> Visited; 6187 SmallVector<clang::Module *, 16> Stack; 6188 Visited.insert(Import->getImportedModule()); 6189 Stack.push_back(Import->getImportedModule()); 6190 6191 while (!Stack.empty()) { 6192 clang::Module *Mod = Stack.pop_back_val(); 6193 if (!EmittedModuleInitializers.insert(Mod).second) 6194 continue; 6195 6196 for (auto *D : Context.getModuleInitializers(Mod)) 6197 EmitTopLevelDecl(D); 6198 6199 // Visit the submodules of this module. 6200 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 6201 SubEnd = Mod->submodule_end(); 6202 Sub != SubEnd; ++Sub) { 6203 // Skip explicit children; they need to be explicitly imported to emit 6204 // the initializers. 6205 if ((*Sub)->IsExplicit) 6206 continue; 6207 6208 if (Visited.insert(*Sub).second) 6209 Stack.push_back(*Sub); 6210 } 6211 } 6212 break; 6213 } 6214 6215 case Decl::Export: 6216 EmitDeclContext(cast<ExportDecl>(D)); 6217 break; 6218 6219 case Decl::OMPThreadPrivate: 6220 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 6221 break; 6222 6223 case Decl::OMPAllocate: 6224 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 6225 break; 6226 6227 case Decl::OMPDeclareReduction: 6228 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 6229 break; 6230 6231 case Decl::OMPDeclareMapper: 6232 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 6233 break; 6234 6235 case Decl::OMPRequires: 6236 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 6237 break; 6238 6239 case Decl::Typedef: 6240 case Decl::TypeAlias: // using foo = bar; [C++11] 6241 if (CGDebugInfo *DI = getModuleDebugInfo()) 6242 DI->EmitAndRetainType( 6243 getContext().getTypedefType(cast<TypedefNameDecl>(D))); 6244 break; 6245 6246 case Decl::Record: 6247 if (CGDebugInfo *DI = getModuleDebugInfo()) 6248 if (cast<RecordDecl>(D)->getDefinition()) 6249 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6250 break; 6251 6252 case Decl::Enum: 6253 if (CGDebugInfo *DI = getModuleDebugInfo()) 6254 if (cast<EnumDecl>(D)->getDefinition()) 6255 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 6256 break; 6257 6258 default: 6259 // Make sure we handled everything we should, every other kind is a 6260 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 6261 // function. Need to recode Decl::Kind to do that easily. 6262 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 6263 break; 6264 } 6265 } 6266 6267 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 6268 // Do we need to generate coverage mapping? 6269 if (!CodeGenOpts.CoverageMapping) 6270 return; 6271 switch (D->getKind()) { 6272 case Decl::CXXConversion: 6273 case Decl::CXXMethod: 6274 case Decl::Function: 6275 case Decl::ObjCMethod: 6276 case Decl::CXXConstructor: 6277 case Decl::CXXDestructor: { 6278 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 6279 break; 6280 SourceManager &SM = getContext().getSourceManager(); 6281 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 6282 break; 6283 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6284 if (I == DeferredEmptyCoverageMappingDecls.end()) 6285 DeferredEmptyCoverageMappingDecls[D] = true; 6286 break; 6287 } 6288 default: 6289 break; 6290 }; 6291 } 6292 6293 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 6294 // Do we need to generate coverage mapping? 6295 if (!CodeGenOpts.CoverageMapping) 6296 return; 6297 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 6298 if (Fn->isTemplateInstantiation()) 6299 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 6300 } 6301 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6302 if (I == DeferredEmptyCoverageMappingDecls.end()) 6303 DeferredEmptyCoverageMappingDecls[D] = false; 6304 else 6305 I->second = false; 6306 } 6307 6308 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 6309 // We call takeVector() here to avoid use-after-free. 6310 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 6311 // we deserialize function bodies to emit coverage info for them, and that 6312 // deserializes more declarations. How should we handle that case? 6313 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 6314 if (!Entry.second) 6315 continue; 6316 const Decl *D = Entry.first; 6317 switch (D->getKind()) { 6318 case Decl::CXXConversion: 6319 case Decl::CXXMethod: 6320 case Decl::Function: 6321 case Decl::ObjCMethod: { 6322 CodeGenPGO PGO(*this); 6323 GlobalDecl GD(cast<FunctionDecl>(D)); 6324 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6325 getFunctionLinkage(GD)); 6326 break; 6327 } 6328 case Decl::CXXConstructor: { 6329 CodeGenPGO PGO(*this); 6330 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 6331 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6332 getFunctionLinkage(GD)); 6333 break; 6334 } 6335 case Decl::CXXDestructor: { 6336 CodeGenPGO PGO(*this); 6337 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 6338 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6339 getFunctionLinkage(GD)); 6340 break; 6341 } 6342 default: 6343 break; 6344 }; 6345 } 6346 } 6347 6348 void CodeGenModule::EmitMainVoidAlias() { 6349 // In order to transition away from "__original_main" gracefully, emit an 6350 // alias for "main" in the no-argument case so that libc can detect when 6351 // new-style no-argument main is in used. 6352 if (llvm::Function *F = getModule().getFunction("main")) { 6353 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 6354 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) { 6355 auto *GA = llvm::GlobalAlias::create("__main_void", F); 6356 GA->setVisibility(llvm::GlobalValue::HiddenVisibility); 6357 } 6358 } 6359 } 6360 6361 /// Turns the given pointer into a constant. 6362 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 6363 const void *Ptr) { 6364 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 6365 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 6366 return llvm::ConstantInt::get(i64, PtrInt); 6367 } 6368 6369 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 6370 llvm::NamedMDNode *&GlobalMetadata, 6371 GlobalDecl D, 6372 llvm::GlobalValue *Addr) { 6373 if (!GlobalMetadata) 6374 GlobalMetadata = 6375 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 6376 6377 // TODO: should we report variant information for ctors/dtors? 6378 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 6379 llvm::ConstantAsMetadata::get(GetPointerConstant( 6380 CGM.getLLVMContext(), D.getDecl()))}; 6381 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 6382 } 6383 6384 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, 6385 llvm::GlobalValue *CppFunc) { 6386 // Store the list of ifuncs we need to replace uses in. 6387 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs; 6388 // List of ConstantExprs that we should be able to delete when we're done 6389 // here. 6390 llvm::SmallVector<llvm::ConstantExpr *> CEs; 6391 6392 // It isn't valid to replace the extern-C ifuncs if all we find is itself! 6393 if (Elem == CppFunc) 6394 return false; 6395 6396 // First make sure that all users of this are ifuncs (or ifuncs via a 6397 // bitcast), and collect the list of ifuncs and CEs so we can work on them 6398 // later. 6399 for (llvm::User *User : Elem->users()) { 6400 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an 6401 // ifunc directly. In any other case, just give up, as we don't know what we 6402 // could break by changing those. 6403 if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) { 6404 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast) 6405 return false; 6406 6407 for (llvm::User *CEUser : ConstExpr->users()) { 6408 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) { 6409 IFuncs.push_back(IFunc); 6410 } else { 6411 return false; 6412 } 6413 } 6414 CEs.push_back(ConstExpr); 6415 } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) { 6416 IFuncs.push_back(IFunc); 6417 } else { 6418 // This user is one we don't know how to handle, so fail redirection. This 6419 // will result in an ifunc retaining a resolver name that will ultimately 6420 // fail to be resolved to a defined function. 6421 return false; 6422 } 6423 } 6424 6425 // Now we know this is a valid case where we can do this alias replacement, we 6426 // need to remove all of the references to Elem (and the bitcasts!) so we can 6427 // delete it. 6428 for (llvm::GlobalIFunc *IFunc : IFuncs) 6429 IFunc->setResolver(nullptr); 6430 for (llvm::ConstantExpr *ConstExpr : CEs) 6431 ConstExpr->destroyConstant(); 6432 6433 // We should now be out of uses for the 'old' version of this function, so we 6434 // can erase it as well. 6435 Elem->eraseFromParent(); 6436 6437 for (llvm::GlobalIFunc *IFunc : IFuncs) { 6438 // The type of the resolver is always just a function-type that returns the 6439 // type of the IFunc, so create that here. If the type of the actual 6440 // resolver doesn't match, it just gets bitcast to the right thing. 6441 auto *ResolverTy = 6442 llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false); 6443 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 6444 CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false); 6445 IFunc->setResolver(Resolver); 6446 } 6447 return true; 6448 } 6449 6450 /// For each function which is declared within an extern "C" region and marked 6451 /// as 'used', but has internal linkage, create an alias from the unmangled 6452 /// name to the mangled name if possible. People expect to be able to refer 6453 /// to such functions with an unmangled name from inline assembly within the 6454 /// same translation unit. 6455 void CodeGenModule::EmitStaticExternCAliases() { 6456 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 6457 return; 6458 for (auto &I : StaticExternCValues) { 6459 IdentifierInfo *Name = I.first; 6460 llvm::GlobalValue *Val = I.second; 6461 6462 // If Val is null, that implies there were multiple declarations that each 6463 // had a claim to the unmangled name. In this case, generation of the alias 6464 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC. 6465 if (!Val) 6466 break; 6467 6468 llvm::GlobalValue *ExistingElem = 6469 getModule().getNamedValue(Name->getName()); 6470 6471 // If there is either not something already by this name, or we were able to 6472 // replace all uses from IFuncs, create the alias. 6473 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val)) 6474 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 6475 } 6476 } 6477 6478 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 6479 GlobalDecl &Result) const { 6480 auto Res = Manglings.find(MangledName); 6481 if (Res == Manglings.end()) 6482 return false; 6483 Result = Res->getValue(); 6484 return true; 6485 } 6486 6487 /// Emits metadata nodes associating all the global values in the 6488 /// current module with the Decls they came from. This is useful for 6489 /// projects using IR gen as a subroutine. 6490 /// 6491 /// Since there's currently no way to associate an MDNode directly 6492 /// with an llvm::GlobalValue, we create a global named metadata 6493 /// with the name 'clang.global.decl.ptrs'. 6494 void CodeGenModule::EmitDeclMetadata() { 6495 llvm::NamedMDNode *GlobalMetadata = nullptr; 6496 6497 for (auto &I : MangledDeclNames) { 6498 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 6499 // Some mangled names don't necessarily have an associated GlobalValue 6500 // in this module, e.g. if we mangled it for DebugInfo. 6501 if (Addr) 6502 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 6503 } 6504 } 6505 6506 /// Emits metadata nodes for all the local variables in the current 6507 /// function. 6508 void CodeGenFunction::EmitDeclMetadata() { 6509 if (LocalDeclMap.empty()) return; 6510 6511 llvm::LLVMContext &Context = getLLVMContext(); 6512 6513 // Find the unique metadata ID for this name. 6514 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 6515 6516 llvm::NamedMDNode *GlobalMetadata = nullptr; 6517 6518 for (auto &I : LocalDeclMap) { 6519 const Decl *D = I.first; 6520 llvm::Value *Addr = I.second.getPointer(); 6521 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 6522 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 6523 Alloca->setMetadata( 6524 DeclPtrKind, llvm::MDNode::get( 6525 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 6526 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 6527 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 6528 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 6529 } 6530 } 6531 } 6532 6533 void CodeGenModule::EmitVersionIdentMetadata() { 6534 llvm::NamedMDNode *IdentMetadata = 6535 TheModule.getOrInsertNamedMetadata("llvm.ident"); 6536 std::string Version = getClangFullVersion(); 6537 llvm::LLVMContext &Ctx = TheModule.getContext(); 6538 6539 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 6540 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 6541 } 6542 6543 void CodeGenModule::EmitCommandLineMetadata() { 6544 llvm::NamedMDNode *CommandLineMetadata = 6545 TheModule.getOrInsertNamedMetadata("llvm.commandline"); 6546 std::string CommandLine = getCodeGenOpts().RecordCommandLine; 6547 llvm::LLVMContext &Ctx = TheModule.getContext(); 6548 6549 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 6550 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 6551 } 6552 6553 void CodeGenModule::EmitCoverageFile() { 6554 if (getCodeGenOpts().CoverageDataFile.empty() && 6555 getCodeGenOpts().CoverageNotesFile.empty()) 6556 return; 6557 6558 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 6559 if (!CUNode) 6560 return; 6561 6562 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 6563 llvm::LLVMContext &Ctx = TheModule.getContext(); 6564 auto *CoverageDataFile = 6565 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 6566 auto *CoverageNotesFile = 6567 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 6568 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 6569 llvm::MDNode *CU = CUNode->getOperand(i); 6570 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 6571 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 6572 } 6573 } 6574 6575 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 6576 bool ForEH) { 6577 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 6578 // FIXME: should we even be calling this method if RTTI is disabled 6579 // and it's not for EH? 6580 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice || 6581 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 6582 getTriple().isNVPTX())) 6583 return llvm::Constant::getNullValue(Int8PtrTy); 6584 6585 if (ForEH && Ty->isObjCObjectPointerType() && 6586 LangOpts.ObjCRuntime.isGNUFamily()) 6587 return ObjCRuntime->GetEHType(Ty); 6588 6589 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 6590 } 6591 6592 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 6593 // Do not emit threadprivates in simd-only mode. 6594 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 6595 return; 6596 for (auto RefExpr : D->varlists()) { 6597 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 6598 bool PerformInit = 6599 VD->getAnyInitializer() && 6600 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 6601 /*ForRef=*/false); 6602 6603 Address Addr(GetAddrOfGlobalVar(VD), 6604 getTypes().ConvertTypeForMem(VD->getType()), 6605 getContext().getDeclAlign(VD)); 6606 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 6607 VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 6608 CXXGlobalInits.push_back(InitFunction); 6609 } 6610 } 6611 6612 llvm::Metadata * 6613 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 6614 StringRef Suffix) { 6615 if (auto *FnType = T->getAs<FunctionProtoType>()) 6616 T = getContext().getFunctionType( 6617 FnType->getReturnType(), FnType->getParamTypes(), 6618 FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 6619 6620 llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 6621 if (InternalId) 6622 return InternalId; 6623 6624 if (isExternallyVisible(T->getLinkage())) { 6625 std::string OutName; 6626 llvm::raw_string_ostream Out(OutName); 6627 getCXXABI().getMangleContext().mangleTypeName(T, Out); 6628 Out << Suffix; 6629 6630 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 6631 } else { 6632 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 6633 llvm::ArrayRef<llvm::Metadata *>()); 6634 } 6635 6636 return InternalId; 6637 } 6638 6639 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 6640 return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 6641 } 6642 6643 llvm::Metadata * 6644 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 6645 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 6646 } 6647 6648 // Generalize pointer types to a void pointer with the qualifiers of the 6649 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 6650 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 6651 // 'void *'. 6652 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 6653 if (!Ty->isPointerType()) 6654 return Ty; 6655 6656 return Ctx.getPointerType( 6657 QualType(Ctx.VoidTy).withCVRQualifiers( 6658 Ty->getPointeeType().getCVRQualifiers())); 6659 } 6660 6661 // Apply type generalization to a FunctionType's return and argument types 6662 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 6663 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 6664 SmallVector<QualType, 8> GeneralizedParams; 6665 for (auto &Param : FnType->param_types()) 6666 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 6667 6668 return Ctx.getFunctionType( 6669 GeneralizeType(Ctx, FnType->getReturnType()), 6670 GeneralizedParams, FnType->getExtProtoInfo()); 6671 } 6672 6673 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 6674 return Ctx.getFunctionNoProtoType( 6675 GeneralizeType(Ctx, FnType->getReturnType())); 6676 6677 llvm_unreachable("Encountered unknown FunctionType"); 6678 } 6679 6680 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 6681 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 6682 GeneralizedMetadataIdMap, ".generalized"); 6683 } 6684 6685 /// Returns whether this module needs the "all-vtables" type identifier. 6686 bool CodeGenModule::NeedAllVtablesTypeId() const { 6687 // Returns true if at least one of vtable-based CFI checkers is enabled and 6688 // is not in the trapping mode. 6689 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 6690 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 6691 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 6692 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 6693 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 6694 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 6695 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 6696 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 6697 } 6698 6699 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 6700 CharUnits Offset, 6701 const CXXRecordDecl *RD) { 6702 llvm::Metadata *MD = 6703 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 6704 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6705 6706 if (CodeGenOpts.SanitizeCfiCrossDso) 6707 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 6708 VTable->addTypeMetadata(Offset.getQuantity(), 6709 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 6710 6711 if (NeedAllVtablesTypeId()) { 6712 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 6713 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6714 } 6715 } 6716 6717 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 6718 if (!SanStats) 6719 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 6720 6721 return *SanStats; 6722 } 6723 6724 llvm::Value * 6725 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 6726 CodeGenFunction &CGF) { 6727 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 6728 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 6729 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 6730 auto *Call = CGF.EmitRuntimeCall( 6731 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 6732 return Call; 6733 } 6734 6735 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 6736 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 6737 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 6738 /* forPointeeType= */ true); 6739 } 6740 6741 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 6742 LValueBaseInfo *BaseInfo, 6743 TBAAAccessInfo *TBAAInfo, 6744 bool forPointeeType) { 6745 if (TBAAInfo) 6746 *TBAAInfo = getTBAAAccessInfo(T); 6747 6748 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 6749 // that doesn't return the information we need to compute BaseInfo. 6750 6751 // Honor alignment typedef attributes even on incomplete types. 6752 // We also honor them straight for C++ class types, even as pointees; 6753 // there's an expressivity gap here. 6754 if (auto TT = T->getAs<TypedefType>()) { 6755 if (auto Align = TT->getDecl()->getMaxAlignment()) { 6756 if (BaseInfo) 6757 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 6758 return getContext().toCharUnitsFromBits(Align); 6759 } 6760 } 6761 6762 bool AlignForArray = T->isArrayType(); 6763 6764 // Analyze the base element type, so we don't get confused by incomplete 6765 // array types. 6766 T = getContext().getBaseElementType(T); 6767 6768 if (T->isIncompleteType()) { 6769 // We could try to replicate the logic from 6770 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 6771 // type is incomplete, so it's impossible to test. We could try to reuse 6772 // getTypeAlignIfKnown, but that doesn't return the information we need 6773 // to set BaseInfo. So just ignore the possibility that the alignment is 6774 // greater than one. 6775 if (BaseInfo) 6776 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6777 return CharUnits::One(); 6778 } 6779 6780 if (BaseInfo) 6781 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6782 6783 CharUnits Alignment; 6784 const CXXRecordDecl *RD; 6785 if (T.getQualifiers().hasUnaligned()) { 6786 Alignment = CharUnits::One(); 6787 } else if (forPointeeType && !AlignForArray && 6788 (RD = T->getAsCXXRecordDecl())) { 6789 // For C++ class pointees, we don't know whether we're pointing at a 6790 // base or a complete object, so we generally need to use the 6791 // non-virtual alignment. 6792 Alignment = getClassPointerAlignment(RD); 6793 } else { 6794 Alignment = getContext().getTypeAlignInChars(T); 6795 } 6796 6797 // Cap to the global maximum type alignment unless the alignment 6798 // was somehow explicit on the type. 6799 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 6800 if (Alignment.getQuantity() > MaxAlign && 6801 !getContext().isAlignmentRequired(T)) 6802 Alignment = CharUnits::fromQuantity(MaxAlign); 6803 } 6804 return Alignment; 6805 } 6806 6807 bool CodeGenModule::stopAutoInit() { 6808 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 6809 if (StopAfter) { 6810 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 6811 // used 6812 if (NumAutoVarInit >= StopAfter) { 6813 return true; 6814 } 6815 if (!NumAutoVarInit) { 6816 unsigned DiagID = getDiags().getCustomDiagID( 6817 DiagnosticsEngine::Warning, 6818 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 6819 "number of times ftrivial-auto-var-init=%1 gets applied."); 6820 getDiags().Report(DiagID) 6821 << StopAfter 6822 << (getContext().getLangOpts().getTrivialAutoVarInit() == 6823 LangOptions::TrivialAutoVarInitKind::Zero 6824 ? "zero" 6825 : "pattern"); 6826 } 6827 ++NumAutoVarInit; 6828 } 6829 return false; 6830 } 6831 6832 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, 6833 const Decl *D) const { 6834 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers 6835 // postfix beginning with '.' since the symbol name can be demangled. 6836 if (LangOpts.HIP) 6837 OS << (isa<VarDecl>(D) ? ".static." : ".intern."); 6838 else 6839 OS << (isa<VarDecl>(D) ? "__static__" : "__intern__"); 6840 6841 // If the CUID is not specified we try to generate a unique postfix. 6842 if (getLangOpts().CUID.empty()) { 6843 SourceManager &SM = getContext().getSourceManager(); 6844 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation()); 6845 assert(PLoc.isValid() && "Source location is expected to be valid."); 6846 6847 // Get the hash of the user defined macros. 6848 llvm::MD5 Hash; 6849 llvm::MD5::MD5Result Result; 6850 for (const auto &Arg : PreprocessorOpts.Macros) 6851 Hash.update(Arg.first); 6852 Hash.final(Result); 6853 6854 // Get the UniqueID for the file containing the decl. 6855 llvm::sys::fs::UniqueID ID; 6856 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { 6857 PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false); 6858 assert(PLoc.isValid() && "Source location is expected to be valid."); 6859 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) 6860 SM.getDiagnostics().Report(diag::err_cannot_open_file) 6861 << PLoc.getFilename() << EC.message(); 6862 } 6863 OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice()) 6864 << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8); 6865 } else { 6866 OS << getContext().getCUIDHash(); 6867 } 6868 } 6869