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