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