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