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