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