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