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