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