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