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