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