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