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