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