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