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