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