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