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