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