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