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