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