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