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