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