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