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