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 1696 // For modules that use export_as for linking, use that module 1697 // name instead. 1698 if (Mod->UseExportAsModuleLinkName) 1699 return; 1700 1701 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1702 // Link against a framework. Frameworks are currently Darwin only, so we 1703 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1704 if (Mod->LinkLibraries[I-1].IsFramework) { 1705 llvm::Metadata *Args[2] = { 1706 llvm::MDString::get(Context, "-framework"), 1707 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1708 1709 Metadata.push_back(llvm::MDNode::get(Context, Args)); 1710 continue; 1711 } 1712 1713 // Link against a library. 1714 llvm::SmallString<24> Opt; 1715 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1716 Mod->LinkLibraries[I-1].Library, Opt); 1717 auto *OptString = llvm::MDString::get(Context, Opt); 1718 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1719 } 1720 } 1721 1722 void CodeGenModule::EmitModuleLinkOptions() { 1723 // Collect the set of all of the modules we want to visit to emit link 1724 // options, which is essentially the imported modules and all of their 1725 // non-explicit child modules. 1726 llvm::SetVector<clang::Module *> LinkModules; 1727 llvm::SmallPtrSet<clang::Module *, 16> Visited; 1728 SmallVector<clang::Module *, 16> Stack; 1729 1730 // Seed the stack with imported modules. 1731 for (Module *M : ImportedModules) { 1732 // Do not add any link flags when an implementation TU of a module imports 1733 // a header of that same module. 1734 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 1735 !getLangOpts().isCompilingModule()) 1736 continue; 1737 if (Visited.insert(M).second) 1738 Stack.push_back(M); 1739 } 1740 1741 // Find all of the modules to import, making a little effort to prune 1742 // non-leaf modules. 1743 while (!Stack.empty()) { 1744 clang::Module *Mod = Stack.pop_back_val(); 1745 1746 bool AnyChildren = false; 1747 1748 // Visit the submodules of this module. 1749 for (const auto &SM : Mod->submodules()) { 1750 // Skip explicit children; they need to be explicitly imported to be 1751 // linked against. 1752 if (SM->IsExplicit) 1753 continue; 1754 1755 if (Visited.insert(SM).second) { 1756 Stack.push_back(SM); 1757 AnyChildren = true; 1758 } 1759 } 1760 1761 // We didn't find any children, so add this module to the list of 1762 // modules to link against. 1763 if (!AnyChildren) { 1764 LinkModules.insert(Mod); 1765 } 1766 } 1767 1768 // Add link options for all of the imported modules in reverse topological 1769 // order. We don't do anything to try to order import link flags with respect 1770 // to linker options inserted by things like #pragma comment(). 1771 SmallVector<llvm::MDNode *, 16> MetadataArgs; 1772 Visited.clear(); 1773 for (Module *M : LinkModules) 1774 if (Visited.insert(M).second) 1775 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1776 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1777 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1778 1779 // Add the linker options metadata flag. 1780 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 1781 for (auto *MD : LinkerOptionsMetadata) 1782 NMD->addOperand(MD); 1783 } 1784 1785 void CodeGenModule::EmitDeferred() { 1786 // Emit deferred declare target declarations. 1787 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 1788 getOpenMPRuntime().emitDeferredTargetDecls(); 1789 1790 // Emit code for any potentially referenced deferred decls. Since a 1791 // previously unused static decl may become used during the generation of code 1792 // for a static function, iterate until no changes are made. 1793 1794 if (!DeferredVTables.empty()) { 1795 EmitDeferredVTables(); 1796 1797 // Emitting a vtable doesn't directly cause more vtables to 1798 // become deferred, although it can cause functions to be 1799 // emitted that then need those vtables. 1800 assert(DeferredVTables.empty()); 1801 } 1802 1803 // Stop if we're out of both deferred vtables and deferred declarations. 1804 if (DeferredDeclsToEmit.empty()) 1805 return; 1806 1807 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 1808 // work, it will not interfere with this. 1809 std::vector<GlobalDecl> CurDeclsToEmit; 1810 CurDeclsToEmit.swap(DeferredDeclsToEmit); 1811 1812 for (GlobalDecl &D : CurDeclsToEmit) { 1813 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 1814 // to get GlobalValue with exactly the type we need, not something that 1815 // might had been created for another decl with the same mangled name but 1816 // different type. 1817 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 1818 GetAddrOfGlobal(D, ForDefinition)); 1819 1820 // In case of different address spaces, we may still get a cast, even with 1821 // IsForDefinition equal to true. Query mangled names table to get 1822 // GlobalValue. 1823 if (!GV) 1824 GV = GetGlobalValue(getMangledName(D)); 1825 1826 // Make sure GetGlobalValue returned non-null. 1827 assert(GV); 1828 1829 // Check to see if we've already emitted this. This is necessary 1830 // for a couple of reasons: first, decls can end up in the 1831 // deferred-decls queue multiple times, and second, decls can end 1832 // up with definitions in unusual ways (e.g. by an extern inline 1833 // function acquiring a strong function redefinition). Just 1834 // ignore these cases. 1835 if (!GV->isDeclaration()) 1836 continue; 1837 1838 // Otherwise, emit the definition and move on to the next one. 1839 EmitGlobalDefinition(D, GV); 1840 1841 // If we found out that we need to emit more decls, do that recursively. 1842 // This has the advantage that the decls are emitted in a DFS and related 1843 // ones are close together, which is convenient for testing. 1844 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 1845 EmitDeferred(); 1846 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 1847 } 1848 } 1849 } 1850 1851 void CodeGenModule::EmitVTablesOpportunistically() { 1852 // Try to emit external vtables as available_externally if they have emitted 1853 // all inlined virtual functions. It runs after EmitDeferred() and therefore 1854 // is not allowed to create new references to things that need to be emitted 1855 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 1856 1857 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 1858 && "Only emit opportunistic vtables with optimizations"); 1859 1860 for (const CXXRecordDecl *RD : OpportunisticVTables) { 1861 assert(getVTables().isVTableExternal(RD) && 1862 "This queue should only contain external vtables"); 1863 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 1864 VTables.GenerateClassData(RD); 1865 } 1866 OpportunisticVTables.clear(); 1867 } 1868 1869 void CodeGenModule::EmitGlobalAnnotations() { 1870 if (Annotations.empty()) 1871 return; 1872 1873 // Create a new global variable for the ConstantStruct in the Module. 1874 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1875 Annotations[0]->getType(), Annotations.size()), Annotations); 1876 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 1877 llvm::GlobalValue::AppendingLinkage, 1878 Array, "llvm.global.annotations"); 1879 gv->setSection(AnnotationSection); 1880 } 1881 1882 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1883 llvm::Constant *&AStr = AnnotationStrings[Str]; 1884 if (AStr) 1885 return AStr; 1886 1887 // Not found yet, create a new global. 1888 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1889 auto *gv = 1890 new llvm::GlobalVariable(getModule(), s->getType(), true, 1891 llvm::GlobalValue::PrivateLinkage, s, ".str"); 1892 gv->setSection(AnnotationSection); 1893 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1894 AStr = gv; 1895 return gv; 1896 } 1897 1898 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1899 SourceManager &SM = getContext().getSourceManager(); 1900 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1901 if (PLoc.isValid()) 1902 return EmitAnnotationString(PLoc.getFilename()); 1903 return EmitAnnotationString(SM.getBufferName(Loc)); 1904 } 1905 1906 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1907 SourceManager &SM = getContext().getSourceManager(); 1908 PresumedLoc PLoc = SM.getPresumedLoc(L); 1909 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1910 SM.getExpansionLineNumber(L); 1911 return llvm::ConstantInt::get(Int32Ty, LineNo); 1912 } 1913 1914 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1915 const AnnotateAttr *AA, 1916 SourceLocation L) { 1917 // Get the globals for file name, annotation, and the line number. 1918 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1919 *UnitGV = EmitAnnotationUnit(L), 1920 *LineNoCst = EmitAnnotationLineNo(L); 1921 1922 // Create the ConstantStruct for the global annotation. 1923 llvm::Constant *Fields[4] = { 1924 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1925 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1926 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1927 LineNoCst 1928 }; 1929 return llvm::ConstantStruct::getAnon(Fields); 1930 } 1931 1932 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1933 llvm::GlobalValue *GV) { 1934 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1935 // Get the struct elements for these annotations. 1936 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1937 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 1938 } 1939 1940 bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind, 1941 llvm::Function *Fn, 1942 SourceLocation Loc) const { 1943 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1944 // Blacklist by function name. 1945 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName())) 1946 return true; 1947 // Blacklist by location. 1948 if (Loc.isValid()) 1949 return SanitizerBL.isBlacklistedLocation(Kind, Loc); 1950 // If location is unknown, this may be a compiler-generated function. Assume 1951 // it's located in the main file. 1952 auto &SM = Context.getSourceManager(); 1953 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 1954 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName()); 1955 } 1956 return false; 1957 } 1958 1959 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 1960 SourceLocation Loc, QualType Ty, 1961 StringRef Category) const { 1962 // For now globals can be blacklisted only in ASan and KASan. 1963 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask & 1964 (SanitizerKind::Address | SanitizerKind::KernelAddress | 1965 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress); 1966 if (!EnabledAsanMask) 1967 return false; 1968 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 1969 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category)) 1970 return true; 1971 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category)) 1972 return true; 1973 // Check global type. 1974 if (!Ty.isNull()) { 1975 // Drill down the array types: if global variable of a fixed type is 1976 // blacklisted, we also don't instrument arrays of them. 1977 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 1978 Ty = AT->getElementType(); 1979 Ty = Ty.getCanonicalType().getUnqualifiedType(); 1980 // We allow to blacklist only record types (classes, structs etc.) 1981 if (Ty->isRecordType()) { 1982 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 1983 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category)) 1984 return true; 1985 } 1986 } 1987 return false; 1988 } 1989 1990 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 1991 StringRef Category) const { 1992 const auto &XRayFilter = getContext().getXRayFilter(); 1993 using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 1994 auto Attr = ImbueAttr::NONE; 1995 if (Loc.isValid()) 1996 Attr = XRayFilter.shouldImbueLocation(Loc, Category); 1997 if (Attr == ImbueAttr::NONE) 1998 Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 1999 switch (Attr) { 2000 case ImbueAttr::NONE: 2001 return false; 2002 case ImbueAttr::ALWAYS: 2003 Fn->addFnAttr("function-instrument", "xray-always"); 2004 break; 2005 case ImbueAttr::ALWAYS_ARG1: 2006 Fn->addFnAttr("function-instrument", "xray-always"); 2007 Fn->addFnAttr("xray-log-args", "1"); 2008 break; 2009 case ImbueAttr::NEVER: 2010 Fn->addFnAttr("function-instrument", "xray-never"); 2011 break; 2012 } 2013 return true; 2014 } 2015 2016 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 2017 // Never defer when EmitAllDecls is specified. 2018 if (LangOpts.EmitAllDecls) 2019 return true; 2020 2021 if (CodeGenOpts.KeepStaticConsts) { 2022 const auto *VD = dyn_cast<VarDecl>(Global); 2023 if (VD && VD->getType().isConstQualified() && 2024 VD->getStorageDuration() == SD_Static) 2025 return true; 2026 } 2027 2028 return getContext().DeclMustBeEmitted(Global); 2029 } 2030 2031 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 2032 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 2033 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 2034 // Implicit template instantiations may change linkage if they are later 2035 // explicitly instantiated, so they should not be emitted eagerly. 2036 return false; 2037 if (const auto *VD = dyn_cast<VarDecl>(Global)) 2038 if (Context.getInlineVariableDefinitionKind(VD) == 2039 ASTContext::InlineVariableDefinitionKind::WeakUnknown) 2040 // A definition of an inline constexpr static data member may change 2041 // linkage later if it's redeclared outside the class. 2042 return false; 2043 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 2044 // codegen for global variables, because they may be marked as threadprivate. 2045 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 2046 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 2047 !isTypeConstant(Global->getType(), false) && 2048 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 2049 return false; 2050 2051 return true; 2052 } 2053 2054 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 2055 const CXXUuidofExpr* E) { 2056 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 2057 // well-formed. 2058 StringRef Uuid = E->getUuidStr(); 2059 std::string Name = "_GUID_" + Uuid.lower(); 2060 std::replace(Name.begin(), Name.end(), '-', '_'); 2061 2062 // The UUID descriptor should be pointer aligned. 2063 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 2064 2065 // Look for an existing global. 2066 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 2067 return ConstantAddress(GV, Alignment); 2068 2069 llvm::Constant *Init = EmitUuidofInitializer(Uuid); 2070 assert(Init && "failed to initialize as constant"); 2071 2072 auto *GV = new llvm::GlobalVariable( 2073 getModule(), Init->getType(), 2074 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2075 if (supportsCOMDAT()) 2076 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2077 setDSOLocal(GV); 2078 return ConstantAddress(GV, Alignment); 2079 } 2080 2081 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 2082 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 2083 assert(AA && "No alias?"); 2084 2085 CharUnits Alignment = getContext().getDeclAlign(VD); 2086 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 2087 2088 // See if there is already something with the target's name in the module. 2089 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 2090 if (Entry) { 2091 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 2092 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 2093 return ConstantAddress(Ptr, Alignment); 2094 } 2095 2096 llvm::Constant *Aliasee; 2097 if (isa<llvm::FunctionType>(DeclTy)) 2098 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 2099 GlobalDecl(cast<FunctionDecl>(VD)), 2100 /*ForVTable=*/false); 2101 else 2102 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2103 llvm::PointerType::getUnqual(DeclTy), 2104 nullptr); 2105 2106 auto *F = cast<llvm::GlobalValue>(Aliasee); 2107 F->setLinkage(llvm::Function::ExternalWeakLinkage); 2108 WeakRefReferences.insert(F); 2109 2110 return ConstantAddress(Aliasee, Alignment); 2111 } 2112 2113 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 2114 const auto *Global = cast<ValueDecl>(GD.getDecl()); 2115 2116 // Weak references don't produce any output by themselves. 2117 if (Global->hasAttr<WeakRefAttr>()) 2118 return; 2119 2120 // If this is an alias definition (which otherwise looks like a declaration) 2121 // emit it now. 2122 if (Global->hasAttr<AliasAttr>()) 2123 return EmitAliasDefinition(GD); 2124 2125 // IFunc like an alias whose value is resolved at runtime by calling resolver. 2126 if (Global->hasAttr<IFuncAttr>()) 2127 return emitIFuncDefinition(GD); 2128 2129 // If this is a cpu_dispatch multiversion function, emit the resolver. 2130 if (Global->hasAttr<CPUDispatchAttr>()) 2131 return emitCPUDispatchDefinition(GD); 2132 2133 // If this is CUDA, be selective about which declarations we emit. 2134 if (LangOpts.CUDA) { 2135 if (LangOpts.CUDAIsDevice) { 2136 if (!Global->hasAttr<CUDADeviceAttr>() && 2137 !Global->hasAttr<CUDAGlobalAttr>() && 2138 !Global->hasAttr<CUDAConstantAttr>() && 2139 !Global->hasAttr<CUDASharedAttr>()) 2140 return; 2141 } else { 2142 // We need to emit host-side 'shadows' for all global 2143 // device-side variables because the CUDA runtime needs their 2144 // size and host-side address in order to provide access to 2145 // their device-side incarnations. 2146 2147 // So device-only functions are the only things we skip. 2148 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 2149 Global->hasAttr<CUDADeviceAttr>()) 2150 return; 2151 2152 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 2153 "Expected Variable or Function"); 2154 } 2155 } 2156 2157 if (LangOpts.OpenMP) { 2158 // If this is OpenMP device, check if it is legal to emit this global 2159 // normally. 2160 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 2161 return; 2162 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 2163 if (MustBeEmitted(Global)) 2164 EmitOMPDeclareReduction(DRD); 2165 return; 2166 } 2167 } 2168 2169 // Ignore declarations, they will be emitted on their first use. 2170 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2171 // Forward declarations are emitted lazily on first use. 2172 if (!FD->doesThisDeclarationHaveABody()) { 2173 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 2174 return; 2175 2176 StringRef MangledName = getMangledName(GD); 2177 2178 // Compute the function info and LLVM type. 2179 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2180 llvm::Type *Ty = getTypes().GetFunctionType(FI); 2181 2182 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 2183 /*DontDefer=*/false); 2184 return; 2185 } 2186 } else { 2187 const auto *VD = cast<VarDecl>(Global); 2188 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 2189 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 2190 !Context.isMSStaticDataMemberInlineDefinition(VD)) { 2191 if (LangOpts.OpenMP) { 2192 // Emit declaration of the must-be-emitted declare target variable. 2193 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2194 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 2195 if (*Res == OMPDeclareTargetDeclAttr::MT_To) { 2196 (void)GetAddrOfGlobalVar(VD); 2197 } else { 2198 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link && 2199 "link claue expected."); 2200 (void)getOpenMPRuntime().getAddrOfDeclareTargetLink(VD); 2201 } 2202 return; 2203 } 2204 } 2205 // If this declaration may have caused an inline variable definition to 2206 // change linkage, make sure that it's emitted. 2207 if (Context.getInlineVariableDefinitionKind(VD) == 2208 ASTContext::InlineVariableDefinitionKind::Strong) 2209 GetAddrOfGlobalVar(VD); 2210 return; 2211 } 2212 } 2213 2214 // Defer code generation to first use when possible, e.g. if this is an inline 2215 // function. If the global must always be emitted, do it eagerly if possible 2216 // to benefit from cache locality. 2217 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 2218 // Emit the definition if it can't be deferred. 2219 EmitGlobalDefinition(GD); 2220 return; 2221 } 2222 2223 // If we're deferring emission of a C++ variable with an 2224 // initializer, remember the order in which it appeared in the file. 2225 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 2226 cast<VarDecl>(Global)->hasInit()) { 2227 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 2228 CXXGlobalInits.push_back(nullptr); 2229 } 2230 2231 StringRef MangledName = getMangledName(GD); 2232 if (GetGlobalValue(MangledName) != nullptr) { 2233 // The value has already been used and should therefore be emitted. 2234 addDeferredDeclToEmit(GD); 2235 } else if (MustBeEmitted(Global)) { 2236 // The value must be emitted, but cannot be emitted eagerly. 2237 assert(!MayBeEmittedEagerly(Global)); 2238 addDeferredDeclToEmit(GD); 2239 } else { 2240 // Otherwise, remember that we saw a deferred decl with this name. The 2241 // first use of the mangled name will cause it to move into 2242 // DeferredDeclsToEmit. 2243 DeferredDecls[MangledName] = GD; 2244 } 2245 } 2246 2247 // Check if T is a class type with a destructor that's not dllimport. 2248 static bool HasNonDllImportDtor(QualType T) { 2249 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2250 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2251 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 2252 return true; 2253 2254 return false; 2255 } 2256 2257 namespace { 2258 struct FunctionIsDirectlyRecursive : 2259 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 2260 const StringRef Name; 2261 const Builtin::Context &BI; 2262 bool Result; 2263 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 2264 Name(N), BI(C), Result(false) { 2265 } 2266 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 2267 2268 bool TraverseCallExpr(CallExpr *E) { 2269 const FunctionDecl *FD = E->getDirectCallee(); 2270 if (!FD) 2271 return true; 2272 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 2273 if (Attr && Name == Attr->getLabel()) { 2274 Result = true; 2275 return false; 2276 } 2277 unsigned BuiltinID = FD->getBuiltinID(); 2278 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 2279 return true; 2280 StringRef BuiltinName = BI.getName(BuiltinID); 2281 if (BuiltinName.startswith("__builtin_") && 2282 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 2283 Result = true; 2284 return false; 2285 } 2286 return true; 2287 } 2288 }; 2289 2290 // Make sure we're not referencing non-imported vars or functions. 2291 struct DLLImportFunctionVisitor 2292 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 2293 bool SafeToInline = true; 2294 2295 bool shouldVisitImplicitCode() const { return true; } 2296 2297 bool VisitVarDecl(VarDecl *VD) { 2298 if (VD->getTLSKind()) { 2299 // A thread-local variable cannot be imported. 2300 SafeToInline = false; 2301 return SafeToInline; 2302 } 2303 2304 // A variable definition might imply a destructor call. 2305 if (VD->isThisDeclarationADefinition()) 2306 SafeToInline = !HasNonDllImportDtor(VD->getType()); 2307 2308 return SafeToInline; 2309 } 2310 2311 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 2312 if (const auto *D = E->getTemporary()->getDestructor()) 2313 SafeToInline = D->hasAttr<DLLImportAttr>(); 2314 return SafeToInline; 2315 } 2316 2317 bool VisitDeclRefExpr(DeclRefExpr *E) { 2318 ValueDecl *VD = E->getDecl(); 2319 if (isa<FunctionDecl>(VD)) 2320 SafeToInline = VD->hasAttr<DLLImportAttr>(); 2321 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 2322 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 2323 return SafeToInline; 2324 } 2325 2326 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 2327 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 2328 return SafeToInline; 2329 } 2330 2331 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2332 CXXMethodDecl *M = E->getMethodDecl(); 2333 if (!M) { 2334 // Call through a pointer to member function. This is safe to inline. 2335 SafeToInline = true; 2336 } else { 2337 SafeToInline = M->hasAttr<DLLImportAttr>(); 2338 } 2339 return SafeToInline; 2340 } 2341 2342 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 2343 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 2344 return SafeToInline; 2345 } 2346 2347 bool VisitCXXNewExpr(CXXNewExpr *E) { 2348 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 2349 return SafeToInline; 2350 } 2351 }; 2352 } 2353 2354 // isTriviallyRecursive - Check if this function calls another 2355 // decl that, because of the asm attribute or the other decl being a builtin, 2356 // ends up pointing to itself. 2357 bool 2358 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 2359 StringRef Name; 2360 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 2361 // asm labels are a special kind of mangling we have to support. 2362 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 2363 if (!Attr) 2364 return false; 2365 Name = Attr->getLabel(); 2366 } else { 2367 Name = FD->getName(); 2368 } 2369 2370 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 2371 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 2372 return Walker.Result; 2373 } 2374 2375 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 2376 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 2377 return true; 2378 const auto *F = cast<FunctionDecl>(GD.getDecl()); 2379 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 2380 return false; 2381 2382 if (F->hasAttr<DLLImportAttr>()) { 2383 // Check whether it would be safe to inline this dllimport function. 2384 DLLImportFunctionVisitor Visitor; 2385 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 2386 if (!Visitor.SafeToInline) 2387 return false; 2388 2389 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 2390 // Implicit destructor invocations aren't captured in the AST, so the 2391 // check above can't see them. Check for them manually here. 2392 for (const Decl *Member : Dtor->getParent()->decls()) 2393 if (isa<FieldDecl>(Member)) 2394 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 2395 return false; 2396 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 2397 if (HasNonDllImportDtor(B.getType())) 2398 return false; 2399 } 2400 } 2401 2402 // PR9614. Avoid cases where the source code is lying to us. An available 2403 // externally function should have an equivalent function somewhere else, 2404 // but a function that calls itself is clearly not equivalent to the real 2405 // implementation. 2406 // This happens in glibc's btowc and in some configure checks. 2407 return !isTriviallyRecursive(F); 2408 } 2409 2410 bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 2411 return CodeGenOpts.OptimizationLevel > 0; 2412 } 2413 2414 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 2415 llvm::GlobalValue *GV) { 2416 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2417 2418 if (FD->isCPUSpecificMultiVersion()) { 2419 auto *Spec = FD->getAttr<CPUSpecificAttr>(); 2420 for (unsigned I = 0; I < Spec->cpus_size(); ++I) 2421 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 2422 // Requires multiple emits. 2423 } else 2424 EmitGlobalFunctionDefinition(GD, GV); 2425 } 2426 2427 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 2428 const auto *D = cast<ValueDecl>(GD.getDecl()); 2429 2430 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 2431 Context.getSourceManager(), 2432 "Generating code for declaration"); 2433 2434 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2435 // At -O0, don't generate IR for functions with available_externally 2436 // linkage. 2437 if (!shouldEmitFunction(GD)) 2438 return; 2439 2440 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 2441 // Make sure to emit the definition(s) before we emit the thunks. 2442 // This is necessary for the generation of certain thunks. 2443 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 2444 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 2445 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 2446 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 2447 else if (FD->isMultiVersion()) 2448 EmitMultiVersionFunctionDefinition(GD, GV); 2449 else 2450 EmitGlobalFunctionDefinition(GD, GV); 2451 2452 if (Method->isVirtual()) 2453 getVTables().EmitThunks(GD); 2454 2455 return; 2456 } 2457 2458 if (FD->isMultiVersion()) 2459 return EmitMultiVersionFunctionDefinition(GD, GV); 2460 return EmitGlobalFunctionDefinition(GD, GV); 2461 } 2462 2463 if (const auto *VD = dyn_cast<VarDecl>(D)) 2464 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 2465 2466 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 2467 } 2468 2469 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2470 llvm::Function *NewFn); 2471 2472 static unsigned 2473 TargetMVPriority(const TargetInfo &TI, 2474 const CodeGenFunction::MultiVersionResolverOption &RO) { 2475 unsigned Priority = 0; 2476 for (StringRef Feat : RO.Conditions.Features) 2477 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 2478 2479 if (!RO.Conditions.Architecture.empty()) 2480 Priority = std::max( 2481 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 2482 return Priority; 2483 } 2484 2485 void CodeGenModule::emitMultiVersionFunctions() { 2486 for (GlobalDecl GD : MultiVersionFuncs) { 2487 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 2488 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 2489 getContext().forEachMultiversionedFunctionVersion( 2490 FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 2491 GlobalDecl CurGD{ 2492 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 2493 StringRef MangledName = getMangledName(CurGD); 2494 llvm::Constant *Func = GetGlobalValue(MangledName); 2495 if (!Func) { 2496 if (CurFD->isDefined()) { 2497 EmitGlobalFunctionDefinition(CurGD, nullptr); 2498 Func = GetGlobalValue(MangledName); 2499 } else { 2500 const CGFunctionInfo &FI = 2501 getTypes().arrangeGlobalDeclaration(GD); 2502 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2503 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 2504 /*DontDefer=*/false, ForDefinition); 2505 } 2506 assert(Func && "This should have just been created"); 2507 } 2508 2509 const auto *TA = CurFD->getAttr<TargetAttr>(); 2510 llvm::SmallVector<StringRef, 8> Feats; 2511 TA->getAddedFeatures(Feats); 2512 2513 Options.emplace_back(cast<llvm::Function>(Func), 2514 TA->getArchitecture(), Feats); 2515 }); 2516 2517 llvm::Function *ResolverFunc; 2518 const TargetInfo &TI = getTarget(); 2519 2520 if (TI.supportsIFunc() || FD->isTargetMultiVersion()) 2521 ResolverFunc = cast<llvm::Function>( 2522 GetGlobalValue((getMangledName(GD) + ".resolver").str())); 2523 else 2524 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD))); 2525 2526 if (supportsCOMDAT()) 2527 ResolverFunc->setComdat( 2528 getModule().getOrInsertComdat(ResolverFunc->getName())); 2529 2530 std::stable_sort( 2531 Options.begin(), Options.end(), 2532 [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 2533 const CodeGenFunction::MultiVersionResolverOption &RHS) { 2534 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 2535 }); 2536 CodeGenFunction CGF(*this); 2537 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 2538 } 2539 } 2540 2541 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 2542 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2543 assert(FD && "Not a FunctionDecl?"); 2544 const auto *DD = FD->getAttr<CPUDispatchAttr>(); 2545 assert(DD && "Not a cpu_dispatch Function?"); 2546 QualType CanonTy = Context.getCanonicalType(FD->getType()); 2547 llvm::Type *DeclTy = getTypes().ConvertFunctionType(CanonTy, FD); 2548 2549 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 2550 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD); 2551 DeclTy = getTypes().GetFunctionType(FInfo); 2552 } 2553 2554 StringRef ResolverName = getMangledName(GD); 2555 2556 llvm::Type *ResolverType; 2557 GlobalDecl ResolverGD; 2558 if (getTarget().supportsIFunc()) 2559 ResolverType = llvm::FunctionType::get( 2560 llvm::PointerType::get(DeclTy, 2561 Context.getTargetAddressSpace(FD->getType())), 2562 false); 2563 else { 2564 ResolverType = DeclTy; 2565 ResolverGD = GD; 2566 } 2567 2568 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 2569 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 2570 2571 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 2572 const TargetInfo &Target = getTarget(); 2573 unsigned Index = 0; 2574 for (const IdentifierInfo *II : DD->cpus()) { 2575 // Get the name of the target function so we can look it up/create it. 2576 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 2577 getCPUSpecificMangling(*this, II->getName()); 2578 2579 llvm::Constant *Func = GetGlobalValue(MangledName); 2580 2581 if (!Func) { 2582 GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 2583 if (ExistingDecl.getDecl() && 2584 ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 2585 EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 2586 Func = GetGlobalValue(MangledName); 2587 } else { 2588 if (!ExistingDecl.getDecl()) 2589 ExistingDecl = GD.getWithMultiVersionIndex(Index); 2590 2591 Func = GetOrCreateLLVMFunction( 2592 MangledName, DeclTy, ExistingDecl, 2593 /*ForVTable=*/false, /*DontDefer=*/true, 2594 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 2595 } 2596 } 2597 2598 llvm::SmallVector<StringRef, 32> Features; 2599 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 2600 llvm::transform(Features, Features.begin(), 2601 [](StringRef Str) { return Str.substr(1); }); 2602 Features.erase(std::remove_if( 2603 Features.begin(), Features.end(), [&Target](StringRef Feat) { 2604 return !Target.validateCpuSupports(Feat); 2605 }), Features.end()); 2606 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 2607 ++Index; 2608 } 2609 2610 llvm::sort( 2611 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 2612 const CodeGenFunction::MultiVersionResolverOption &RHS) { 2613 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) > 2614 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features); 2615 }); 2616 2617 // If the list contains multiple 'default' versions, such as when it contains 2618 // 'pentium' and 'generic', don't emit the call to the generic one (since we 2619 // always run on at least a 'pentium'). We do this by deleting the 'least 2620 // advanced' (read, lowest mangling letter). 2621 while (Options.size() > 1 && 2622 CodeGenFunction::GetX86CpuSupportsMask( 2623 (Options.end() - 2)->Conditions.Features) == 0) { 2624 StringRef LHSName = (Options.end() - 2)->Function->getName(); 2625 StringRef RHSName = (Options.end() - 1)->Function->getName(); 2626 if (LHSName.compare(RHSName) < 0) 2627 Options.erase(Options.end() - 2); 2628 else 2629 Options.erase(Options.end() - 1); 2630 } 2631 2632 CodeGenFunction CGF(*this); 2633 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 2634 } 2635 2636 /// If a dispatcher for the specified mangled name is not in the module, create 2637 /// and return an llvm Function with the specified type. 2638 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver( 2639 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) { 2640 std::string MangledName = 2641 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 2642 2643 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 2644 // a separate resolver). 2645 std::string ResolverName = MangledName; 2646 if (getTarget().supportsIFunc()) 2647 ResolverName += ".ifunc"; 2648 else if (FD->isTargetMultiVersion()) 2649 ResolverName += ".resolver"; 2650 2651 // If this already exists, just return that one. 2652 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 2653 return ResolverGV; 2654 2655 // Since this is the first time we've created this IFunc, make sure 2656 // that we put this multiversioned function into the list to be 2657 // replaced later if necessary (target multiversioning only). 2658 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion()) 2659 MultiVersionFuncs.push_back(GD); 2660 2661 if (getTarget().supportsIFunc()) { 2662 llvm::Type *ResolverType = llvm::FunctionType::get( 2663 llvm::PointerType::get( 2664 DeclTy, getContext().getTargetAddressSpace(FD->getType())), 2665 false); 2666 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 2667 MangledName + ".resolver", ResolverType, GlobalDecl{}, 2668 /*ForVTable=*/false); 2669 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create( 2670 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule()); 2671 GIF->setName(ResolverName); 2672 SetCommonAttributes(FD, GIF); 2673 2674 return GIF; 2675 } 2676 2677 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 2678 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 2679 assert(isa<llvm::GlobalValue>(Resolver) && 2680 "Resolver should be created for the first time"); 2681 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 2682 return Resolver; 2683 } 2684 2685 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 2686 /// module, create and return an llvm Function with the specified type. If there 2687 /// is something in the module with the specified name, return it potentially 2688 /// bitcasted to the right type. 2689 /// 2690 /// If D is non-null, it specifies a decl that correspond to this. This is used 2691 /// to set the attributes on the function when it is first created. 2692 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 2693 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 2694 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 2695 ForDefinition_t IsForDefinition) { 2696 const Decl *D = GD.getDecl(); 2697 2698 // Any attempts to use a MultiVersion function should result in retrieving 2699 // the iFunc instead. Name Mangling will handle the rest of the changes. 2700 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 2701 // For the device mark the function as one that should be emitted. 2702 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 2703 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 2704 !DontDefer && !IsForDefinition) { 2705 if (const FunctionDecl *FDDef = FD->getDefinition()) { 2706 GlobalDecl GDDef; 2707 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 2708 GDDef = GlobalDecl(CD, GD.getCtorType()); 2709 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 2710 GDDef = GlobalDecl(DD, GD.getDtorType()); 2711 else 2712 GDDef = GlobalDecl(FDDef); 2713 EmitGlobal(GDDef); 2714 } 2715 } 2716 2717 if (FD->isMultiVersion()) { 2718 const auto *TA = FD->getAttr<TargetAttr>(); 2719 if (TA && TA->isDefaultVersion()) 2720 UpdateMultiVersionNames(GD, FD); 2721 if (!IsForDefinition) 2722 return GetOrCreateMultiVersionResolver(GD, Ty, FD); 2723 } 2724 } 2725 2726 // Lookup the entry, lazily creating it if necessary. 2727 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2728 if (Entry) { 2729 if (WeakRefReferences.erase(Entry)) { 2730 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 2731 if (FD && !FD->hasAttr<WeakAttr>()) 2732 Entry->setLinkage(llvm::Function::ExternalLinkage); 2733 } 2734 2735 // Handle dropped DLL attributes. 2736 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) { 2737 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 2738 setDSOLocal(Entry); 2739 } 2740 2741 // If there are two attempts to define the same mangled name, issue an 2742 // error. 2743 if (IsForDefinition && !Entry->isDeclaration()) { 2744 GlobalDecl OtherGD; 2745 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 2746 // to make sure that we issue an error only once. 2747 if (lookupRepresentativeDecl(MangledName, OtherGD) && 2748 (GD.getCanonicalDecl().getDecl() != 2749 OtherGD.getCanonicalDecl().getDecl()) && 2750 DiagnosedConflictingDefinitions.insert(GD).second) { 2751 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 2752 << MangledName; 2753 getDiags().Report(OtherGD.getDecl()->getLocation(), 2754 diag::note_previous_definition); 2755 } 2756 } 2757 2758 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 2759 (Entry->getType()->getElementType() == Ty)) { 2760 return Entry; 2761 } 2762 2763 // Make sure the result is of the correct type. 2764 // (If function is requested for a definition, we always need to create a new 2765 // function, not just return a bitcast.) 2766 if (!IsForDefinition) 2767 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 2768 } 2769 2770 // This function doesn't have a complete type (for example, the return 2771 // type is an incomplete struct). Use a fake type instead, and make 2772 // sure not to try to set attributes. 2773 bool IsIncompleteFunction = false; 2774 2775 llvm::FunctionType *FTy; 2776 if (isa<llvm::FunctionType>(Ty)) { 2777 FTy = cast<llvm::FunctionType>(Ty); 2778 } else { 2779 FTy = llvm::FunctionType::get(VoidTy, false); 2780 IsIncompleteFunction = true; 2781 } 2782 2783 llvm::Function *F = 2784 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 2785 Entry ? StringRef() : MangledName, &getModule()); 2786 2787 // If we already created a function with the same mangled name (but different 2788 // type) before, take its name and add it to the list of functions to be 2789 // replaced with F at the end of CodeGen. 2790 // 2791 // This happens if there is a prototype for a function (e.g. "int f()") and 2792 // then a definition of a different type (e.g. "int f(int x)"). 2793 if (Entry) { 2794 F->takeName(Entry); 2795 2796 // This might be an implementation of a function without a prototype, in 2797 // which case, try to do special replacement of calls which match the new 2798 // prototype. The really key thing here is that we also potentially drop 2799 // arguments from the call site so as to make a direct call, which makes the 2800 // inliner happier and suppresses a number of optimizer warnings (!) about 2801 // dropping arguments. 2802 if (!Entry->use_empty()) { 2803 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 2804 Entry->removeDeadConstantUsers(); 2805 } 2806 2807 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 2808 F, Entry->getType()->getElementType()->getPointerTo()); 2809 addGlobalValReplacement(Entry, BC); 2810 } 2811 2812 assert(F->getName() == MangledName && "name was uniqued!"); 2813 if (D) 2814 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 2815 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) { 2816 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 2817 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 2818 } 2819 2820 if (!DontDefer) { 2821 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 2822 // each other bottoming out with the base dtor. Therefore we emit non-base 2823 // dtors on usage, even if there is no dtor definition in the TU. 2824 if (D && isa<CXXDestructorDecl>(D) && 2825 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 2826 GD.getDtorType())) 2827 addDeferredDeclToEmit(GD); 2828 2829 // This is the first use or definition of a mangled name. If there is a 2830 // deferred decl with this name, remember that we need to emit it at the end 2831 // of the file. 2832 auto DDI = DeferredDecls.find(MangledName); 2833 if (DDI != DeferredDecls.end()) { 2834 // Move the potentially referenced deferred decl to the 2835 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 2836 // don't need it anymore). 2837 addDeferredDeclToEmit(DDI->second); 2838 DeferredDecls.erase(DDI); 2839 2840 // Otherwise, there are cases we have to worry about where we're 2841 // using a declaration for which we must emit a definition but where 2842 // we might not find a top-level definition: 2843 // - member functions defined inline in their classes 2844 // - friend functions defined inline in some class 2845 // - special member functions with implicit definitions 2846 // If we ever change our AST traversal to walk into class methods, 2847 // this will be unnecessary. 2848 // 2849 // We also don't emit a definition for a function if it's going to be an 2850 // entry in a vtable, unless it's already marked as used. 2851 } else if (getLangOpts().CPlusPlus && D) { 2852 // Look for a declaration that's lexically in a record. 2853 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 2854 FD = FD->getPreviousDecl()) { 2855 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 2856 if (FD->doesThisDeclarationHaveABody()) { 2857 addDeferredDeclToEmit(GD.getWithDecl(FD)); 2858 break; 2859 } 2860 } 2861 } 2862 } 2863 } 2864 2865 // Make sure the result is of the requested type. 2866 if (!IsIncompleteFunction) { 2867 assert(F->getType()->getElementType() == Ty); 2868 return F; 2869 } 2870 2871 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2872 return llvm::ConstantExpr::getBitCast(F, PTy); 2873 } 2874 2875 /// GetAddrOfFunction - Return the address of the given function. If Ty is 2876 /// non-null, then this function will use the specified type if it has to 2877 /// create it (this occurs when we see a definition of the function). 2878 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 2879 llvm::Type *Ty, 2880 bool ForVTable, 2881 bool DontDefer, 2882 ForDefinition_t IsForDefinition) { 2883 // If there was no specific requested type, just convert it now. 2884 if (!Ty) { 2885 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2886 auto CanonTy = Context.getCanonicalType(FD->getType()); 2887 Ty = getTypes().ConvertFunctionType(CanonTy, FD); 2888 } 2889 2890 // Devirtualized destructor calls may come through here instead of via 2891 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 2892 // of the complete destructor when necessary. 2893 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 2894 if (getTarget().getCXXABI().isMicrosoft() && 2895 GD.getDtorType() == Dtor_Complete && 2896 DD->getParent()->getNumVBases() == 0) 2897 GD = GlobalDecl(DD, Dtor_Base); 2898 } 2899 2900 StringRef MangledName = getMangledName(GD); 2901 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 2902 /*IsThunk=*/false, llvm::AttributeList(), 2903 IsForDefinition); 2904 } 2905 2906 static const FunctionDecl * 2907 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 2908 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 2909 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 2910 2911 IdentifierInfo &CII = C.Idents.get(Name); 2912 for (const auto &Result : DC->lookup(&CII)) 2913 if (const auto FD = dyn_cast<FunctionDecl>(Result)) 2914 return FD; 2915 2916 if (!C.getLangOpts().CPlusPlus) 2917 return nullptr; 2918 2919 // Demangle the premangled name from getTerminateFn() 2920 IdentifierInfo &CXXII = 2921 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 2922 ? C.Idents.get("terminate") 2923 : C.Idents.get(Name); 2924 2925 for (const auto &N : {"__cxxabiv1", "std"}) { 2926 IdentifierInfo &NS = C.Idents.get(N); 2927 for (const auto &Result : DC->lookup(&NS)) { 2928 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 2929 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result)) 2930 for (const auto &Result : LSD->lookup(&NS)) 2931 if ((ND = dyn_cast<NamespaceDecl>(Result))) 2932 break; 2933 2934 if (ND) 2935 for (const auto &Result : ND->lookup(&CXXII)) 2936 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 2937 return FD; 2938 } 2939 } 2940 2941 return nullptr; 2942 } 2943 2944 /// CreateRuntimeFunction - Create a new runtime function with the specified 2945 /// type and name. 2946 llvm::Constant * 2947 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 2948 llvm::AttributeList ExtraAttrs, 2949 bool Local) { 2950 llvm::Constant *C = 2951 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 2952 /*DontDefer=*/false, /*IsThunk=*/false, 2953 ExtraAttrs); 2954 2955 if (auto *F = dyn_cast<llvm::Function>(C)) { 2956 if (F->empty()) { 2957 F->setCallingConv(getRuntimeCC()); 2958 2959 if (!Local && getTriple().isOSBinFormatCOFF() && 2960 !getCodeGenOpts().LTOVisibilityPublicStd && 2961 !getTriple().isWindowsGNUEnvironment()) { 2962 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 2963 if (!FD || FD->hasAttr<DLLImportAttr>()) { 2964 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 2965 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 2966 } 2967 } 2968 setDSOLocal(F); 2969 } 2970 } 2971 2972 return C; 2973 } 2974 2975 /// CreateBuiltinFunction - Create a new builtin function with the specified 2976 /// type and name. 2977 llvm::Constant * 2978 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name, 2979 llvm::AttributeList ExtraAttrs) { 2980 return CreateRuntimeFunction(FTy, Name, ExtraAttrs, true); 2981 } 2982 2983 /// isTypeConstant - Determine whether an object of this type can be emitted 2984 /// as a constant. 2985 /// 2986 /// If ExcludeCtor is true, the duration when the object's constructor runs 2987 /// will not be considered. The caller will need to verify that the object is 2988 /// not written to during its construction. 2989 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 2990 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 2991 return false; 2992 2993 if (Context.getLangOpts().CPlusPlus) { 2994 if (const CXXRecordDecl *Record 2995 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 2996 return ExcludeCtor && !Record->hasMutableFields() && 2997 Record->hasTrivialDestructor(); 2998 } 2999 3000 return true; 3001 } 3002 3003 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 3004 /// create and return an llvm GlobalVariable with the specified type. If there 3005 /// is something in the module with the specified name, return it potentially 3006 /// bitcasted to the right type. 3007 /// 3008 /// If D is non-null, it specifies a decl that correspond to this. This is used 3009 /// to set the attributes on the global when it is first created. 3010 /// 3011 /// If IsForDefinition is true, it is guaranteed that an actual global with 3012 /// type Ty will be returned, not conversion of a variable with the same 3013 /// mangled name but some other type. 3014 llvm::Constant * 3015 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 3016 llvm::PointerType *Ty, 3017 const VarDecl *D, 3018 ForDefinition_t IsForDefinition) { 3019 // Lookup the entry, lazily creating it if necessary. 3020 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3021 if (Entry) { 3022 if (WeakRefReferences.erase(Entry)) { 3023 if (D && !D->hasAttr<WeakAttr>()) 3024 Entry->setLinkage(llvm::Function::ExternalLinkage); 3025 } 3026 3027 // Handle dropped DLL attributes. 3028 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 3029 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3030 3031 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 3032 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 3033 3034 if (Entry->getType() == Ty) 3035 return Entry; 3036 3037 // If there are two attempts to define the same mangled name, issue an 3038 // error. 3039 if (IsForDefinition && !Entry->isDeclaration()) { 3040 GlobalDecl OtherGD; 3041 const VarDecl *OtherD; 3042 3043 // Check that D is not yet in DiagnosedConflictingDefinitions is required 3044 // to make sure that we issue an error only once. 3045 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 3046 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 3047 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 3048 OtherD->hasInit() && 3049 DiagnosedConflictingDefinitions.insert(D).second) { 3050 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3051 << MangledName; 3052 getDiags().Report(OtherGD.getDecl()->getLocation(), 3053 diag::note_previous_definition); 3054 } 3055 } 3056 3057 // Make sure the result is of the correct type. 3058 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 3059 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 3060 3061 // (If global is requested for a definition, we always need to create a new 3062 // global, not just return a bitcast.) 3063 if (!IsForDefinition) 3064 return llvm::ConstantExpr::getBitCast(Entry, Ty); 3065 } 3066 3067 auto AddrSpace = GetGlobalVarAddressSpace(D); 3068 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace); 3069 3070 auto *GV = new llvm::GlobalVariable( 3071 getModule(), Ty->getElementType(), false, 3072 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 3073 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace); 3074 3075 // If we already created a global with the same mangled name (but different 3076 // type) before, take its name and remove it from its parent. 3077 if (Entry) { 3078 GV->takeName(Entry); 3079 3080 if (!Entry->use_empty()) { 3081 llvm::Constant *NewPtrForOldDecl = 3082 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 3083 Entry->replaceAllUsesWith(NewPtrForOldDecl); 3084 } 3085 3086 Entry->eraseFromParent(); 3087 } 3088 3089 // This is the first use or definition of a mangled name. If there is a 3090 // deferred decl with this name, remember that we need to emit it at the end 3091 // of the file. 3092 auto DDI = DeferredDecls.find(MangledName); 3093 if (DDI != DeferredDecls.end()) { 3094 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 3095 // list, and remove it from DeferredDecls (since we don't need it anymore). 3096 addDeferredDeclToEmit(DDI->second); 3097 DeferredDecls.erase(DDI); 3098 } 3099 3100 // Handle things which are present even on external declarations. 3101 if (D) { 3102 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 3103 getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 3104 3105 // FIXME: This code is overly simple and should be merged with other global 3106 // handling. 3107 GV->setConstant(isTypeConstant(D->getType(), false)); 3108 3109 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 3110 3111 setLinkageForGV(GV, D); 3112 3113 if (D->getTLSKind()) { 3114 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 3115 CXXThreadLocals.push_back(D); 3116 setTLSMode(GV, *D); 3117 } 3118 3119 setGVProperties(GV, D); 3120 3121 // If required by the ABI, treat declarations of static data members with 3122 // inline initializers as definitions. 3123 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 3124 EmitGlobalVarDefinition(D); 3125 } 3126 3127 // Emit section information for extern variables. 3128 if (D->hasExternalStorage()) { 3129 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 3130 GV->setSection(SA->getName()); 3131 } 3132 3133 // Handle XCore specific ABI requirements. 3134 if (getTriple().getArch() == llvm::Triple::xcore && 3135 D->getLanguageLinkage() == CLanguageLinkage && 3136 D->getType().isConstant(Context) && 3137 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 3138 GV->setSection(".cp.rodata"); 3139 3140 // Check if we a have a const declaration with an initializer, we may be 3141 // able to emit it as available_externally to expose it's value to the 3142 // optimizer. 3143 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 3144 D->getType().isConstQualified() && !GV->hasInitializer() && 3145 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 3146 const auto *Record = 3147 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 3148 bool HasMutableFields = Record && Record->hasMutableFields(); 3149 if (!HasMutableFields) { 3150 const VarDecl *InitDecl; 3151 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 3152 if (InitExpr) { 3153 ConstantEmitter emitter(*this); 3154 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 3155 if (Init) { 3156 auto *InitType = Init->getType(); 3157 if (GV->getType()->getElementType() != InitType) { 3158 // The type of the initializer does not match the definition. 3159 // This happens when an initializer has a different type from 3160 // the type of the global (because of padding at the end of a 3161 // structure for instance). 3162 GV->setName(StringRef()); 3163 // Make a new global with the correct type, this is now guaranteed 3164 // to work. 3165 auto *NewGV = cast<llvm::GlobalVariable>( 3166 GetAddrOfGlobalVar(D, InitType, IsForDefinition)); 3167 3168 // Erase the old global, since it is no longer used. 3169 GV->eraseFromParent(); 3170 GV = NewGV; 3171 } else { 3172 GV->setInitializer(Init); 3173 GV->setConstant(true); 3174 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 3175 } 3176 emitter.finalize(GV); 3177 } 3178 } 3179 } 3180 } 3181 } 3182 3183 LangAS ExpectedAS = 3184 D ? D->getType().getAddressSpace() 3185 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 3186 assert(getContext().getTargetAddressSpace(ExpectedAS) == 3187 Ty->getPointerAddressSpace()); 3188 if (AddrSpace != ExpectedAS) 3189 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace, 3190 ExpectedAS, Ty); 3191 3192 return GV; 3193 } 3194 3195 llvm::Constant * 3196 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 3197 ForDefinition_t IsForDefinition) { 3198 const Decl *D = GD.getDecl(); 3199 if (isa<CXXConstructorDecl>(D)) 3200 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D), 3201 getFromCtorType(GD.getCtorType()), 3202 /*FnInfo=*/nullptr, /*FnType=*/nullptr, 3203 /*DontDefer=*/false, IsForDefinition); 3204 else if (isa<CXXDestructorDecl>(D)) 3205 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D), 3206 getFromDtorType(GD.getDtorType()), 3207 /*FnInfo=*/nullptr, /*FnType=*/nullptr, 3208 /*DontDefer=*/false, IsForDefinition); 3209 else if (isa<CXXMethodDecl>(D)) { 3210 auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 3211 cast<CXXMethodDecl>(D)); 3212 auto Ty = getTypes().GetFunctionType(*FInfo); 3213 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 3214 IsForDefinition); 3215 } else if (isa<FunctionDecl>(D)) { 3216 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3217 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3218 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 3219 IsForDefinition); 3220 } else 3221 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, 3222 IsForDefinition); 3223 } 3224 3225 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 3226 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 3227 unsigned Alignment) { 3228 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 3229 llvm::GlobalVariable *OldGV = nullptr; 3230 3231 if (GV) { 3232 // Check if the variable has the right type. 3233 if (GV->getType()->getElementType() == Ty) 3234 return GV; 3235 3236 // Because C++ name mangling, the only way we can end up with an already 3237 // existing global with the same name is if it has been declared extern "C". 3238 assert(GV->isDeclaration() && "Declaration has wrong type!"); 3239 OldGV = GV; 3240 } 3241 3242 // Create a new variable. 3243 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 3244 Linkage, nullptr, Name); 3245 3246 if (OldGV) { 3247 // Replace occurrences of the old variable if needed. 3248 GV->takeName(OldGV); 3249 3250 if (!OldGV->use_empty()) { 3251 llvm::Constant *NewPtrForOldDecl = 3252 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 3253 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 3254 } 3255 3256 OldGV->eraseFromParent(); 3257 } 3258 3259 if (supportsCOMDAT() && GV->isWeakForLinker() && 3260 !GV->hasAvailableExternallyLinkage()) 3261 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3262 3263 GV->setAlignment(Alignment); 3264 3265 return GV; 3266 } 3267 3268 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 3269 /// given global variable. If Ty is non-null and if the global doesn't exist, 3270 /// then it will be created with the specified type instead of whatever the 3271 /// normal requested type would be. If IsForDefinition is true, it is guaranteed 3272 /// that an actual global with type Ty will be returned, not conversion of a 3273 /// variable with the same mangled name but some other type. 3274 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 3275 llvm::Type *Ty, 3276 ForDefinition_t IsForDefinition) { 3277 assert(D->hasGlobalStorage() && "Not a global variable"); 3278 QualType ASTTy = D->getType(); 3279 if (!Ty) 3280 Ty = getTypes().ConvertTypeForMem(ASTTy); 3281 3282 llvm::PointerType *PTy = 3283 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 3284 3285 StringRef MangledName = getMangledName(D); 3286 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 3287 } 3288 3289 /// CreateRuntimeVariable - Create a new runtime global variable with the 3290 /// specified type and name. 3291 llvm::Constant * 3292 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 3293 StringRef Name) { 3294 auto *Ret = 3295 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 3296 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 3297 return Ret; 3298 } 3299 3300 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 3301 assert(!D->getInit() && "Cannot emit definite definitions here!"); 3302 3303 StringRef MangledName = getMangledName(D); 3304 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 3305 3306 // We already have a definition, not declaration, with the same mangled name. 3307 // Emitting of declaration is not required (and actually overwrites emitted 3308 // definition). 3309 if (GV && !GV->isDeclaration()) 3310 return; 3311 3312 // If we have not seen a reference to this variable yet, place it into the 3313 // deferred declarations table to be emitted if needed later. 3314 if (!MustBeEmitted(D) && !GV) { 3315 DeferredDecls[MangledName] = D; 3316 return; 3317 } 3318 3319 // The tentative definition is the only definition. 3320 EmitGlobalVarDefinition(D); 3321 } 3322 3323 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 3324 return Context.toCharUnitsFromBits( 3325 getDataLayout().getTypeStoreSizeInBits(Ty)); 3326 } 3327 3328 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 3329 LangAS AddrSpace = LangAS::Default; 3330 if (LangOpts.OpenCL) { 3331 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 3332 assert(AddrSpace == LangAS::opencl_global || 3333 AddrSpace == LangAS::opencl_constant || 3334 AddrSpace == LangAS::opencl_local || 3335 AddrSpace >= LangAS::FirstTargetAddressSpace); 3336 return AddrSpace; 3337 } 3338 3339 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 3340 if (D && D->hasAttr<CUDAConstantAttr>()) 3341 return LangAS::cuda_constant; 3342 else if (D && D->hasAttr<CUDASharedAttr>()) 3343 return LangAS::cuda_shared; 3344 else if (D && D->hasAttr<CUDADeviceAttr>()) 3345 return LangAS::cuda_device; 3346 else if (D && D->getType().isConstQualified()) 3347 return LangAS::cuda_constant; 3348 else 3349 return LangAS::cuda_device; 3350 } 3351 3352 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 3353 } 3354 3355 LangAS CodeGenModule::getStringLiteralAddressSpace() const { 3356 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 3357 if (LangOpts.OpenCL) 3358 return LangAS::opencl_constant; 3359 if (auto AS = getTarget().getConstantAddressSpace()) 3360 return AS.getValue(); 3361 return LangAS::Default; 3362 } 3363 3364 // In address space agnostic languages, string literals are in default address 3365 // space in AST. However, certain targets (e.g. amdgcn) request them to be 3366 // emitted in constant address space in LLVM IR. To be consistent with other 3367 // parts of AST, string literal global variables in constant address space 3368 // need to be casted to default address space before being put into address 3369 // map and referenced by other part of CodeGen. 3370 // In OpenCL, string literals are in constant address space in AST, therefore 3371 // they should not be casted to default address space. 3372 static llvm::Constant * 3373 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 3374 llvm::GlobalVariable *GV) { 3375 llvm::Constant *Cast = GV; 3376 if (!CGM.getLangOpts().OpenCL) { 3377 if (auto AS = CGM.getTarget().getConstantAddressSpace()) { 3378 if (AS != LangAS::Default) 3379 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 3380 CGM, GV, AS.getValue(), LangAS::Default, 3381 GV->getValueType()->getPointerTo( 3382 CGM.getContext().getTargetAddressSpace(LangAS::Default))); 3383 } 3384 } 3385 return Cast; 3386 } 3387 3388 template<typename SomeDecl> 3389 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 3390 llvm::GlobalValue *GV) { 3391 if (!getLangOpts().CPlusPlus) 3392 return; 3393 3394 // Must have 'used' attribute, or else inline assembly can't rely on 3395 // the name existing. 3396 if (!D->template hasAttr<UsedAttr>()) 3397 return; 3398 3399 // Must have internal linkage and an ordinary name. 3400 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 3401 return; 3402 3403 // Must be in an extern "C" context. Entities declared directly within 3404 // a record are not extern "C" even if the record is in such a context. 3405 const SomeDecl *First = D->getFirstDecl(); 3406 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 3407 return; 3408 3409 // OK, this is an internal linkage entity inside an extern "C" linkage 3410 // specification. Make a note of that so we can give it the "expected" 3411 // mangled name if nothing else is using that name. 3412 std::pair<StaticExternCMap::iterator, bool> R = 3413 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 3414 3415 // If we have multiple internal linkage entities with the same name 3416 // in extern "C" regions, none of them gets that name. 3417 if (!R.second) 3418 R.first->second = nullptr; 3419 } 3420 3421 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 3422 if (!CGM.supportsCOMDAT()) 3423 return false; 3424 3425 if (D.hasAttr<SelectAnyAttr>()) 3426 return true; 3427 3428 GVALinkage Linkage; 3429 if (auto *VD = dyn_cast<VarDecl>(&D)) 3430 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 3431 else 3432 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 3433 3434 switch (Linkage) { 3435 case GVA_Internal: 3436 case GVA_AvailableExternally: 3437 case GVA_StrongExternal: 3438 return false; 3439 case GVA_DiscardableODR: 3440 case GVA_StrongODR: 3441 return true; 3442 } 3443 llvm_unreachable("No such linkage"); 3444 } 3445 3446 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 3447 llvm::GlobalObject &GO) { 3448 if (!shouldBeInCOMDAT(*this, D)) 3449 return; 3450 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 3451 } 3452 3453 /// Pass IsTentative as true if you want to create a tentative definition. 3454 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 3455 bool IsTentative) { 3456 // OpenCL global variables of sampler type are translated to function calls, 3457 // therefore no need to be translated. 3458 QualType ASTTy = D->getType(); 3459 if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 3460 return; 3461 3462 // If this is OpenMP device, check if it is legal to emit this global 3463 // normally. 3464 if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 3465 OpenMPRuntime->emitTargetGlobalVariable(D)) 3466 return; 3467 3468 llvm::Constant *Init = nullptr; 3469 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3470 bool NeedsGlobalCtor = false; 3471 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 3472 3473 const VarDecl *InitDecl; 3474 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 3475 3476 Optional<ConstantEmitter> emitter; 3477 3478 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 3479 // as part of their declaration." Sema has already checked for 3480 // error cases, so we just need to set Init to UndefValue. 3481 bool IsCUDASharedVar = 3482 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 3483 // Shadows of initialized device-side global variables are also left 3484 // undefined. 3485 bool IsCUDAShadowVar = 3486 !getLangOpts().CUDAIsDevice && 3487 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 3488 D->hasAttr<CUDASharedAttr>()); 3489 if (getLangOpts().CUDA && (IsCUDASharedVar || IsCUDAShadowVar)) 3490 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 3491 else if (!InitExpr) { 3492 // This is a tentative definition; tentative definitions are 3493 // implicitly initialized with { 0 }. 3494 // 3495 // Note that tentative definitions are only emitted at the end of 3496 // a translation unit, so they should never have incomplete 3497 // type. In addition, EmitTentativeDefinition makes sure that we 3498 // never attempt to emit a tentative definition if a real one 3499 // exists. A use may still exists, however, so we still may need 3500 // to do a RAUW. 3501 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 3502 Init = EmitNullConstant(D->getType()); 3503 } else { 3504 initializedGlobalDecl = GlobalDecl(D); 3505 emitter.emplace(*this); 3506 Init = emitter->tryEmitForInitializer(*InitDecl); 3507 3508 if (!Init) { 3509 QualType T = InitExpr->getType(); 3510 if (D->getType()->isReferenceType()) 3511 T = D->getType(); 3512 3513 if (getLangOpts().CPlusPlus) { 3514 Init = EmitNullConstant(T); 3515 NeedsGlobalCtor = true; 3516 } else { 3517 ErrorUnsupported(D, "static initializer"); 3518 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 3519 } 3520 } else { 3521 // We don't need an initializer, so remove the entry for the delayed 3522 // initializer position (just in case this entry was delayed) if we 3523 // also don't need to register a destructor. 3524 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 3525 DelayedCXXInitPosition.erase(D); 3526 } 3527 } 3528 3529 llvm::Type* InitType = Init->getType(); 3530 llvm::Constant *Entry = 3531 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 3532 3533 // Strip off a bitcast if we got one back. 3534 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 3535 assert(CE->getOpcode() == llvm::Instruction::BitCast || 3536 CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 3537 // All zero index gep. 3538 CE->getOpcode() == llvm::Instruction::GetElementPtr); 3539 Entry = CE->getOperand(0); 3540 } 3541 3542 // Entry is now either a Function or GlobalVariable. 3543 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 3544 3545 // We have a definition after a declaration with the wrong type. 3546 // We must make a new GlobalVariable* and update everything that used OldGV 3547 // (a declaration or tentative definition) with the new GlobalVariable* 3548 // (which will be a definition). 3549 // 3550 // This happens if there is a prototype for a global (e.g. 3551 // "extern int x[];") and then a definition of a different type (e.g. 3552 // "int x[10];"). This also happens when an initializer has a different type 3553 // from the type of the global (this happens with unions). 3554 if (!GV || GV->getType()->getElementType() != InitType || 3555 GV->getType()->getAddressSpace() != 3556 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 3557 3558 // Move the old entry aside so that we'll create a new one. 3559 Entry->setName(StringRef()); 3560 3561 // Make a new global with the correct type, this is now guaranteed to work. 3562 GV = cast<llvm::GlobalVariable>( 3563 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))); 3564 3565 // Replace all uses of the old global with the new global 3566 llvm::Constant *NewPtrForOldDecl = 3567 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 3568 Entry->replaceAllUsesWith(NewPtrForOldDecl); 3569 3570 // Erase the old global, since it is no longer used. 3571 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 3572 } 3573 3574 MaybeHandleStaticInExternC(D, GV); 3575 3576 if (D->hasAttr<AnnotateAttr>()) 3577 AddGlobalAnnotations(D, GV); 3578 3579 // Set the llvm linkage type as appropriate. 3580 llvm::GlobalValue::LinkageTypes Linkage = 3581 getLLVMLinkageVarDefinition(D, GV->isConstant()); 3582 3583 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 3584 // the device. [...]" 3585 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 3586 // __device__, declares a variable that: [...] 3587 // Is accessible from all the threads within the grid and from the host 3588 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 3589 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 3590 if (GV && LangOpts.CUDA) { 3591 if (LangOpts.CUDAIsDevice) { 3592 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) 3593 GV->setExternallyInitialized(true); 3594 } else { 3595 // Host-side shadows of external declarations of device-side 3596 // global variables become internal definitions. These have to 3597 // be internal in order to prevent name conflicts with global 3598 // host variables with the same name in a different TUs. 3599 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) { 3600 Linkage = llvm::GlobalValue::InternalLinkage; 3601 3602 // Shadow variables and their properties must be registered 3603 // with CUDA runtime. 3604 unsigned Flags = 0; 3605 if (!D->hasDefinition()) 3606 Flags |= CGCUDARuntime::ExternDeviceVar; 3607 if (D->hasAttr<CUDAConstantAttr>()) 3608 Flags |= CGCUDARuntime::ConstantDeviceVar; 3609 // Extern global variables will be registered in the TU where they are 3610 // defined. 3611 if (!D->hasExternalStorage()) 3612 getCUDARuntime().registerDeviceVar(*GV, Flags); 3613 } else if (D->hasAttr<CUDASharedAttr>()) 3614 // __shared__ variables are odd. Shadows do get created, but 3615 // they are not registered with the CUDA runtime, so they 3616 // can't really be used to access their device-side 3617 // counterparts. It's not clear yet whether it's nvcc's bug or 3618 // a feature, but we've got to do the same for compatibility. 3619 Linkage = llvm::GlobalValue::InternalLinkage; 3620 } 3621 } 3622 3623 GV->setInitializer(Init); 3624 if (emitter) emitter->finalize(GV); 3625 3626 // If it is safe to mark the global 'constant', do so now. 3627 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 3628 isTypeConstant(D->getType(), true)); 3629 3630 // If it is in a read-only section, mark it 'constant'. 3631 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 3632 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 3633 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 3634 GV->setConstant(true); 3635 } 3636 3637 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 3638 3639 3640 // On Darwin, if the normal linkage of a C++ thread_local variable is 3641 // LinkOnce or Weak, we keep the normal linkage to prevent multiple 3642 // copies within a linkage unit; otherwise, the backing variable has 3643 // internal linkage and all accesses should just be calls to the 3644 // Itanium-specified entry point, which has the normal linkage of the 3645 // variable. This is to preserve the ability to change the implementation 3646 // behind the scenes. 3647 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 3648 Context.getTargetInfo().getTriple().isOSDarwin() && 3649 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 3650 !llvm::GlobalVariable::isWeakLinkage(Linkage)) 3651 Linkage = llvm::GlobalValue::InternalLinkage; 3652 3653 GV->setLinkage(Linkage); 3654 if (D->hasAttr<DLLImportAttr>()) 3655 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 3656 else if (D->hasAttr<DLLExportAttr>()) 3657 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 3658 else 3659 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 3660 3661 if (Linkage == llvm::GlobalVariable::CommonLinkage) { 3662 // common vars aren't constant even if declared const. 3663 GV->setConstant(false); 3664 // Tentative definition of global variables may be initialized with 3665 // non-zero null pointers. In this case they should have weak linkage 3666 // since common linkage must have zero initializer and must not have 3667 // explicit section therefore cannot have non-zero initial value. 3668 if (!GV->getInitializer()->isNullValue()) 3669 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 3670 } 3671 3672 setNonAliasAttributes(D, GV); 3673 3674 if (D->getTLSKind() && !GV->isThreadLocal()) { 3675 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 3676 CXXThreadLocals.push_back(D); 3677 setTLSMode(GV, *D); 3678 } 3679 3680 maybeSetTrivialComdat(*D, *GV); 3681 3682 // Emit the initializer function if necessary. 3683 if (NeedsGlobalCtor || NeedsGlobalDtor) 3684 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 3685 3686 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 3687 3688 // Emit global variable debug information. 3689 if (CGDebugInfo *DI = getModuleDebugInfo()) 3690 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 3691 DI->EmitGlobalVariable(GV, D); 3692 } 3693 3694 static bool isVarDeclStrongDefinition(const ASTContext &Context, 3695 CodeGenModule &CGM, const VarDecl *D, 3696 bool NoCommon) { 3697 // Don't give variables common linkage if -fno-common was specified unless it 3698 // was overridden by a NoCommon attribute. 3699 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 3700 return true; 3701 3702 // C11 6.9.2/2: 3703 // A declaration of an identifier for an object that has file scope without 3704 // an initializer, and without a storage-class specifier or with the 3705 // storage-class specifier static, constitutes a tentative definition. 3706 if (D->getInit() || D->hasExternalStorage()) 3707 return true; 3708 3709 // A variable cannot be both common and exist in a section. 3710 if (D->hasAttr<SectionAttr>()) 3711 return true; 3712 3713 // A variable cannot be both common and exist in a section. 3714 // We don't try to determine which is the right section in the front-end. 3715 // If no specialized section name is applicable, it will resort to default. 3716 if (D->hasAttr<PragmaClangBSSSectionAttr>() || 3717 D->hasAttr<PragmaClangDataSectionAttr>() || 3718 D->hasAttr<PragmaClangRodataSectionAttr>()) 3719 return true; 3720 3721 // Thread local vars aren't considered common linkage. 3722 if (D->getTLSKind()) 3723 return true; 3724 3725 // Tentative definitions marked with WeakImportAttr are true definitions. 3726 if (D->hasAttr<WeakImportAttr>()) 3727 return true; 3728 3729 // A variable cannot be both common and exist in a comdat. 3730 if (shouldBeInCOMDAT(CGM, *D)) 3731 return true; 3732 3733 // Declarations with a required alignment do not have common linkage in MSVC 3734 // mode. 3735 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 3736 if (D->hasAttr<AlignedAttr>()) 3737 return true; 3738 QualType VarType = D->getType(); 3739 if (Context.isAlignmentRequired(VarType)) 3740 return true; 3741 3742 if (const auto *RT = VarType->getAs<RecordType>()) { 3743 const RecordDecl *RD = RT->getDecl(); 3744 for (const FieldDecl *FD : RD->fields()) { 3745 if (FD->isBitField()) 3746 continue; 3747 if (FD->hasAttr<AlignedAttr>()) 3748 return true; 3749 if (Context.isAlignmentRequired(FD->getType())) 3750 return true; 3751 } 3752 } 3753 } 3754 3755 return false; 3756 } 3757 3758 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 3759 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 3760 if (Linkage == GVA_Internal) 3761 return llvm::Function::InternalLinkage; 3762 3763 if (D->hasAttr<WeakAttr>()) { 3764 if (IsConstantVariable) 3765 return llvm::GlobalVariable::WeakODRLinkage; 3766 else 3767 return llvm::GlobalVariable::WeakAnyLinkage; 3768 } 3769 3770 if (const auto *FD = D->getAsFunction()) 3771 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 3772 return llvm::GlobalVariable::LinkOnceAnyLinkage; 3773 3774 // We are guaranteed to have a strong definition somewhere else, 3775 // so we can use available_externally linkage. 3776 if (Linkage == GVA_AvailableExternally) 3777 return llvm::GlobalValue::AvailableExternallyLinkage; 3778 3779 // Note that Apple's kernel linker doesn't support symbol 3780 // coalescing, so we need to avoid linkonce and weak linkages there. 3781 // Normally, this means we just map to internal, but for explicit 3782 // instantiations we'll map to external. 3783 3784 // In C++, the compiler has to emit a definition in every translation unit 3785 // that references the function. We should use linkonce_odr because 3786 // a) if all references in this translation unit are optimized away, we 3787 // don't need to codegen it. b) if the function persists, it needs to be 3788 // merged with other definitions. c) C++ has the ODR, so we know the 3789 // definition is dependable. 3790 if (Linkage == GVA_DiscardableODR) 3791 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 3792 : llvm::Function::InternalLinkage; 3793 3794 // An explicit instantiation of a template has weak linkage, since 3795 // explicit instantiations can occur in multiple translation units 3796 // and must all be equivalent. However, we are not allowed to 3797 // throw away these explicit instantiations. 3798 // 3799 // We don't currently support CUDA device code spread out across multiple TUs, 3800 // so say that CUDA templates are either external (for kernels) or internal. 3801 // This lets llvm perform aggressive inter-procedural optimizations. 3802 if (Linkage == GVA_StrongODR) { 3803 if (Context.getLangOpts().AppleKext) 3804 return llvm::Function::ExternalLinkage; 3805 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) 3806 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 3807 : llvm::Function::InternalLinkage; 3808 return llvm::Function::WeakODRLinkage; 3809 } 3810 3811 // C++ doesn't have tentative definitions and thus cannot have common 3812 // linkage. 3813 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 3814 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 3815 CodeGenOpts.NoCommon)) 3816 return llvm::GlobalVariable::CommonLinkage; 3817 3818 // selectany symbols are externally visible, so use weak instead of 3819 // linkonce. MSVC optimizes away references to const selectany globals, so 3820 // all definitions should be the same and ODR linkage should be used. 3821 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 3822 if (D->hasAttr<SelectAnyAttr>()) 3823 return llvm::GlobalVariable::WeakODRLinkage; 3824 3825 // Otherwise, we have strong external linkage. 3826 assert(Linkage == GVA_StrongExternal); 3827 return llvm::GlobalVariable::ExternalLinkage; 3828 } 3829 3830 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 3831 const VarDecl *VD, bool IsConstant) { 3832 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 3833 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 3834 } 3835 3836 /// Replace the uses of a function that was declared with a non-proto type. 3837 /// We want to silently drop extra arguments from call sites 3838 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 3839 llvm::Function *newFn) { 3840 // Fast path. 3841 if (old->use_empty()) return; 3842 3843 llvm::Type *newRetTy = newFn->getReturnType(); 3844 SmallVector<llvm::Value*, 4> newArgs; 3845 SmallVector<llvm::OperandBundleDef, 1> newBundles; 3846 3847 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 3848 ui != ue; ) { 3849 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 3850 llvm::User *user = use->getUser(); 3851 3852 // Recognize and replace uses of bitcasts. Most calls to 3853 // unprototyped functions will use bitcasts. 3854 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 3855 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 3856 replaceUsesOfNonProtoConstant(bitcast, newFn); 3857 continue; 3858 } 3859 3860 // Recognize calls to the function. 3861 llvm::CallSite callSite(user); 3862 if (!callSite) continue; 3863 if (!callSite.isCallee(&*use)) continue; 3864 3865 // If the return types don't match exactly, then we can't 3866 // transform this call unless it's dead. 3867 if (callSite->getType() != newRetTy && !callSite->use_empty()) 3868 continue; 3869 3870 // Get the call site's attribute list. 3871 SmallVector<llvm::AttributeSet, 8> newArgAttrs; 3872 llvm::AttributeList oldAttrs = callSite.getAttributes(); 3873 3874 // If the function was passed too few arguments, don't transform. 3875 unsigned newNumArgs = newFn->arg_size(); 3876 if (callSite.arg_size() < newNumArgs) continue; 3877 3878 // If extra arguments were passed, we silently drop them. 3879 // If any of the types mismatch, we don't transform. 3880 unsigned argNo = 0; 3881 bool dontTransform = false; 3882 for (llvm::Argument &A : newFn->args()) { 3883 if (callSite.getArgument(argNo)->getType() != A.getType()) { 3884 dontTransform = true; 3885 break; 3886 } 3887 3888 // Add any parameter attributes. 3889 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo)); 3890 argNo++; 3891 } 3892 if (dontTransform) 3893 continue; 3894 3895 // Okay, we can transform this. Create the new call instruction and copy 3896 // over the required information. 3897 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 3898 3899 // Copy over any operand bundles. 3900 callSite.getOperandBundlesAsDefs(newBundles); 3901 3902 llvm::CallSite newCall; 3903 if (callSite.isCall()) { 3904 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 3905 callSite.getInstruction()); 3906 } else { 3907 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 3908 newCall = llvm::InvokeInst::Create(newFn, 3909 oldInvoke->getNormalDest(), 3910 oldInvoke->getUnwindDest(), 3911 newArgs, newBundles, "", 3912 callSite.getInstruction()); 3913 } 3914 newArgs.clear(); // for the next iteration 3915 3916 if (!newCall->getType()->isVoidTy()) 3917 newCall->takeName(callSite.getInstruction()); 3918 newCall.setAttributes(llvm::AttributeList::get( 3919 newFn->getContext(), oldAttrs.getFnAttributes(), 3920 oldAttrs.getRetAttributes(), newArgAttrs)); 3921 newCall.setCallingConv(callSite.getCallingConv()); 3922 3923 // Finally, remove the old call, replacing any uses with the new one. 3924 if (!callSite->use_empty()) 3925 callSite->replaceAllUsesWith(newCall.getInstruction()); 3926 3927 // Copy debug location attached to CI. 3928 if (callSite->getDebugLoc()) 3929 newCall->setDebugLoc(callSite->getDebugLoc()); 3930 3931 callSite->eraseFromParent(); 3932 } 3933 } 3934 3935 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 3936 /// implement a function with no prototype, e.g. "int foo() {}". If there are 3937 /// existing call uses of the old function in the module, this adjusts them to 3938 /// call the new function directly. 3939 /// 3940 /// This is not just a cleanup: the always_inline pass requires direct calls to 3941 /// functions to be able to inline them. If there is a bitcast in the way, it 3942 /// won't inline them. Instcombine normally deletes these calls, but it isn't 3943 /// run at -O0. 3944 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3945 llvm::Function *NewFn) { 3946 // If we're redefining a global as a function, don't transform it. 3947 if (!isa<llvm::Function>(Old)) return; 3948 3949 replaceUsesOfNonProtoConstant(Old, NewFn); 3950 } 3951 3952 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 3953 auto DK = VD->isThisDeclarationADefinition(); 3954 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 3955 return; 3956 3957 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 3958 // If we have a definition, this might be a deferred decl. If the 3959 // instantiation is explicit, make sure we emit it at the end. 3960 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 3961 GetAddrOfGlobalVar(VD); 3962 3963 EmitTopLevelDecl(VD); 3964 } 3965 3966 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 3967 llvm::GlobalValue *GV) { 3968 const auto *D = cast<FunctionDecl>(GD.getDecl()); 3969 3970 // Compute the function info and LLVM type. 3971 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3972 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3973 3974 // Get or create the prototype for the function. 3975 if (!GV || (GV->getType()->getElementType() != Ty)) 3976 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 3977 /*DontDefer=*/true, 3978 ForDefinition)); 3979 3980 // Already emitted. 3981 if (!GV->isDeclaration()) 3982 return; 3983 3984 // We need to set linkage and visibility on the function before 3985 // generating code for it because various parts of IR generation 3986 // want to propagate this information down (e.g. to local static 3987 // declarations). 3988 auto *Fn = cast<llvm::Function>(GV); 3989 setFunctionLinkage(GD, Fn); 3990 3991 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 3992 setGVProperties(Fn, GD); 3993 3994 MaybeHandleStaticInExternC(D, Fn); 3995 3996 3997 maybeSetTrivialComdat(*D, *Fn); 3998 3999 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 4000 4001 setNonAliasAttributes(GD, Fn); 4002 SetLLVMFunctionAttributesForDefinition(D, Fn); 4003 4004 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 4005 AddGlobalCtor(Fn, CA->getPriority()); 4006 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 4007 AddGlobalDtor(Fn, DA->getPriority()); 4008 if (D->hasAttr<AnnotateAttr>()) 4009 AddGlobalAnnotations(D, Fn); 4010 } 4011 4012 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 4013 const auto *D = cast<ValueDecl>(GD.getDecl()); 4014 const AliasAttr *AA = D->getAttr<AliasAttr>(); 4015 assert(AA && "Not an alias?"); 4016 4017 StringRef MangledName = getMangledName(GD); 4018 4019 if (AA->getAliasee() == MangledName) { 4020 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 4021 return; 4022 } 4023 4024 // If there is a definition in the module, then it wins over the alias. 4025 // This is dubious, but allow it to be safe. Just ignore the alias. 4026 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4027 if (Entry && !Entry->isDeclaration()) 4028 return; 4029 4030 Aliases.push_back(GD); 4031 4032 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 4033 4034 // Create a reference to the named value. This ensures that it is emitted 4035 // if a deferred decl. 4036 llvm::Constant *Aliasee; 4037 if (isa<llvm::FunctionType>(DeclTy)) 4038 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 4039 /*ForVTable=*/false); 4040 else 4041 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 4042 llvm::PointerType::getUnqual(DeclTy), 4043 /*D=*/nullptr); 4044 4045 // Create the new alias itself, but don't set a name yet. 4046 auto *GA = llvm::GlobalAlias::create( 4047 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 4048 4049 if (Entry) { 4050 if (GA->getAliasee() == Entry) { 4051 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 4052 return; 4053 } 4054 4055 assert(Entry->isDeclaration()); 4056 4057 // If there is a declaration in the module, then we had an extern followed 4058 // by the alias, as in: 4059 // extern int test6(); 4060 // ... 4061 // int test6() __attribute__((alias("test7"))); 4062 // 4063 // Remove it and replace uses of it with the alias. 4064 GA->takeName(Entry); 4065 4066 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 4067 Entry->getType())); 4068 Entry->eraseFromParent(); 4069 } else { 4070 GA->setName(MangledName); 4071 } 4072 4073 // Set attributes which are particular to an alias; this is a 4074 // specialization of the attributes which may be set on a global 4075 // variable/function. 4076 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 4077 D->isWeakImported()) { 4078 GA->setLinkage(llvm::Function::WeakAnyLinkage); 4079 } 4080 4081 if (const auto *VD = dyn_cast<VarDecl>(D)) 4082 if (VD->getTLSKind()) 4083 setTLSMode(GA, *VD); 4084 4085 SetCommonAttributes(GD, GA); 4086 } 4087 4088 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 4089 const auto *D = cast<ValueDecl>(GD.getDecl()); 4090 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 4091 assert(IFA && "Not an ifunc?"); 4092 4093 StringRef MangledName = getMangledName(GD); 4094 4095 if (IFA->getResolver() == MangledName) { 4096 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 4097 return; 4098 } 4099 4100 // Report an error if some definition overrides ifunc. 4101 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4102 if (Entry && !Entry->isDeclaration()) { 4103 GlobalDecl OtherGD; 4104 if (lookupRepresentativeDecl(MangledName, OtherGD) && 4105 DiagnosedConflictingDefinitions.insert(GD).second) { 4106 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 4107 << MangledName; 4108 Diags.Report(OtherGD.getDecl()->getLocation(), 4109 diag::note_previous_definition); 4110 } 4111 return; 4112 } 4113 4114 Aliases.push_back(GD); 4115 4116 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 4117 llvm::Constant *Resolver = 4118 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 4119 /*ForVTable=*/false); 4120 llvm::GlobalIFunc *GIF = 4121 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 4122 "", Resolver, &getModule()); 4123 if (Entry) { 4124 if (GIF->getResolver() == Entry) { 4125 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 4126 return; 4127 } 4128 assert(Entry->isDeclaration()); 4129 4130 // If there is a declaration in the module, then we had an extern followed 4131 // by the ifunc, as in: 4132 // extern int test(); 4133 // ... 4134 // int test() __attribute__((ifunc("resolver"))); 4135 // 4136 // Remove it and replace uses of it with the ifunc. 4137 GIF->takeName(Entry); 4138 4139 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 4140 Entry->getType())); 4141 Entry->eraseFromParent(); 4142 } else 4143 GIF->setName(MangledName); 4144 4145 SetCommonAttributes(GD, GIF); 4146 } 4147 4148 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 4149 ArrayRef<llvm::Type*> Tys) { 4150 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 4151 Tys); 4152 } 4153 4154 static llvm::StringMapEntry<llvm::GlobalVariable *> & 4155 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 4156 const StringLiteral *Literal, bool TargetIsLSB, 4157 bool &IsUTF16, unsigned &StringLength) { 4158 StringRef String = Literal->getString(); 4159 unsigned NumBytes = String.size(); 4160 4161 // Check for simple case. 4162 if (!Literal->containsNonAsciiOrNull()) { 4163 StringLength = NumBytes; 4164 return *Map.insert(std::make_pair(String, nullptr)).first; 4165 } 4166 4167 // Otherwise, convert the UTF8 literals into a string of shorts. 4168 IsUTF16 = true; 4169 4170 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 4171 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 4172 llvm::UTF16 *ToPtr = &ToBuf[0]; 4173 4174 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 4175 ToPtr + NumBytes, llvm::strictConversion); 4176 4177 // ConvertUTF8toUTF16 returns the length in ToPtr. 4178 StringLength = ToPtr - &ToBuf[0]; 4179 4180 // Add an explicit null. 4181 *ToPtr = 0; 4182 return *Map.insert(std::make_pair( 4183 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 4184 (StringLength + 1) * 2), 4185 nullptr)).first; 4186 } 4187 4188 ConstantAddress 4189 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 4190 unsigned StringLength = 0; 4191 bool isUTF16 = false; 4192 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 4193 GetConstantCFStringEntry(CFConstantStringMap, Literal, 4194 getDataLayout().isLittleEndian(), isUTF16, 4195 StringLength); 4196 4197 if (auto *C = Entry.second) 4198 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 4199 4200 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 4201 llvm::Constant *Zeros[] = { Zero, Zero }; 4202 4203 const ASTContext &Context = getContext(); 4204 const llvm::Triple &Triple = getTriple(); 4205 4206 const auto CFRuntime = getLangOpts().CFRuntime; 4207 const bool IsSwiftABI = 4208 static_cast<unsigned>(CFRuntime) >= 4209 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 4210 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 4211 4212 // If we don't already have it, get __CFConstantStringClassReference. 4213 if (!CFConstantStringClassRef) { 4214 const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 4215 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 4216 Ty = llvm::ArrayType::get(Ty, 0); 4217 4218 switch (CFRuntime) { 4219 default: break; 4220 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH; 4221 case LangOptions::CoreFoundationABI::Swift5_0: 4222 CFConstantStringClassName = 4223 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 4224 : "$s10Foundation19_NSCFConstantStringCN"; 4225 Ty = IntPtrTy; 4226 break; 4227 case LangOptions::CoreFoundationABI::Swift4_2: 4228 CFConstantStringClassName = 4229 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 4230 : "$S10Foundation19_NSCFConstantStringCN"; 4231 Ty = IntPtrTy; 4232 break; 4233 case LangOptions::CoreFoundationABI::Swift4_1: 4234 CFConstantStringClassName = 4235 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 4236 : "__T010Foundation19_NSCFConstantStringCN"; 4237 Ty = IntPtrTy; 4238 break; 4239 } 4240 4241 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 4242 4243 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 4244 llvm::GlobalValue *GV = nullptr; 4245 4246 if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 4247 IdentifierInfo &II = Context.Idents.get(GV->getName()); 4248 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 4249 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 4250 4251 const VarDecl *VD = nullptr; 4252 for (const auto &Result : DC->lookup(&II)) 4253 if ((VD = dyn_cast<VarDecl>(Result))) 4254 break; 4255 4256 if (Triple.isOSBinFormatELF()) { 4257 if (!VD) 4258 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 4259 } else { 4260 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 4261 if (!VD || !VD->hasAttr<DLLExportAttr>()) 4262 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 4263 else 4264 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 4265 } 4266 4267 setDSOLocal(GV); 4268 } 4269 } 4270 4271 // Decay array -> ptr 4272 CFConstantStringClassRef = 4273 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 4274 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 4275 } 4276 4277 QualType CFTy = Context.getCFConstantStringType(); 4278 4279 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 4280 4281 ConstantInitBuilder Builder(*this); 4282 auto Fields = Builder.beginStruct(STy); 4283 4284 // Class pointer. 4285 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 4286 4287 // Flags. 4288 if (IsSwiftABI) { 4289 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 4290 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 4291 } else { 4292 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 4293 } 4294 4295 // String pointer. 4296 llvm::Constant *C = nullptr; 4297 if (isUTF16) { 4298 auto Arr = llvm::makeArrayRef( 4299 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 4300 Entry.first().size() / 2); 4301 C = llvm::ConstantDataArray::get(VMContext, Arr); 4302 } else { 4303 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 4304 } 4305 4306 // Note: -fwritable-strings doesn't make the backing store strings of 4307 // CFStrings writable. (See <rdar://problem/10657500>) 4308 auto *GV = 4309 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 4310 llvm::GlobalValue::PrivateLinkage, C, ".str"); 4311 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 4312 // Don't enforce the target's minimum global alignment, since the only use 4313 // of the string is via this class initializer. 4314 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 4315 : Context.getTypeAlignInChars(Context.CharTy); 4316 GV->setAlignment(Align.getQuantity()); 4317 4318 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 4319 // Without it LLVM can merge the string with a non unnamed_addr one during 4320 // LTO. Doing that changes the section it ends in, which surprises ld64. 4321 if (Triple.isOSBinFormatMachO()) 4322 GV->setSection(isUTF16 ? "__TEXT,__ustring" 4323 : "__TEXT,__cstring,cstring_literals"); 4324 // Make sure the literal ends up in .rodata to allow for safe ICF and for 4325 // the static linker to adjust permissions to read-only later on. 4326 else if (Triple.isOSBinFormatELF()) 4327 GV->setSection(".rodata"); 4328 4329 // String. 4330 llvm::Constant *Str = 4331 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 4332 4333 if (isUTF16) 4334 // Cast the UTF16 string to the correct type. 4335 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 4336 Fields.add(Str); 4337 4338 // String length. 4339 llvm::IntegerType *LengthTy = 4340 llvm::IntegerType::get(getModule().getContext(), 4341 Context.getTargetInfo().getLongWidth()); 4342 if (IsSwiftABI) { 4343 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 4344 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 4345 LengthTy = Int32Ty; 4346 else 4347 LengthTy = IntPtrTy; 4348 } 4349 Fields.addInt(LengthTy, StringLength); 4350 4351 CharUnits Alignment = getPointerAlign(); 4352 4353 // The struct. 4354 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 4355 /*isConstant=*/false, 4356 llvm::GlobalVariable::PrivateLinkage); 4357 switch (Triple.getObjectFormat()) { 4358 case llvm::Triple::UnknownObjectFormat: 4359 llvm_unreachable("unknown file format"); 4360 case llvm::Triple::COFF: 4361 case llvm::Triple::ELF: 4362 case llvm::Triple::Wasm: 4363 GV->setSection("cfstring"); 4364 break; 4365 case llvm::Triple::MachO: 4366 GV->setSection("__DATA,__cfstring"); 4367 break; 4368 } 4369 Entry.second = GV; 4370 4371 return ConstantAddress(GV, Alignment); 4372 } 4373 4374 bool CodeGenModule::getExpressionLocationsEnabled() const { 4375 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 4376 } 4377 4378 QualType CodeGenModule::getObjCFastEnumerationStateType() { 4379 if (ObjCFastEnumerationStateType.isNull()) { 4380 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 4381 D->startDefinition(); 4382 4383 QualType FieldTypes[] = { 4384 Context.UnsignedLongTy, 4385 Context.getPointerType(Context.getObjCIdType()), 4386 Context.getPointerType(Context.UnsignedLongTy), 4387 Context.getConstantArrayType(Context.UnsignedLongTy, 4388 llvm::APInt(32, 5), ArrayType::Normal, 0) 4389 }; 4390 4391 for (size_t i = 0; i < 4; ++i) { 4392 FieldDecl *Field = FieldDecl::Create(Context, 4393 D, 4394 SourceLocation(), 4395 SourceLocation(), nullptr, 4396 FieldTypes[i], /*TInfo=*/nullptr, 4397 /*BitWidth=*/nullptr, 4398 /*Mutable=*/false, 4399 ICIS_NoInit); 4400 Field->setAccess(AS_public); 4401 D->addDecl(Field); 4402 } 4403 4404 D->completeDefinition(); 4405 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 4406 } 4407 4408 return ObjCFastEnumerationStateType; 4409 } 4410 4411 llvm::Constant * 4412 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 4413 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 4414 4415 // Don't emit it as the address of the string, emit the string data itself 4416 // as an inline array. 4417 if (E->getCharByteWidth() == 1) { 4418 SmallString<64> Str(E->getString()); 4419 4420 // Resize the string to the right size, which is indicated by its type. 4421 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 4422 Str.resize(CAT->getSize().getZExtValue()); 4423 return llvm::ConstantDataArray::getString(VMContext, Str, false); 4424 } 4425 4426 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 4427 llvm::Type *ElemTy = AType->getElementType(); 4428 unsigned NumElements = AType->getNumElements(); 4429 4430 // Wide strings have either 2-byte or 4-byte elements. 4431 if (ElemTy->getPrimitiveSizeInBits() == 16) { 4432 SmallVector<uint16_t, 32> Elements; 4433 Elements.reserve(NumElements); 4434 4435 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 4436 Elements.push_back(E->getCodeUnit(i)); 4437 Elements.resize(NumElements); 4438 return llvm::ConstantDataArray::get(VMContext, Elements); 4439 } 4440 4441 assert(ElemTy->getPrimitiveSizeInBits() == 32); 4442 SmallVector<uint32_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 static llvm::GlobalVariable * 4452 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 4453 CodeGenModule &CGM, StringRef GlobalName, 4454 CharUnits Alignment) { 4455 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 4456 CGM.getStringLiteralAddressSpace()); 4457 4458 llvm::Module &M = CGM.getModule(); 4459 // Create a global variable for this string 4460 auto *GV = new llvm::GlobalVariable( 4461 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 4462 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 4463 GV->setAlignment(Alignment.getQuantity()); 4464 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 4465 if (GV->isWeakForLinker()) { 4466 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 4467 GV->setComdat(M.getOrInsertComdat(GV->getName())); 4468 } 4469 CGM.setDSOLocal(GV); 4470 4471 return GV; 4472 } 4473 4474 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 4475 /// constant array for the given string literal. 4476 ConstantAddress 4477 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 4478 StringRef Name) { 4479 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 4480 4481 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 4482 llvm::GlobalVariable **Entry = nullptr; 4483 if (!LangOpts.WritableStrings) { 4484 Entry = &ConstantStringMap[C]; 4485 if (auto GV = *Entry) { 4486 if (Alignment.getQuantity() > GV->getAlignment()) 4487 GV->setAlignment(Alignment.getQuantity()); 4488 return ConstantAddress(GV, Alignment); 4489 } 4490 } 4491 4492 SmallString<256> MangledNameBuffer; 4493 StringRef GlobalVariableName; 4494 llvm::GlobalValue::LinkageTypes LT; 4495 4496 // Mangle the string literal if that's how the ABI merges duplicate strings. 4497 // Don't do it if they are writable, since we don't want writes in one TU to 4498 // affect strings in another. 4499 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 4500 !LangOpts.WritableStrings) { 4501 llvm::raw_svector_ostream Out(MangledNameBuffer); 4502 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 4503 LT = llvm::GlobalValue::LinkOnceODRLinkage; 4504 GlobalVariableName = MangledNameBuffer; 4505 } else { 4506 LT = llvm::GlobalValue::PrivateLinkage; 4507 GlobalVariableName = Name; 4508 } 4509 4510 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 4511 if (Entry) 4512 *Entry = GV; 4513 4514 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 4515 QualType()); 4516 4517 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 4518 Alignment); 4519 } 4520 4521 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 4522 /// array for the given ObjCEncodeExpr node. 4523 ConstantAddress 4524 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 4525 std::string Str; 4526 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 4527 4528 return GetAddrOfConstantCString(Str); 4529 } 4530 4531 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 4532 /// the literal and a terminating '\0' character. 4533 /// The result has pointer to array type. 4534 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 4535 const std::string &Str, const char *GlobalName) { 4536 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 4537 CharUnits Alignment = 4538 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 4539 4540 llvm::Constant *C = 4541 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 4542 4543 // Don't share any string literals if strings aren't constant. 4544 llvm::GlobalVariable **Entry = nullptr; 4545 if (!LangOpts.WritableStrings) { 4546 Entry = &ConstantStringMap[C]; 4547 if (auto GV = *Entry) { 4548 if (Alignment.getQuantity() > GV->getAlignment()) 4549 GV->setAlignment(Alignment.getQuantity()); 4550 return ConstantAddress(GV, Alignment); 4551 } 4552 } 4553 4554 // Get the default prefix if a name wasn't specified. 4555 if (!GlobalName) 4556 GlobalName = ".str"; 4557 // Create a global variable for this. 4558 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 4559 GlobalName, Alignment); 4560 if (Entry) 4561 *Entry = GV; 4562 4563 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 4564 Alignment); 4565 } 4566 4567 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 4568 const MaterializeTemporaryExpr *E, const Expr *Init) { 4569 assert((E->getStorageDuration() == SD_Static || 4570 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 4571 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 4572 4573 // If we're not materializing a subobject of the temporary, keep the 4574 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 4575 QualType MaterializedType = Init->getType(); 4576 if (Init == E->GetTemporaryExpr()) 4577 MaterializedType = E->getType(); 4578 4579 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 4580 4581 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 4582 return ConstantAddress(Slot, Align); 4583 4584 // FIXME: If an externally-visible declaration extends multiple temporaries, 4585 // we need to give each temporary the same name in every translation unit (and 4586 // we also need to make the temporaries externally-visible). 4587 SmallString<256> Name; 4588 llvm::raw_svector_ostream Out(Name); 4589 getCXXABI().getMangleContext().mangleReferenceTemporary( 4590 VD, E->getManglingNumber(), Out); 4591 4592 APValue *Value = nullptr; 4593 if (E->getStorageDuration() == SD_Static) { 4594 // We might have a cached constant initializer for this temporary. Note 4595 // that this might have a different value from the value computed by 4596 // evaluating the initializer if the surrounding constant expression 4597 // modifies the temporary. 4598 Value = getContext().getMaterializedTemporaryValue(E, false); 4599 if (Value && Value->isUninit()) 4600 Value = nullptr; 4601 } 4602 4603 // Try evaluating it now, it might have a constant initializer. 4604 Expr::EvalResult EvalResult; 4605 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 4606 !EvalResult.hasSideEffects()) 4607 Value = &EvalResult.Val; 4608 4609 LangAS AddrSpace = 4610 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 4611 4612 Optional<ConstantEmitter> emitter; 4613 llvm::Constant *InitialValue = nullptr; 4614 bool Constant = false; 4615 llvm::Type *Type; 4616 if (Value) { 4617 // The temporary has a constant initializer, use it. 4618 emitter.emplace(*this); 4619 InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 4620 MaterializedType); 4621 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 4622 Type = InitialValue->getType(); 4623 } else { 4624 // No initializer, the initialization will be provided when we 4625 // initialize the declaration which performed lifetime extension. 4626 Type = getTypes().ConvertTypeForMem(MaterializedType); 4627 } 4628 4629 // Create a global variable for this lifetime-extended temporary. 4630 llvm::GlobalValue::LinkageTypes Linkage = 4631 getLLVMLinkageVarDefinition(VD, Constant); 4632 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 4633 const VarDecl *InitVD; 4634 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 4635 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 4636 // Temporaries defined inside a class get linkonce_odr linkage because the 4637 // class can be defined in multiple translation units. 4638 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 4639 } else { 4640 // There is no need for this temporary to have external linkage if the 4641 // VarDecl has external linkage. 4642 Linkage = llvm::GlobalVariable::InternalLinkage; 4643 } 4644 } 4645 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 4646 auto *GV = new llvm::GlobalVariable( 4647 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 4648 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 4649 if (emitter) emitter->finalize(GV); 4650 setGVProperties(GV, VD); 4651 GV->setAlignment(Align.getQuantity()); 4652 if (supportsCOMDAT() && GV->isWeakForLinker()) 4653 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 4654 if (VD->getTLSKind()) 4655 setTLSMode(GV, *VD); 4656 llvm::Constant *CV = GV; 4657 if (AddrSpace != LangAS::Default) 4658 CV = getTargetCodeGenInfo().performAddrSpaceCast( 4659 *this, GV, AddrSpace, LangAS::Default, 4660 Type->getPointerTo( 4661 getContext().getTargetAddressSpace(LangAS::Default))); 4662 MaterializedGlobalTemporaryMap[E] = CV; 4663 return ConstantAddress(CV, Align); 4664 } 4665 4666 /// EmitObjCPropertyImplementations - Emit information for synthesized 4667 /// properties for an implementation. 4668 void CodeGenModule::EmitObjCPropertyImplementations(const 4669 ObjCImplementationDecl *D) { 4670 for (const auto *PID : D->property_impls()) { 4671 // Dynamic is just for type-checking. 4672 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 4673 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 4674 4675 // Determine which methods need to be implemented, some may have 4676 // been overridden. Note that ::isPropertyAccessor is not the method 4677 // we want, that just indicates if the decl came from a 4678 // property. What we want to know is if the method is defined in 4679 // this implementation. 4680 if (!D->getInstanceMethod(PD->getGetterName())) 4681 CodeGenFunction(*this).GenerateObjCGetter( 4682 const_cast<ObjCImplementationDecl *>(D), PID); 4683 if (!PD->isReadOnly() && 4684 !D->getInstanceMethod(PD->getSetterName())) 4685 CodeGenFunction(*this).GenerateObjCSetter( 4686 const_cast<ObjCImplementationDecl *>(D), PID); 4687 } 4688 } 4689 } 4690 4691 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 4692 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 4693 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 4694 ivar; ivar = ivar->getNextIvar()) 4695 if (ivar->getType().isDestructedType()) 4696 return true; 4697 4698 return false; 4699 } 4700 4701 static bool AllTrivialInitializers(CodeGenModule &CGM, 4702 ObjCImplementationDecl *D) { 4703 CodeGenFunction CGF(CGM); 4704 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 4705 E = D->init_end(); B != E; ++B) { 4706 CXXCtorInitializer *CtorInitExp = *B; 4707 Expr *Init = CtorInitExp->getInit(); 4708 if (!CGF.isTrivialInitializer(Init)) 4709 return false; 4710 } 4711 return true; 4712 } 4713 4714 /// EmitObjCIvarInitializations - Emit information for ivar initialization 4715 /// for an implementation. 4716 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 4717 // We might need a .cxx_destruct even if we don't have any ivar initializers. 4718 if (needsDestructMethod(D)) { 4719 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 4720 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 4721 ObjCMethodDecl *DTORMethod = 4722 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 4723 cxxSelector, getContext().VoidTy, nullptr, D, 4724 /*isInstance=*/true, /*isVariadic=*/false, 4725 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 4726 /*isDefined=*/false, ObjCMethodDecl::Required); 4727 D->addInstanceMethod(DTORMethod); 4728 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 4729 D->setHasDestructors(true); 4730 } 4731 4732 // If the implementation doesn't have any ivar initializers, we don't need 4733 // a .cxx_construct. 4734 if (D->getNumIvarInitializers() == 0 || 4735 AllTrivialInitializers(*this, D)) 4736 return; 4737 4738 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 4739 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 4740 // The constructor returns 'self'. 4741 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 4742 D->getLocation(), 4743 D->getLocation(), 4744 cxxSelector, 4745 getContext().getObjCIdType(), 4746 nullptr, D, /*isInstance=*/true, 4747 /*isVariadic=*/false, 4748 /*isPropertyAccessor=*/true, 4749 /*isImplicitlyDeclared=*/true, 4750 /*isDefined=*/false, 4751 ObjCMethodDecl::Required); 4752 D->addInstanceMethod(CTORMethod); 4753 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 4754 D->setHasNonZeroConstructors(true); 4755 } 4756 4757 // EmitLinkageSpec - Emit all declarations in a linkage spec. 4758 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 4759 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 4760 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 4761 ErrorUnsupported(LSD, "linkage spec"); 4762 return; 4763 } 4764 4765 EmitDeclContext(LSD); 4766 } 4767 4768 void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 4769 for (auto *I : DC->decls()) { 4770 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 4771 // are themselves considered "top-level", so EmitTopLevelDecl on an 4772 // ObjCImplDecl does not recursively visit them. We need to do that in 4773 // case they're nested inside another construct (LinkageSpecDecl / 4774 // ExportDecl) that does stop them from being considered "top-level". 4775 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 4776 for (auto *M : OID->methods()) 4777 EmitTopLevelDecl(M); 4778 } 4779 4780 EmitTopLevelDecl(I); 4781 } 4782 } 4783 4784 /// EmitTopLevelDecl - Emit code for a single top level declaration. 4785 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 4786 // Ignore dependent declarations. 4787 if (D->isTemplated()) 4788 return; 4789 4790 switch (D->getKind()) { 4791 case Decl::CXXConversion: 4792 case Decl::CXXMethod: 4793 case Decl::Function: 4794 EmitGlobal(cast<FunctionDecl>(D)); 4795 // Always provide some coverage mapping 4796 // even for the functions that aren't emitted. 4797 AddDeferredUnusedCoverageMapping(D); 4798 break; 4799 4800 case Decl::CXXDeductionGuide: 4801 // Function-like, but does not result in code emission. 4802 break; 4803 4804 case Decl::Var: 4805 case Decl::Decomposition: 4806 case Decl::VarTemplateSpecialization: 4807 EmitGlobal(cast<VarDecl>(D)); 4808 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 4809 for (auto *B : DD->bindings()) 4810 if (auto *HD = B->getHoldingVar()) 4811 EmitGlobal(HD); 4812 break; 4813 4814 // Indirect fields from global anonymous structs and unions can be 4815 // ignored; only the actual variable requires IR gen support. 4816 case Decl::IndirectField: 4817 break; 4818 4819 // C++ Decls 4820 case Decl::Namespace: 4821 EmitDeclContext(cast<NamespaceDecl>(D)); 4822 break; 4823 case Decl::ClassTemplateSpecialization: { 4824 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 4825 if (DebugInfo && 4826 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 4827 Spec->hasDefinition()) 4828 DebugInfo->completeTemplateDefinition(*Spec); 4829 } LLVM_FALLTHROUGH; 4830 case Decl::CXXRecord: 4831 if (DebugInfo) { 4832 if (auto *ES = D->getASTContext().getExternalSource()) 4833 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 4834 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D)); 4835 } 4836 // Emit any static data members, they may be definitions. 4837 for (auto *I : cast<CXXRecordDecl>(D)->decls()) 4838 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 4839 EmitTopLevelDecl(I); 4840 break; 4841 // No code generation needed. 4842 case Decl::UsingShadow: 4843 case Decl::ClassTemplate: 4844 case Decl::VarTemplate: 4845 case Decl::VarTemplatePartialSpecialization: 4846 case Decl::FunctionTemplate: 4847 case Decl::TypeAliasTemplate: 4848 case Decl::Block: 4849 case Decl::Empty: 4850 case Decl::Binding: 4851 break; 4852 case Decl::Using: // using X; [C++] 4853 if (CGDebugInfo *DI = getModuleDebugInfo()) 4854 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 4855 return; 4856 case Decl::NamespaceAlias: 4857 if (CGDebugInfo *DI = getModuleDebugInfo()) 4858 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 4859 return; 4860 case Decl::UsingDirective: // using namespace X; [C++] 4861 if (CGDebugInfo *DI = getModuleDebugInfo()) 4862 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 4863 return; 4864 case Decl::CXXConstructor: 4865 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 4866 break; 4867 case Decl::CXXDestructor: 4868 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 4869 break; 4870 4871 case Decl::StaticAssert: 4872 // Nothing to do. 4873 break; 4874 4875 // Objective-C Decls 4876 4877 // Forward declarations, no (immediate) code generation. 4878 case Decl::ObjCInterface: 4879 case Decl::ObjCCategory: 4880 break; 4881 4882 case Decl::ObjCProtocol: { 4883 auto *Proto = cast<ObjCProtocolDecl>(D); 4884 if (Proto->isThisDeclarationADefinition()) 4885 ObjCRuntime->GenerateProtocol(Proto); 4886 break; 4887 } 4888 4889 case Decl::ObjCCategoryImpl: 4890 // Categories have properties but don't support synthesize so we 4891 // can ignore them here. 4892 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 4893 break; 4894 4895 case Decl::ObjCImplementation: { 4896 auto *OMD = cast<ObjCImplementationDecl>(D); 4897 EmitObjCPropertyImplementations(OMD); 4898 EmitObjCIvarInitializations(OMD); 4899 ObjCRuntime->GenerateClass(OMD); 4900 // Emit global variable debug information. 4901 if (CGDebugInfo *DI = getModuleDebugInfo()) 4902 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 4903 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 4904 OMD->getClassInterface()), OMD->getLocation()); 4905 break; 4906 } 4907 case Decl::ObjCMethod: { 4908 auto *OMD = cast<ObjCMethodDecl>(D); 4909 // If this is not a prototype, emit the body. 4910 if (OMD->getBody()) 4911 CodeGenFunction(*this).GenerateObjCMethod(OMD); 4912 break; 4913 } 4914 case Decl::ObjCCompatibleAlias: 4915 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 4916 break; 4917 4918 case Decl::PragmaComment: { 4919 const auto *PCD = cast<PragmaCommentDecl>(D); 4920 switch (PCD->getCommentKind()) { 4921 case PCK_Unknown: 4922 llvm_unreachable("unexpected pragma comment kind"); 4923 case PCK_Linker: 4924 AppendLinkerOptions(PCD->getArg()); 4925 break; 4926 case PCK_Lib: 4927 if (getTarget().getTriple().isOSBinFormatELF() && 4928 !getTarget().getTriple().isPS4()) 4929 AddELFLibDirective(PCD->getArg()); 4930 else 4931 AddDependentLib(PCD->getArg()); 4932 break; 4933 case PCK_Compiler: 4934 case PCK_ExeStr: 4935 case PCK_User: 4936 break; // We ignore all of these. 4937 } 4938 break; 4939 } 4940 4941 case Decl::PragmaDetectMismatch: { 4942 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 4943 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 4944 break; 4945 } 4946 4947 case Decl::LinkageSpec: 4948 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 4949 break; 4950 4951 case Decl::FileScopeAsm: { 4952 // File-scope asm is ignored during device-side CUDA compilation. 4953 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 4954 break; 4955 // File-scope asm is ignored during device-side OpenMP compilation. 4956 if (LangOpts.OpenMPIsDevice) 4957 break; 4958 auto *AD = cast<FileScopeAsmDecl>(D); 4959 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 4960 break; 4961 } 4962 4963 case Decl::Import: { 4964 auto *Import = cast<ImportDecl>(D); 4965 4966 // If we've already imported this module, we're done. 4967 if (!ImportedModules.insert(Import->getImportedModule())) 4968 break; 4969 4970 // Emit debug information for direct imports. 4971 if (!Import->getImportedOwningModule()) { 4972 if (CGDebugInfo *DI = getModuleDebugInfo()) 4973 DI->EmitImportDecl(*Import); 4974 } 4975 4976 // Find all of the submodules and emit the module initializers. 4977 llvm::SmallPtrSet<clang::Module *, 16> Visited; 4978 SmallVector<clang::Module *, 16> Stack; 4979 Visited.insert(Import->getImportedModule()); 4980 Stack.push_back(Import->getImportedModule()); 4981 4982 while (!Stack.empty()) { 4983 clang::Module *Mod = Stack.pop_back_val(); 4984 if (!EmittedModuleInitializers.insert(Mod).second) 4985 continue; 4986 4987 for (auto *D : Context.getModuleInitializers(Mod)) 4988 EmitTopLevelDecl(D); 4989 4990 // Visit the submodules of this module. 4991 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 4992 SubEnd = Mod->submodule_end(); 4993 Sub != SubEnd; ++Sub) { 4994 // Skip explicit children; they need to be explicitly imported to emit 4995 // the initializers. 4996 if ((*Sub)->IsExplicit) 4997 continue; 4998 4999 if (Visited.insert(*Sub).second) 5000 Stack.push_back(*Sub); 5001 } 5002 } 5003 break; 5004 } 5005 5006 case Decl::Export: 5007 EmitDeclContext(cast<ExportDecl>(D)); 5008 break; 5009 5010 case Decl::OMPThreadPrivate: 5011 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 5012 break; 5013 5014 case Decl::OMPDeclareReduction: 5015 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 5016 break; 5017 5018 case Decl::OMPRequires: 5019 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 5020 break; 5021 5022 default: 5023 // Make sure we handled everything we should, every other kind is a 5024 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 5025 // function. Need to recode Decl::Kind to do that easily. 5026 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 5027 break; 5028 } 5029 } 5030 5031 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 5032 // Do we need to generate coverage mapping? 5033 if (!CodeGenOpts.CoverageMapping) 5034 return; 5035 switch (D->getKind()) { 5036 case Decl::CXXConversion: 5037 case Decl::CXXMethod: 5038 case Decl::Function: 5039 case Decl::ObjCMethod: 5040 case Decl::CXXConstructor: 5041 case Decl::CXXDestructor: { 5042 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 5043 return; 5044 SourceManager &SM = getContext().getSourceManager(); 5045 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 5046 return; 5047 auto I = DeferredEmptyCoverageMappingDecls.find(D); 5048 if (I == DeferredEmptyCoverageMappingDecls.end()) 5049 DeferredEmptyCoverageMappingDecls[D] = true; 5050 break; 5051 } 5052 default: 5053 break; 5054 }; 5055 } 5056 5057 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 5058 // Do we need to generate coverage mapping? 5059 if (!CodeGenOpts.CoverageMapping) 5060 return; 5061 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 5062 if (Fn->isTemplateInstantiation()) 5063 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 5064 } 5065 auto I = DeferredEmptyCoverageMappingDecls.find(D); 5066 if (I == DeferredEmptyCoverageMappingDecls.end()) 5067 DeferredEmptyCoverageMappingDecls[D] = false; 5068 else 5069 I->second = false; 5070 } 5071 5072 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 5073 // We call takeVector() here to avoid use-after-free. 5074 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 5075 // we deserialize function bodies to emit coverage info for them, and that 5076 // deserializes more declarations. How should we handle that case? 5077 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 5078 if (!Entry.second) 5079 continue; 5080 const Decl *D = Entry.first; 5081 switch (D->getKind()) { 5082 case Decl::CXXConversion: 5083 case Decl::CXXMethod: 5084 case Decl::Function: 5085 case Decl::ObjCMethod: { 5086 CodeGenPGO PGO(*this); 5087 GlobalDecl GD(cast<FunctionDecl>(D)); 5088 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5089 getFunctionLinkage(GD)); 5090 break; 5091 } 5092 case Decl::CXXConstructor: { 5093 CodeGenPGO PGO(*this); 5094 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 5095 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5096 getFunctionLinkage(GD)); 5097 break; 5098 } 5099 case Decl::CXXDestructor: { 5100 CodeGenPGO PGO(*this); 5101 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 5102 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5103 getFunctionLinkage(GD)); 5104 break; 5105 } 5106 default: 5107 break; 5108 }; 5109 } 5110 } 5111 5112 /// Turns the given pointer into a constant. 5113 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 5114 const void *Ptr) { 5115 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 5116 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 5117 return llvm::ConstantInt::get(i64, PtrInt); 5118 } 5119 5120 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 5121 llvm::NamedMDNode *&GlobalMetadata, 5122 GlobalDecl D, 5123 llvm::GlobalValue *Addr) { 5124 if (!GlobalMetadata) 5125 GlobalMetadata = 5126 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 5127 5128 // TODO: should we report variant information for ctors/dtors? 5129 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 5130 llvm::ConstantAsMetadata::get(GetPointerConstant( 5131 CGM.getLLVMContext(), D.getDecl()))}; 5132 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 5133 } 5134 5135 /// For each function which is declared within an extern "C" region and marked 5136 /// as 'used', but has internal linkage, create an alias from the unmangled 5137 /// name to the mangled name if possible. People expect to be able to refer 5138 /// to such functions with an unmangled name from inline assembly within the 5139 /// same translation unit. 5140 void CodeGenModule::EmitStaticExternCAliases() { 5141 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 5142 return; 5143 for (auto &I : StaticExternCValues) { 5144 IdentifierInfo *Name = I.first; 5145 llvm::GlobalValue *Val = I.second; 5146 if (Val && !getModule().getNamedValue(Name->getName())) 5147 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 5148 } 5149 } 5150 5151 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 5152 GlobalDecl &Result) const { 5153 auto Res = Manglings.find(MangledName); 5154 if (Res == Manglings.end()) 5155 return false; 5156 Result = Res->getValue(); 5157 return true; 5158 } 5159 5160 /// Emits metadata nodes associating all the global values in the 5161 /// current module with the Decls they came from. This is useful for 5162 /// projects using IR gen as a subroutine. 5163 /// 5164 /// Since there's currently no way to associate an MDNode directly 5165 /// with an llvm::GlobalValue, we create a global named metadata 5166 /// with the name 'clang.global.decl.ptrs'. 5167 void CodeGenModule::EmitDeclMetadata() { 5168 llvm::NamedMDNode *GlobalMetadata = nullptr; 5169 5170 for (auto &I : MangledDeclNames) { 5171 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 5172 // Some mangled names don't necessarily have an associated GlobalValue 5173 // in this module, e.g. if we mangled it for DebugInfo. 5174 if (Addr) 5175 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 5176 } 5177 } 5178 5179 /// Emits metadata nodes for all the local variables in the current 5180 /// function. 5181 void CodeGenFunction::EmitDeclMetadata() { 5182 if (LocalDeclMap.empty()) return; 5183 5184 llvm::LLVMContext &Context = getLLVMContext(); 5185 5186 // Find the unique metadata ID for this name. 5187 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 5188 5189 llvm::NamedMDNode *GlobalMetadata = nullptr; 5190 5191 for (auto &I : LocalDeclMap) { 5192 const Decl *D = I.first; 5193 llvm::Value *Addr = I.second.getPointer(); 5194 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 5195 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 5196 Alloca->setMetadata( 5197 DeclPtrKind, llvm::MDNode::get( 5198 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 5199 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 5200 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 5201 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 5202 } 5203 } 5204 } 5205 5206 void CodeGenModule::EmitVersionIdentMetadata() { 5207 llvm::NamedMDNode *IdentMetadata = 5208 TheModule.getOrInsertNamedMetadata("llvm.ident"); 5209 std::string Version = getClangFullVersion(); 5210 llvm::LLVMContext &Ctx = TheModule.getContext(); 5211 5212 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 5213 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 5214 } 5215 5216 void CodeGenModule::EmitCommandLineMetadata() { 5217 llvm::NamedMDNode *CommandLineMetadata = 5218 TheModule.getOrInsertNamedMetadata("llvm.commandline"); 5219 std::string CommandLine = getCodeGenOpts().RecordCommandLine; 5220 llvm::LLVMContext &Ctx = TheModule.getContext(); 5221 5222 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 5223 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 5224 } 5225 5226 void CodeGenModule::EmitTargetMetadata() { 5227 // Warning, new MangledDeclNames may be appended within this loop. 5228 // We rely on MapVector insertions adding new elements to the end 5229 // of the container. 5230 // FIXME: Move this loop into the one target that needs it, and only 5231 // loop over those declarations for which we couldn't emit the target 5232 // metadata when we emitted the declaration. 5233 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 5234 auto Val = *(MangledDeclNames.begin() + I); 5235 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 5236 llvm::GlobalValue *GV = GetGlobalValue(Val.second); 5237 getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 5238 } 5239 } 5240 5241 void CodeGenModule::EmitCoverageFile() { 5242 if (getCodeGenOpts().CoverageDataFile.empty() && 5243 getCodeGenOpts().CoverageNotesFile.empty()) 5244 return; 5245 5246 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 5247 if (!CUNode) 5248 return; 5249 5250 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 5251 llvm::LLVMContext &Ctx = TheModule.getContext(); 5252 auto *CoverageDataFile = 5253 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 5254 auto *CoverageNotesFile = 5255 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 5256 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 5257 llvm::MDNode *CU = CUNode->getOperand(i); 5258 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 5259 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 5260 } 5261 } 5262 5263 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 5264 // Sema has checked that all uuid strings are of the form 5265 // "12345678-1234-1234-1234-1234567890ab". 5266 assert(Uuid.size() == 36); 5267 for (unsigned i = 0; i < 36; ++i) { 5268 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 5269 else assert(isHexDigit(Uuid[i])); 5270 } 5271 5272 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 5273 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 5274 5275 llvm::Constant *Field3[8]; 5276 for (unsigned Idx = 0; Idx < 8; ++Idx) 5277 Field3[Idx] = llvm::ConstantInt::get( 5278 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 5279 5280 llvm::Constant *Fields[4] = { 5281 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 5282 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 5283 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 5284 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 5285 }; 5286 5287 return llvm::ConstantStruct::getAnon(Fields); 5288 } 5289 5290 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 5291 bool ForEH) { 5292 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 5293 // FIXME: should we even be calling this method if RTTI is disabled 5294 // and it's not for EH? 5295 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice) 5296 return llvm::Constant::getNullValue(Int8PtrTy); 5297 5298 if (ForEH && Ty->isObjCObjectPointerType() && 5299 LangOpts.ObjCRuntime.isGNUFamily()) 5300 return ObjCRuntime->GetEHType(Ty); 5301 5302 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 5303 } 5304 5305 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 5306 // Do not emit threadprivates in simd-only mode. 5307 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 5308 return; 5309 for (auto RefExpr : D->varlists()) { 5310 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 5311 bool PerformInit = 5312 VD->getAnyInitializer() && 5313 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 5314 /*ForRef=*/false); 5315 5316 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 5317 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 5318 VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 5319 CXXGlobalInits.push_back(InitFunction); 5320 } 5321 } 5322 5323 llvm::Metadata * 5324 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 5325 StringRef Suffix) { 5326 llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 5327 if (InternalId) 5328 return InternalId; 5329 5330 if (isExternallyVisible(T->getLinkage())) { 5331 std::string OutName; 5332 llvm::raw_string_ostream Out(OutName); 5333 getCXXABI().getMangleContext().mangleTypeName(T, Out); 5334 Out << Suffix; 5335 5336 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 5337 } else { 5338 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 5339 llvm::ArrayRef<llvm::Metadata *>()); 5340 } 5341 5342 return InternalId; 5343 } 5344 5345 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 5346 return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 5347 } 5348 5349 llvm::Metadata * 5350 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 5351 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 5352 } 5353 5354 // Generalize pointer types to a void pointer with the qualifiers of the 5355 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 5356 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 5357 // 'void *'. 5358 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 5359 if (!Ty->isPointerType()) 5360 return Ty; 5361 5362 return Ctx.getPointerType( 5363 QualType(Ctx.VoidTy).withCVRQualifiers( 5364 Ty->getPointeeType().getCVRQualifiers())); 5365 } 5366 5367 // Apply type generalization to a FunctionType's return and argument types 5368 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 5369 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 5370 SmallVector<QualType, 8> GeneralizedParams; 5371 for (auto &Param : FnType->param_types()) 5372 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 5373 5374 return Ctx.getFunctionType( 5375 GeneralizeType(Ctx, FnType->getReturnType()), 5376 GeneralizedParams, FnType->getExtProtoInfo()); 5377 } 5378 5379 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 5380 return Ctx.getFunctionNoProtoType( 5381 GeneralizeType(Ctx, FnType->getReturnType())); 5382 5383 llvm_unreachable("Encountered unknown FunctionType"); 5384 } 5385 5386 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 5387 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 5388 GeneralizedMetadataIdMap, ".generalized"); 5389 } 5390 5391 /// Returns whether this module needs the "all-vtables" type identifier. 5392 bool CodeGenModule::NeedAllVtablesTypeId() const { 5393 // Returns true if at least one of vtable-based CFI checkers is enabled and 5394 // is not in the trapping mode. 5395 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 5396 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 5397 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 5398 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 5399 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 5400 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 5401 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 5402 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 5403 } 5404 5405 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 5406 CharUnits Offset, 5407 const CXXRecordDecl *RD) { 5408 llvm::Metadata *MD = 5409 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 5410 VTable->addTypeMetadata(Offset.getQuantity(), MD); 5411 5412 if (CodeGenOpts.SanitizeCfiCrossDso) 5413 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 5414 VTable->addTypeMetadata(Offset.getQuantity(), 5415 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 5416 5417 if (NeedAllVtablesTypeId()) { 5418 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 5419 VTable->addTypeMetadata(Offset.getQuantity(), MD); 5420 } 5421 } 5422 5423 TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) { 5424 assert(TD != nullptr); 5425 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 5426 5427 ParsedAttr.Features.erase( 5428 llvm::remove_if(ParsedAttr.Features, 5429 [&](const std::string &Feat) { 5430 return !Target.isValidFeatureName( 5431 StringRef{Feat}.substr(1)); 5432 }), 5433 ParsedAttr.Features.end()); 5434 return ParsedAttr; 5435 } 5436 5437 5438 // Fills in the supplied string map with the set of target features for the 5439 // passed in function. 5440 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 5441 GlobalDecl GD) { 5442 StringRef TargetCPU = Target.getTargetOpts().CPU; 5443 const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 5444 if (const auto *TD = FD->getAttr<TargetAttr>()) { 5445 TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 5446 5447 // Make a copy of the features as passed on the command line into the 5448 // beginning of the additional features from the function to override. 5449 ParsedAttr.Features.insert(ParsedAttr.Features.begin(), 5450 Target.getTargetOpts().FeaturesAsWritten.begin(), 5451 Target.getTargetOpts().FeaturesAsWritten.end()); 5452 5453 if (ParsedAttr.Architecture != "" && 5454 Target.isValidCPUName(ParsedAttr.Architecture)) 5455 TargetCPU = ParsedAttr.Architecture; 5456 5457 // Now populate the feature map, first with the TargetCPU which is either 5458 // the default or a new one from the target attribute string. Then we'll use 5459 // the passed in features (FeaturesAsWritten) along with the new ones from 5460 // the attribute. 5461 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 5462 ParsedAttr.Features); 5463 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 5464 llvm::SmallVector<StringRef, 32> FeaturesTmp; 5465 Target.getCPUSpecificCPUDispatchFeatures( 5466 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 5467 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 5468 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features); 5469 } else { 5470 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 5471 Target.getTargetOpts().Features); 5472 } 5473 } 5474 5475 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 5476 if (!SanStats) 5477 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule()); 5478 5479 return *SanStats; 5480 } 5481 llvm::Value * 5482 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 5483 CodeGenFunction &CGF) { 5484 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 5485 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 5486 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 5487 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, 5488 "__translate_sampler_initializer"), 5489 {C}); 5490 } 5491