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