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