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