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