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