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