blob: 129a7703e6a297f063b6d21b3f5a10ce29958aa3 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
John McCall7f416cc2015-09-08 08:05:57 +000015#include "CGBlocks.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000016#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGCall.h"
19#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000021#include "CGOpenCLRuntime.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022#include "CGOpenMPRuntime.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000023#include "CGOpenMPRuntimeNVPTX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "CodeGenFunction.h"
Justin Bogneref512b92014-01-06 22:27:43 +000025#include "CodeGenPGO.h"
John McCallde0fe072017-08-15 21:42:52 +000026#include "ConstantEmitter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000027#include "CoverageMappingGen.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000028#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000029#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000030#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000031#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000033#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000034#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000035#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000036#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000037#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000038#include "clang/Basic/CharInfo.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000039#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000040#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000041#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000042#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000043#include "clang/Basic/Version.h"
John McCall5ad74072017-03-02 20:04:19 +000044#include "clang/CodeGen/ConstantInitBuilder.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000045#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindola208b5c02013-10-22 19:26:13 +000046#include "clang/Sema/SemaDiagnostic.h"
Caroline Tice62279732018-09-21 18:34:59 +000047#include "llvm/ADT/StringSwitch.h"
John McCallbeec5a02010-03-06 00:35:14 +000048#include "llvm/ADT/Triple.h"
Matthias Brauna4519532017-05-20 01:29:55 +000049#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000050#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000051#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"
Justin Bogner837a6f62014-04-18 21:52:00 +000056#include "llvm/ProfileData/InstrProfReader.h"
Caroline Tice62279732018-09-21 18:34:59 +000057#include "llvm/Support/CodeGen.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000058#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000059#include "llvm/Support/ErrorHandling.h"
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +000060#include "llvm/Support/MD5.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000061
Chris Lattnerbed31442007-05-28 01:07:47 +000062using namespace clang;
63using namespace CodeGen;
64
Vedant Kumar0acf3432017-09-22 18:23:04 +000065static llvm::cl::opt<bool> LimitedCoverage(
Zachary Turner8065f0b2017-12-01 00:53:10 +000066 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
Vedant Kumar0acf3432017-09-22 18:23:04 +000067 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
68 llvm::cl::init(false));
69
Julien Lerouge5a6b6982011-09-09 22:41:49 +000070static const char AnnotationSection[] = "llvm.metadata";
71
Alp Toker82862252013-12-28 21:58:40 +000072static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000073 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000074 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000075 case TargetCXXABI::GenericARM:
76 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000077 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +000078 case TargetCXXABI::WatchOS:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000079 case TargetCXXABI::GenericMIPS:
John McCall57625922013-01-25 23:36:14 +000080 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +000081 case TargetCXXABI::WebAssembly:
Alp Toker82862252013-12-28 21:58:40 +000082 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000083 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000084 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000085 }
86
87 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000088}
89
Adrian Prantle74f5252015-06-30 02:26:03 +000090CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
91 const PreprocessorOptions &PPO,
92 const CodeGenOptions &CGO, llvm::Module &M,
Alex Lorenzee024992014-08-04 18:41:51 +000093 DiagnosticsEngine &diags,
94 CoverageSourceInfo *CoverageInfo)
Adrian Prantle74f5252015-06-30 02:26:03 +000095 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
96 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
Mehdi Aminica3cf9e2015-07-24 16:04:29 +000097 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
Reid Kleckner9305fd12016-04-13 23:37:17 +000098 VMContext(M.getContext()), Types(*this), VTables(*this),
Peter Collingbourne3afb2662016-04-28 17:09:37 +000099 SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietzf54319c2013-01-18 11:30:38 +0000100
Chris Lattnerece04092012-02-07 00:39:47 +0000101 // Initialize the type cache.
102 llvm::LLVMContext &LLVMContext = M.getContext();
103 VoidTy = llvm::Type::getVoidTy(LLVMContext);
104 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
105 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
106 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
107 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
Abderrazek Zaafranif58a1322017-12-21 19:20:01 +0000108 HalfTy = llvm::Type::getHalfTy(LLVMContext);
Chris Lattnerece04092012-02-07 00:39:47 +0000109 FloatTy = llvm::Type::getFloatTy(LLVMContext);
110 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
111 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
112 PointerAlignInBytes =
John McCall7f416cc2015-09-08 08:05:57 +0000113 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
Yaxun Liu26f75662016-08-19 05:17:25 +0000114 SizeSizeInBytes =
115 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +0000116 IntAlignInBytes =
117 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
Chris Lattnerece04092012-02-07 00:39:47 +0000118 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
Yaxun Liu26f75662016-08-19 05:17:25 +0000119 IntPtrTy = llvm::IntegerType::get(LLVMContext,
120 C.getTargetInfo().getMaxPointerWidth());
Chris Lattnerece04092012-02-07 00:39:47 +0000121 Int8PtrTy = Int8Ty->getPointerTo(0);
122 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000123 AllocaInt8PtrTy = Int8Ty->getPointerTo(
124 M.getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000125 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
Chris Lattnerece04092012-02-07 00:39:47 +0000126
John McCall882987f2013-02-28 19:01:20 +0000127 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
128
David Blaikiebbafb8a2012-03-11 07:00:24 +0000129 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000130 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000131 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000132 createOpenCLRuntime();
Alexey Bataev9959db52014-05-06 10:08:46 +0000133 if (LangOpts.OpenMP)
134 createOpenMPRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000135 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000136 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000137
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000138 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000139 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000140 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000141 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
Reid Kleckner9305fd12016-04-13 23:37:17 +0000142 getCXXABI().getMangleContext()));
Dan Gohman947c9af2010-10-14 23:06:10 +0000143
Nick Lewycky207bce32011-04-21 23:44:07 +0000144 // If debug info or coverage generation is enabled, create the CGDebugInfo
145 // object.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000146 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
147 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000148 DebugInfo.reset(new CGDebugInfo(*this));
John McCallad7c5c12011-02-08 08:22:06 +0000149
150 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000151
John McCallb04ecb72015-10-21 18:06:43 +0000152 if (C.getLangOpts().ObjC1)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000153 ObjCData.reset(new ObjCEntrypoints());
Justin Bogneref512b92014-01-06 22:27:43 +0000154
Rong Xu9c6f1532016-03-02 20:59:36 +0000155 if (CodeGenOpts.hasProfileClangUse()) {
156 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
Richard Smith8654ae52018-10-10 23:13:35 +0000157 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000158 if (auto E = ReaderOrErr.takeError()) {
Justin Bogner837a6f62014-04-18 21:52:00 +0000159 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
Diego Novillo5aecacb2015-06-25 22:56:00 +0000160 "Could not read profile %0: %1");
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000161 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
162 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
163 << EI.message();
164 });
Nico Weber176efac2015-04-06 04:16:48 +0000165 } else
166 PGOReader = std::move(ReaderOrErr.get());
Justin Bogner837a6f62014-04-18 21:52:00 +0000167 }
Alex Lorenzee024992014-08-04 18:41:51 +0000168
169 // If coverage mapping generation is enabled, create the
170 // CoverageMappingModuleGen object.
171 if (CodeGenOpts.CoverageMapping)
172 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattnera087ff92008-03-01 08:45:05 +0000173}
174
Reid Kleckner9305fd12016-04-13 23:37:17 +0000175CodeGenModule::~CodeGenModule() {}
Ted Kremenek2c674f62008-08-05 18:50:11 +0000176
David Chisnall481e3a82010-01-23 02:40:42 +0000177void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000178 // This is just isGNUFamily(), but we want to force implementors of
179 // new ABIs to decide how best to do this.
180 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000181 case ObjCRuntime::GNUstep:
182 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000183 case ObjCRuntime::ObjFW:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000184 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000185 return;
186
187 case ObjCRuntime::FragileMacOSX:
188 case ObjCRuntime::MacOSX:
189 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000190 case ObjCRuntime::WatchOS:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000191 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000192 return;
193 }
194 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000195}
196
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000197void CodeGenModule::createOpenCLRuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000198 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000199}
200
Alexey Bataev9959db52014-05-06 10:08:46 +0000201void CodeGenModule::createOpenMPRuntime() {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000202 // Select a specialized code generation class based on the target, if any.
203 // If it does not exist use the default implementation.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000204 switch (getTriple().getArch()) {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000205 case llvm::Triple::nvptx:
206 case llvm::Triple::nvptx64:
207 assert(getLangOpts().OpenMPIsDevice &&
208 "OpenMP NVPTX is only prepared to deal with device code.");
Reid Kleckner9305fd12016-04-13 23:37:17 +0000209 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000210 break;
211 default:
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000212 if (LangOpts.OpenMPSimd)
213 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
214 else
215 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000216 break;
217 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000218}
219
Peter Collingbournefe883422011-10-06 18:29:37 +0000220void CodeGenModule::createCUDARuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000221 CUDARuntime.reset(CreateNVCUDARuntime(*this));
Peter Collingbournefe883422011-10-06 18:29:37 +0000222}
223
Rafael Espindola1e4df922014-09-16 15:18:21 +0000224void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
225 Replacements[Name] = C;
226}
227
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000228void CodeGenModule::applyReplacements() {
Yaron Kerenb54db522015-06-11 12:33:25 +0000229 for (auto &I : Replacements) {
230 StringRef MangledName = I.first();
231 llvm::Constant *Replacement = I.second;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000232 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
233 if (!Entry)
234 continue;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000235 auto *OldF = cast<llvm::Function>(Entry);
236 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000237 if (!NewF) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000238 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
Rafael Espindola0fcad882014-05-16 22:20:18 +0000239 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Reid Klecknerb78257d2014-02-03 18:54:51 +0000240 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000241 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Reid Klecknerb78257d2014-02-03 18:54:51 +0000242 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
243 CE->getOpcode() == llvm::Instruction::GetElementPtr);
244 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
245 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000246 }
247
248 // Replace old with new, but keep the old order.
249 OldF->replaceAllUsesWith(Replacement);
250 if (NewF) {
251 NewF->removeFromParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000252 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
253 NewF);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000254 }
255 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000256 }
257}
258
Andrey Bokhankocab58582015-08-31 13:20:44 +0000259void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
260 GlobalValReplacements.push_back(std::make_pair(GV, C));
261}
262
263void CodeGenModule::applyGlobalValReplacements() {
264 for (auto &I : GlobalValReplacements) {
265 llvm::GlobalValue *GV = I.first;
266 llvm::Constant *C = I.second;
267
268 GV->replaceAllUsesWith(C);
269 GV->eraseFromParent();
270 }
271}
272
Rafael Espindola27c60b52014-06-03 02:42:01 +0000273// This is only used in aliases that we created and we know they have a
274// linear structure.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000275static const llvm::GlobalObject *getAliasedGlobal(
276 const llvm::GlobalIndirectSymbol &GIS) {
277 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
278 const llvm::Constant *C = &GIS;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000279 for (;;) {
Rafael Espindolae11f40a2014-06-04 19:03:20 +0000280 C = C->stripPointerCasts();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000281 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
282 return GO;
283 // stripPointerCasts will not walk over weak aliases.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000284 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
285 if (!GIS2)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000286 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000287 if (!Visited.insert(GIS2).second)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000288 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000289 C = GIS2->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000290 }
291}
292
Rafael Espindola208b5c02013-10-22 19:26:13 +0000293void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000294 // Check if the constructed aliases are well formed. It is really unfortunate
295 // that we have to do this in CodeGen, but we only construct mangled names
296 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000297 bool Error = false;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000298 DiagnosticsEngine &Diags = getDiags();
Yaron Kerenb54db522015-06-11 12:33:25 +0000299 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000300 const auto *D = cast<ValueDecl>(GD.getDecl());
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000301 SourceLocation Location;
302 bool IsIFunc = D->hasAttr<IFuncAttr>();
303 if (const Attr *A = D->getDefiningAttr())
304 Location = A->getLocation();
305 else
306 llvm_unreachable("Not an alias or ifunc?");
Rafael Espindola208b5c02013-10-22 19:26:13 +0000307 StringRef MangledName = getMangledName(GD);
308 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000309 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000310 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
311 if (!GV) {
312 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000313 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000314 } else if (GV->isDeclaration()) {
Rafael Espindola93c7a652014-03-13 15:47:50 +0000315 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000316 Diags.Report(Location, diag::err_alias_to_undefined)
317 << IsIFunc << IsIFunc;
318 } else if (IsIFunc) {
319 // Check resolver function type.
320 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
321 GV->getType()->getPointerElementType());
322 assert(FTy);
323 if (!FTy->getReturnType()->isPointerTy())
324 Diags.Report(Location, diag::err_ifunc_resolver_return);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000325 }
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000326
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000327 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000328 llvm::GlobalValue *AliaseeGV;
329 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
330 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
331 else
332 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
333
Rafael Espindola502f65a2014-05-05 20:21:03 +0000334 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
335 StringRef AliasSection = SA->getName();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000336 if (AliasSection != AliaseeGV->getSection())
Rafael Espindola502f65a2014-05-05 20:21:03 +0000337 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000338 << AliasSection << IsIFunc << IsIFunc;
Rafael Espindola502f65a2014-05-05 20:21:03 +0000339 }
Rafael Espindola27c60b52014-06-03 02:42:01 +0000340
341 // We have to handle alias to weak aliases in here. LLVM itself disallows
342 // this since the object semantics would not match the IL one. For
343 // compatibility with gcc we implement it by just pointing the alias
344 // to its aliasee's aliasee. We also warn, since the user is probably
345 // expecting the link to be weak.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000346 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
Sanjoy Dasf60a0d72016-04-08 01:31:02 +0000347 if (GA->isInterposable()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000348 Diags.Report(Location, diag::warn_alias_to_weak_alias)
349 << GV->getName() << GA->getName() << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000350 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000351 GA->getIndirectSymbol(), Alias->getType());
352 Alias->setIndirectSymbol(Aliasee);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000353 }
354 }
Rafael Espindola208b5c02013-10-22 19:26:13 +0000355 }
356 if (!Error)
357 return;
358
Yaron Kerenb54db522015-06-11 12:33:25 +0000359 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola208b5c02013-10-22 19:26:13 +0000360 StringRef MangledName = getMangledName(GD);
361 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000362 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000363 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
364 Alias->eraseFromParent();
365 }
366}
367
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000368void CodeGenModule::clear() {
369 DeferredDeclsToEmit.clear();
Alexey Bataev91797552015-03-18 04:13:55 +0000370 if (OpenMPRuntime)
371 OpenMPRuntime->clear();
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000372}
373
Justin Bogner40b8ba12014-06-26 01:45:07 +0000374void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
375 StringRef MainFile) {
376 if (!hasDiagnostics())
377 return;
378 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
379 if (MainFile.empty())
380 MainFile = "<stdin>";
381 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
Vedant Kumar96d6ca72017-04-27 17:30:58 +0000382 } else {
383 if (Mismatched > 0)
384 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
385
386 if (Missing > 0)
387 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
388 }
Justin Bogner40b8ba12014-06-26 01:45:07 +0000389}
390
Ted Kremenek2c674f62008-08-05 18:50:11 +0000391void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000392 EmitDeferred();
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000393 EmitVTablesOpportunistically();
Andrey Bokhankocab58582015-08-31 13:20:44 +0000394 applyGlobalValReplacements();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000395 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000396 checkAliases();
Erich Keane281d20b2018-01-08 21:34:17 +0000397 emitMultiVersionFunctions();
Eli Friedman5866fe32010-01-08 00:50:11 +0000398 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000399 EmitCXXGlobalDtorFunc();
Akira Hatanaka617e2612018-04-17 18:41:52 +0000400 registerGlobalDtorsWithAtExit();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000401 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000402 if (ObjCRuntime)
403 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000404 AddGlobalCtor(ObjCInitFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000405 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
406 CUDARuntime) {
Artem Belevichc66d2542018-06-27 18:32:51 +0000407 if (llvm::Function *CudaCtorFunction =
408 CUDARuntime->makeModuleCtorFunction())
Artem Belevich52cc4872015-05-07 19:34:16 +0000409 AddGlobalCtor(CudaCtorFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000410 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000411 if (OpenMPRuntime) {
Samuel Antaoee8fb302016-01-06 13:42:12 +0000412 if (llvm::Function *OpenMPRegistrationFunction =
George Rokos29d0f002017-05-27 03:03:13 +0000413 OpenMPRuntime->emitRegistrationFunction()) {
414 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415 OpenMPRegistrationFunction : nullptr;
416 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
417 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000418 OpenMPRuntime->clear();
419 }
Easwaran Raman695890c2015-12-17 19:14:27 +0000420 if (PGOReader) {
Easwaran Raman81608122016-03-24 21:32:25 +0000421 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
Easwaran Raman695890c2015-12-17 19:14:27 +0000422 if (PGOStats.hasDiagnostics())
423 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
424 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000425 EmitCtorList(GlobalCtors, "llvm.global_ctors");
426 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000427 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000428 EmitStaticExternCAliases();
Alex Lorenzee024992014-08-04 18:41:51 +0000429 EmitDeferredUnusedCoverageMappings();
430 if (CoverageMapping)
431 CoverageMapping->emit();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000432 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000433 CodeGenFunction(*this).EmitCfiCheckFail();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000434 CodeGenFunction(*this).EmitCfiCheckStub();
435 }
Alex Lorenza8fbef42017-03-23 11:14:27 +0000436 emitAtAvailableLinkGuard();
Rafael Espindola060062a2014-03-06 22:15:10 +0000437 emitLLVMUsed();
Peter Collingbournedc134532016-01-16 00:31:22 +0000438 if (SanStats)
439 SanStats->finish();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000440
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000441 if (CodeGenOpts.Autolink &&
442 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000443 EmitModuleLinkOptions();
444 }
Nirav Dave8497ef42017-03-18 00:43:39 +0000445
Nirav Dave741dea02017-03-30 13:41:44 +0000446 // Record mregparm value now so it is visible through rest of codegen.
447 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
448 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
449 CodeGenOpts.NumRegisterParameters);
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000450
Reid Kleckner124955a2015-08-05 18:51:13 +0000451 if (CodeGenOpts.DwarfVersion) {
Manman Ren9691f7f2013-06-19 01:46:49 +0000452 // We actually want the latest version when there are conflicts.
453 // We can change from Warning to Latest if such mode is supported.
454 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
455 CodeGenOpts.DwarfVersion);
Reid Kleckner124955a2015-08-05 18:51:13 +0000456 }
457 if (CodeGenOpts.EmitCodeView) {
458 // Indicate that we want CodeView in the metadata.
459 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
460 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000461 if (CodeGenOpts.ControlFlowGuard) {
462 // We want function ID tables for Control Flow Guard.
Hans Wennborga912e3e2018-08-10 09:49:21 +0000463 getModule().addModuleFlag(llvm::Module::Warning, "cfguardtable", 1);
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000464 }
Piotr Padlewski9d0ecf22015-09-15 21:46:50 +0000465 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
466 // We don't support LTO with 2 with different StrictVTablePointers
467 // FIXME: we could support it by stripping all the information introduced
468 // by StrictVTablePointers.
469
470 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
471
472 llvm::Metadata *Ops[2] = {
473 llvm::MDString::get(VMContext, "StrictVTablePointers"),
474 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
475 llvm::Type::getInt32Ty(VMContext), 1))};
476
477 getModule().addModuleFlag(llvm::Module::Require,
478 "StrictVTablePointersRequirement",
479 llvm::MDNode::get(VMContext, Ops));
480 }
Manman Ren4b7f23d2013-11-22 19:42:45 +0000481 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000482 // We support a single version in the linked module. The LLVM
483 // parser will drop debug info with a different version number
484 // (and warn about it, too).
485 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000486 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000487
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000488 // We need to record the widths of enums and wchar_t, so that we can generate
Matthias Brauna4519532017-05-20 01:29:55 +0000489 // the correct build attributes in the ARM backend. wchar_size is also used by
490 // TargetLibraryInfo.
Matthias Braunbffc1bb2017-09-26 02:37:23 +0000491 uint64_t WCharWidth =
492 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
Matthias Brauna4519532017-05-20 01:29:55 +0000493 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
494
Justin Bogner9bb7f152014-06-23 20:03:28 +0000495 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000496 if ( Arch == llvm::Triple::arm
497 || Arch == llvm::Triple::armeb
498 || Arch == llvm::Triple::thumb
499 || Arch == llvm::Triple::thumbeb) {
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000500 // The minimum width of an enum in bytes
501 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
502 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
503 }
504
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000505 if (CodeGenOpts.SanitizeCfiCrossDso) {
506 // Indicate that we want cross-DSO control flow integrity checks.
507 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
508 }
509
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +0000510 if (CodeGenOpts.CFProtectionReturn &&
511 Target.checkCFProtectionReturnSupported(getDiags())) {
512 // Indicate that we want to instrument return control flow protection.
513 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
514 1);
515 }
516
517 if (CodeGenOpts.CFProtectionBranch &&
518 Target.checkCFProtectionBranchSupported(getDiags())) {
519 // Indicate that we want to instrument branch control flow protection.
520 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
521 1);
522 }
523
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000524 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
Justin Lebard3a44f62016-04-05 18:26:20 +0000525 // Indicate whether __nvvm_reflect should be configured to flush denormal
526 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
527 // property.)
528 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
Yaxun Liue1bfbc52018-07-21 02:02:22 +0000529 CodeGenOpts.FlushDenorm ? 1 : 0);
Justin Lebard3a44f62016-04-05 18:26:20 +0000530 }
531
Alexey Bader364a1162017-06-20 14:30:18 +0000532 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
533 if (LangOpts.OpenCL) {
534 EmitOpenCLMetadata();
535 // Emit SPIR version.
536 if (getTriple().getArch() == llvm::Triple::spir ||
537 getTriple().getArch() == llvm::Triple::spir64) {
538 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
539 // opencl.spir.version named metadata.
540 llvm::Metadata *SPIRVerElts[] = {
541 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
542 Int32Ty, LangOpts.OpenCLVersion / 100)),
543 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
544 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
545 llvm::NamedMDNode *SPIRVerMD =
546 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
547 llvm::LLVMContext &Ctx = TheModule.getContext();
548 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
549 }
550 }
551
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000552 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
Sriraman Tallam70e70e62016-04-28 22:34:00 +0000553 assert(PLevel < 3 && "Invalid PIC Level");
554 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
Rafael Espindolac9d336e2016-06-23 15:07:32 +0000555 if (Context.getLangOpts().PIE)
556 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000557 }
558
Caroline Tice62279732018-09-21 18:34:59 +0000559 if (getCodeGenOpts().CodeModel.size() > 0) {
560 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
561 .Case("tiny", llvm::CodeModel::Tiny)
562 .Case("small", llvm::CodeModel::Small)
563 .Case("kernel", llvm::CodeModel::Kernel)
564 .Case("medium", llvm::CodeModel::Medium)
565 .Case("large", llvm::CodeModel::Large)
566 .Default(~0u);
567 if (CM != ~0u) {
568 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
569 getModule().setCodeModel(codeModel);
570 }
571 }
572
Sriraman Tallam80af0052018-02-23 21:27:33 +0000573 if (CodeGenOpts.NoPLT)
574 getModule().setRtLibUseGOT();
575
John McCall0bdb1fd2010-09-16 06:16:50 +0000576 SimplifyPersonality();
577
John McCall09ae0322010-07-06 23:57:41 +0000578 if (getCodeGenOpts().EmitDeclMetadata)
579 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000580
581 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000582 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000583
584 if (DebugInfo)
585 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000586
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +0000587 if (getCodeGenOpts().EmitVersionIdentMetadata)
588 EmitVersionIdentMetadata();
Robert Lytton57765d52014-07-03 09:30:33 +0000589
590 EmitTargetMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000591}
592
Alexey Bader364a1162017-06-20 14:30:18 +0000593void CodeGenModule::EmitOpenCLMetadata() {
594 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
595 // opencl.ocl.version named metadata node.
596 llvm::Metadata *OCLVerElts[] = {
597 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
598 Int32Ty, LangOpts.OpenCLVersion / 100)),
599 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
600 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
601 llvm::NamedMDNode *OCLVerMD =
602 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
603 llvm::LLVMContext &Ctx = TheModule.getContext();
604 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
605}
606
Devang Patel945b8ae2011-03-23 16:29:39 +0000607void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
608 // Make sure that this type is translated.
609 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000610}
611
David Majnemer929025d2016-01-26 19:30:26 +0000612void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
613 // Make sure that this type is translated.
614 Types.RefreshTypeCacheForClass(RD);
615}
616
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000617llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
Dan Gohman947c9af2010-10-14 23:06:10 +0000618 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000619 return nullptr;
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000620 return TBAA->getTypeInfo(QTy);
Dan Gohman947c9af2010-10-14 23:06:10 +0000621}
622
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000623TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
Ivan A. Kosarev124a2182018-02-20 12:33:04 +0000624 if (!TBAA)
625 return TBAAAccessInfo();
626 return TBAA->getAccessInfo(AccessType);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000627}
628
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000629TBAAAccessInfo
630CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000631 if (!TBAA)
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000632 return TBAAAccessInfo();
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000633 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000634}
635
Dan Gohman22695fc2012-09-28 21:58:29 +0000636llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
637 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000638 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000639 return TBAA->getTBAAStructInfo(QTy);
640}
641
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000642llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
643 if (!TBAA)
644 return nullptr;
645 return TBAA->getBaseTypeInfo(QTy);
646}
647
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000648llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
Manman Renc451e572013-04-04 21:53:22 +0000649 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000650 return nullptr;
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000651 return TBAA->getAccessTagInfo(Info);
Manman Renc451e572013-04-04 21:53:22 +0000652}
653
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000654TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
655 TBAAAccessInfo TargetInfo) {
656 if (!TBAA)
657 return TBAAAccessInfo();
658 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
659}
660
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +0000661TBAAAccessInfo
662CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
663 TBAAAccessInfo InfoB) {
664 if (!TBAA)
665 return TBAAAccessInfo();
666 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
667}
668
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000669TBAAAccessInfo
670CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
671 TBAAAccessInfo SrcInfo) {
672 if (!TBAA)
673 return TBAAAccessInfo();
674 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
675}
676
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000677void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000678 TBAAAccessInfo TBAAInfo) {
679 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
680 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
Dan Gohman947c9af2010-10-14 23:06:10 +0000681}
682
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000683void CodeGenModule::DecorateInstructionWithInvariantGroup(
684 llvm::Instruction *I, const CXXRecordDecl *RD) {
Piotr Padlewski34046bd2017-04-24 12:58:43 +0000685 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
686 llvm::MDNode::get(getLLVMContext(), {}));
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000687}
688
Alp Toker29cb66b2014-01-26 06:17:37 +0000689void CodeGenModule::Error(SourceLocation loc, StringRef message) {
690 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
691 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000692}
693
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000694/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000695/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000696void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000697 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000698 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000699 std::string Msg = Type;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000700 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
701 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000702}
Chris Lattner41af8182007-12-02 06:27:33 +0000703
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000704/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000705/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000706void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000707 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000708 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000709 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000710 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000711}
712
John McCall23c29fe2011-06-24 21:55:10 +0000713llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
714 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
715}
716
Mike Stump11289f42009-09-09 15:08:12 +0000717void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000718 const NamedDecl *D) const {
Rafael Espindola123ce972018-01-24 18:58:32 +0000719 if (GV->hasDLLImportStorageClass())
720 return;
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000721 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000722 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000723 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000724 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000725 }
Rafael Espindola3f727a82018-03-14 18:14:46 +0000726 if (!D)
727 return;
John McCallc273f242010-10-30 11:50:40 +0000728 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000729 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000730 if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
Rafael Espindola4a5da442013-02-27 02:56:45 +0000731 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000732}
733
Rafael Espindola699f5d62018-02-07 22:15:33 +0000734static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
Rafael Espindola3dd49812018-02-23 00:22:15 +0000735 llvm::GlobalValue *GV) {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000736 if (GV->hasLocalLinkage())
737 return true;
738
739 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
740 return true;
741
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000742 // DLLImport explicitly marks the GV as external.
743 if (GV->hasDLLImportStorageClass())
744 return false;
745
Rafael Espindola699f5d62018-02-07 22:15:33 +0000746 const llvm::Triple &TT = CGM.getTriple();
Martin Storsjo5ff7a8e2018-08-29 17:26:58 +0000747 if (TT.isWindowsGNUEnvironment()) {
748 // In MinGW, variables without DLLImport can still be automatically
749 // imported from a DLL by the linker; don't mark variables that
750 // potentially could come from another DLL as DSO local.
751 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
752 !GV->isThreadLocal())
753 return false;
754 }
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000755 // Every other GV is local on COFF.
756 // Make an exception for windows OS in the triple: Some firmware builds use
757 // *-win32-macho triples. This (accidentally?) produced windows relocations
758 // without GOT tables in older clang versions; Keep this behaviour.
759 // FIXME: even thread local variables?
760 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
761 return true;
762
763 // Only handle COFF and ELF for now.
Rafael Espindola699f5d62018-02-07 22:15:33 +0000764 if (!TT.isOSBinFormatELF())
765 return false;
766
767 // If this is not an executable, don't assume anything is local.
768 const auto &CGOpts = CGM.getCodeGenOpts();
769 llvm::Reloc::Model RM = CGOpts.RelocationModel;
770 const auto &LOpts = CGM.getLangOpts();
771 if (RM != llvm::Reloc::Static && !LOpts.PIE)
772 return false;
773
774 // A definition cannot be preempted from an executable.
775 if (!GV->isDeclarationForLinker())
776 return true;
777
778 // Most PIC code sequences that assume that a symbol is local cannot produce a
779 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
780 // depended, it seems worth it to handle it here.
781 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
782 return false;
783
784 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
785 llvm::Triple::ArchType Arch = TT.getArch();
786 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
787 Arch == llvm::Triple::ppc64le)
788 return false;
789
790 // If we can use copy relocations we can assume it is local.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000791 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
792 if (!Var->isThreadLocal() &&
Rafael Espindola75e57362018-02-07 23:04:06 +0000793 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
794 return true;
Rafael Espindola699f5d62018-02-07 22:15:33 +0000795
796 // If we can use a plt entry as the symbol address we can assume it
797 // is local.
798 // FIXME: This should work for PIE, but the gold linker doesn't support it.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000799 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
Rafael Espindola699f5d62018-02-07 22:15:33 +0000800 return true;
801
802 // Otherwise don't assue it is local.
803 return false;
804}
805
Rafael Espindola3dd49812018-02-23 00:22:15 +0000806void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000807 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
Rafael Espindola699f5d62018-02-07 22:15:33 +0000808}
809
Rafael Espindolab7350042018-03-01 00:35:47 +0000810void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
811 GlobalDecl GD) const {
812 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
Reid Klecknerae9b0702018-03-16 19:40:50 +0000813 // C++ destructors have a few C++ ABI specific special cases.
Rafael Espindolab7350042018-03-01 00:35:47 +0000814 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
Reid Klecknerae9b0702018-03-16 19:40:50 +0000815 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
816 return;
Rafael Espindolab7350042018-03-01 00:35:47 +0000817 }
818 setDLLImportDLLExport(GV, D);
819}
820
821void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
822 const NamedDecl *D) const {
Rafael Espindola3f727a82018-03-14 18:14:46 +0000823 if (D && D->isExternallyVisible()) {
Rafael Espindolab7350042018-03-01 00:35:47 +0000824 if (D->hasAttr<DLLImportAttr>())
825 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
826 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
827 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
828 }
829}
830
831void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
832 GlobalDecl GD) const {
833 setDLLImportDLLExport(GV, GD);
834 setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
835}
836
Rafael Espindola699f5d62018-02-07 22:15:33 +0000837void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
838 const NamedDecl *D) const {
Rafael Espindolab7350042018-03-01 00:35:47 +0000839 setDLLImportDLLExport(GV, D);
840 setGlobalVisibilityAndLocal(GV, D);
841}
842
843void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
844 const NamedDecl *D) const {
Rafael Espindola699f5d62018-02-07 22:15:33 +0000845 setGlobalVisibility(GV, D);
Rafael Espindola3dd49812018-02-23 00:22:15 +0000846 setDSOLocal(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +0000847}
848
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000849static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
850 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
851 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
852 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
853 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
854 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
855}
856
857static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
858 CodeGenOptions::TLSModel M) {
859 switch (M) {
860 case CodeGenOptions::GeneralDynamicTLSModel:
861 return llvm::GlobalVariable::GeneralDynamicTLSModel;
862 case CodeGenOptions::LocalDynamicTLSModel:
863 return llvm::GlobalVariable::LocalDynamicTLSModel;
864 case CodeGenOptions::InitialExecTLSModel:
865 return llvm::GlobalVariable::InitialExecTLSModel;
866 case CodeGenOptions::LocalExecTLSModel:
867 return llvm::GlobalVariable::LocalExecTLSModel;
868 }
869 llvm_unreachable("Invalid TLS model!");
870}
871
David Majnemerbb525f7c2014-10-15 22:38:23 +0000872void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000873 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000874
David Majnemerbb525f7c2014-10-15 22:38:23 +0000875 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000876 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000877
878 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000879 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000880 TLM = GetLLVMTLSModel(Attr->getModel());
881 }
882
883 GV->setThreadLocalMode(TLM);
884}
885
Erich Keane3efe0022018-07-20 14:13:28 +0000886static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
887 StringRef Name) {
888 const TargetInfo &Target = CGM.getTarget();
889 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
890}
891
892static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
893 const CPUSpecificAttr *Attr,
894 raw_ostream &Out) {
Erich Keane19a8adc2018-10-25 18:57:19 +0000895 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
896 // supported.
Erich Keane3efe0022018-07-20 14:13:28 +0000897 if (Attr)
898 Out << getCPUSpecificMangling(CGM, Attr->getCurCPUName()->getName());
Erich Keane19a8adc2018-10-25 18:57:19 +0000899 else if (CGM.getTarget().supportsIFunc())
Erich Keane3efe0022018-07-20 14:13:28 +0000900 Out << ".resolver";
901}
902
Erich Keane281d20b2018-01-08 21:34:17 +0000903static void AppendTargetMangling(const CodeGenModule &CGM,
904 const TargetAttr *Attr, raw_ostream &Out) {
905 if (Attr->isDefaultVersion())
906 return;
907
908 Out << '.';
Erich Keane3efe0022018-07-20 14:13:28 +0000909 const TargetInfo &Target = CGM.getTarget();
Erich Keane281d20b2018-01-08 21:34:17 +0000910 TargetAttr::ParsedTargetAttr Info =
911 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
Erich Keane3efe0022018-07-20 14:13:28 +0000912 // Multiversioning doesn't allow "no-${feature}", so we can
913 // only have "+" prefixes here.
914 assert(LHS.startswith("+") && RHS.startswith("+") &&
915 "Features should always have a prefix.");
916 return Target.multiVersionSortPriority(LHS.substr(1)) >
917 Target.multiVersionSortPriority(RHS.substr(1));
918 });
Erich Keane281d20b2018-01-08 21:34:17 +0000919
920 bool IsFirst = true;
921
922 if (!Info.Architecture.empty()) {
923 IsFirst = false;
924 Out << "arch_" << Info.Architecture;
925 }
926
927 for (StringRef Feat : Info.Features) {
928 if (!IsFirst)
929 Out << '_';
930 IsFirst = false;
931 Out << Feat.substr(1);
932 }
933}
934
935static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
936 const NamedDecl *ND,
Erich Keane3efe0022018-07-20 14:13:28 +0000937 bool OmitMultiVersionMangling = false) {
Erich Keane281d20b2018-01-08 21:34:17 +0000938 SmallString<256> Buffer;
939 llvm::raw_svector_ostream Out(Buffer);
940 MangleContext &MC = CGM.getCXXABI().getMangleContext();
941 if (MC.shouldMangleDeclName(ND)) {
942 llvm::raw_svector_ostream Out(Buffer);
943 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
944 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
945 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
946 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
947 else
948 MC.mangleName(ND, Out);
949 } else {
950 IdentifierInfo *II = ND->getIdentifier();
951 assert(II && "Attempt to mangle unnamed decl.");
952 const auto *FD = dyn_cast<FunctionDecl>(ND);
953
954 if (FD &&
955 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
956 llvm::raw_svector_ostream Out(Buffer);
957 Out << "__regcall3__" << II->getName();
958 } else {
959 Out << II->getName();
960 }
961 }
962
963 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Erich Keane3efe0022018-07-20 14:13:28 +0000964 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
965 if (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())
966 AppendCPUSpecificCPUDispatchMangling(
967 CGM, FD->getAttr<CPUSpecificAttr>(), Out);
968 else
969 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
970 }
971
Erich Keane281d20b2018-01-08 21:34:17 +0000972 return Out.str();
973}
974
975void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
976 const FunctionDecl *FD) {
977 if (!FD->isMultiVersion())
978 return;
979
980 // Get the name of what this would be without the 'target' attribute. This
981 // allows us to lookup the version that was emitted when this wasn't a
982 // multiversion function.
983 std::string NonTargetName =
Erich Keane3efe0022018-07-20 14:13:28 +0000984 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
Erich Keane281d20b2018-01-08 21:34:17 +0000985 GlobalDecl OtherGD;
986 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
987 assert(OtherGD.getCanonicalDecl()
988 .getDecl()
989 ->getAsFunction()
990 ->isMultiVersion() &&
991 "Other GD should now be a multiversioned function");
992 // OtherFD is the version of this function that was mangled BEFORE
993 // becoming a MultiVersion function. It potentially needs to be updated.
994 const FunctionDecl *OtherFD =
995 OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
996 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
997 // This is so that if the initial version was already the 'default'
998 // version, we don't try to update it.
999 if (OtherName != NonTargetName) {
Erich Keanebc40c5c2018-01-09 01:09:12 +00001000 // Remove instead of erase, since others may have stored the StringRef
1001 // to this.
1002 const auto ExistingRecord = Manglings.find(NonTargetName);
1003 if (ExistingRecord != std::end(Manglings))
1004 Manglings.remove(&(*ExistingRecord));
Erich Keane281d20b2018-01-08 21:34:17 +00001005 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1006 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1007 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1008 Entry->setName(OtherName);
1009 }
1010 }
1011}
1012
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001013StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
David Majnemerd2385c02016-01-08 20:48:26 +00001014 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1015
1016 // Some ABIs don't have constructor variants. Make sure that base and
1017 // complete constructors get mangled the same.
1018 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1019 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1020 CXXCtorType OrigCtorType = GD.getCtorType();
1021 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1022 if (OrigCtorType == Ctor_Base)
1023 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1024 }
1025 }
1026
Erich Keane3efe0022018-07-20 14:13:28 +00001027 const auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
1028 // Since CPUSpecific can require multiple emits per decl, store the manglings
1029 // separately.
1030 if (FD &&
1031 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())) {
1032 const auto *SD = FD->getAttr<CPUSpecificAttr>();
1033
1034 std::pair<GlobalDecl, unsigned> SpecCanonicalGD{
1035 CanonicalGD,
1036 SD ? SD->ActiveArgIndex : std::numeric_limits<unsigned>::max()};
1037
1038 auto FoundName = CPUSpecificMangledDeclNames.find(SpecCanonicalGD);
1039 if (FoundName != CPUSpecificMangledDeclNames.end())
1040 return FoundName->second;
1041
1042 auto Result = CPUSpecificManglings.insert(
1043 std::make_pair(getMangledNameImpl(*this, GD, FD), SpecCanonicalGD));
1044 return CPUSpecificMangledDeclNames[SpecCanonicalGD] = Result.first->first();
1045 }
1046
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +00001047 auto FoundName = MangledDeclNames.find(CanonicalGD);
1048 if (FoundName != MangledDeclNames.end())
1049 return FoundName->second;
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001050
Richard Smith6d0e97a2014-08-02 00:50:16 +00001051 // Keep the first result in the case of a mangling collision.
Erich Keane281d20b2018-01-08 21:34:17 +00001052 const auto *ND = cast<NamedDecl>(GD.getDecl());
1053 auto Result =
1054 Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +00001055 return MangledDeclNames[CanonicalGD] = Result.first->first();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +00001056}
1057
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001058StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1059 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001060 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1061 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +00001062
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001063 SmallString<256> Buffer;
1064 llvm::raw_svector_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +00001065 if (!D)
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001066 MangleCtx.mangleGlobalBlock(BD,
Fariborz Jahanian63628032012-06-26 16:06:38 +00001067 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001068 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001069 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001070 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001071 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001072 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001073 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001074
Richard Smith6d0e97a2014-08-02 00:50:16 +00001075 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1076 return Result.first->first();
Anders Carlsson635186a2010-06-09 02:36:32 +00001077}
1078
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001079llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +00001080 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +00001081}
1082
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001083/// AddGlobalCtor - Add a function to the list that will be called before
1084/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001085void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1086 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +00001087 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001088 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001089}
1090
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001091/// AddGlobalDtor - Add a function to the list that will be called
1092/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001093void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Akira Hatanaka617e2612018-04-17 18:41:52 +00001094 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1095 DtorsUsingAtExit[Priority].push_back(Dtor);
1096 return;
1097 }
1098
Daniel Dunbardec798b2009-01-13 02:25:00 +00001099 // FIXME: Type coercion of void()* types.
Craig Topper4b566922014-06-09 02:04:02 +00001100 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001101}
1102
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001103void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001104 if (Fns.empty()) return;
1105
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001106 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +00001107 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001108 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001109
Reid Kleckner563f0e82014-05-23 21:13:45 +00001110 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1111 llvm::StructType *CtorStructTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00001112 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001113
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001114 // Construct the constructor and destructor arrays.
John McCall23c9dc62016-11-28 22:18:27 +00001115 ConstantInitBuilder builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001116 auto ctors = builder.beginArray(CtorStructTy);
Yaron Kerenb54db522015-06-11 12:33:25 +00001117 for (const auto &I : Fns) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001118 auto ctor = ctors.beginStruct(CtorStructTy);
1119 ctor.addInt(Int32Ty, I.Priority);
1120 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1121 if (I.AssociatedData)
1122 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1123 else
1124 ctor.addNullPointer(VoidPtrTy);
John McCallf1788632016-11-28 22:18:30 +00001125 ctor.finishAndAddTo(ctors);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001126 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001127
John McCall18081af2016-11-19 20:12:25 +00001128 auto list =
1129 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1130 /*constant*/ false,
1131 llvm::GlobalValue::AppendingLinkage);
1132
1133 // The LTO linker doesn't seem to like it when we set an alignment
1134 // on appending variables. Take it off as a workaround.
1135 list->setAlignment(0);
1136
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001137 Fns.clear();
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001138}
1139
John McCalld4324142010-02-19 01:32:20 +00001140llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001141CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001142 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +00001143
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001144 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +00001145
Reid Klecknerae9b0702018-03-16 19:40:50 +00001146 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1147 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
Reid Klecknera283e482017-12-21 19:44:23 +00001148
Richard Smith5179eb72016-06-28 19:03:57 +00001149 if (isa<CXXConstructorDecl>(D) &&
1150 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1151 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1152 // Our approach to inheriting constructors is fundamentally different from
1153 // that used by the MS ABI, so keep our inheriting constructor thunks
1154 // internal rather than trying to pick an unambiguous mangling for them.
1155 return llvm::GlobalValue::InternalLinkage;
1156 }
1157
Hans Wennborg275efb92014-05-28 01:52:23 +00001158 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +00001159}
Nuno Lopesb6f79532008-06-08 15:45:52 +00001160
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001161llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001162 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1163 if (!MDS) return nullptr;
1164
Benjamin Kramer630cf8c2016-11-23 11:20:27 +00001165 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001166}
1167
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001168void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +00001169 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001170 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001171 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +00001172 llvm::AttributeList PAL;
1173 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
1174 F->setAttributes(PAL);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001175 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +00001176}
1177
John McCall9b0a7ce2011-10-02 01:16:38 +00001178/// Determines whether the language options require us to model
1179/// unwind exceptions. We treat -fexceptions as mandating this
1180/// except under the fragile ObjC ABI with only ObjC exceptions
1181/// enabled. This means, for example, that C with -fexceptions
1182/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001183static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +00001184 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001185 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +00001186
1187 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001188 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +00001189
1190 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001191 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +00001192 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +00001193 }
1194
1195 return true;
1196}
1197
Peter Collingbournee44acad2018-06-26 02:15:47 +00001198static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1199 const CXXMethodDecl *MD) {
1200 // Check that the type metadata can ever actually be used by a call.
1201 if (!CGM.getCodeGenOpts().LTOUnit ||
1202 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1203 return false;
1204
1205 // Only functions whose address can be taken with a member function pointer
1206 // need this sort of type metadata.
1207 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1208 !isa<CXXDestructorDecl>(MD);
1209}
1210
1211std::vector<const CXXRecordDecl *>
1212CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1213 llvm::SetVector<const CXXRecordDecl *> MostBases;
1214
1215 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1216 CollectMostBases = [&](const CXXRecordDecl *RD) {
1217 if (RD->getNumBases() == 0)
1218 MostBases.insert(RD);
1219 for (const CXXBaseSpecifier &B : RD->bases())
1220 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1221 };
1222 CollectMostBases(RD);
1223 return MostBases.takeVector();
1224}
1225
Daniel Dunbar38932572009-04-14 08:05:55 +00001226void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1227 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001228 llvm::AttrBuilder B;
1229
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001230 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001231 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001232
David Blaikiebbafb8a2012-03-11 07:00:24 +00001233 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001234 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +00001235
Manoj Gupta4fbf84c2018-05-09 21:41:18 +00001236 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1237 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1238 B.addAttribute(llvm::Attribute::StackProtect);
1239 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1240 B.addAttribute(llvm::Attribute::StackProtectStrong);
1241 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1242 B.addAttribute(llvm::Attribute::StackProtectReq);
1243 }
Akira Hatanaka200500d2015-10-08 19:30:57 +00001244
1245 if (!D) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001246 // If we don't have a declaration to control inlining, the function isn't
1247 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1248 // disabled, mark the function as noinline.
1249 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1250 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1251 B.addAttribute(llvm::Attribute::NoInline);
1252
Reid Kleckneree4930b2017-05-02 22:07:37 +00001253 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Akira Hatanaka200500d2015-10-08 19:30:57 +00001254 return;
1255 }
1256
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001257 // Track whether we need to add the optnone LLVM attribute,
1258 // starting with the default for this optimization level.
1259 bool ShouldAddOptNone =
1260 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1261 // We can't add optnone in the following cases, it won't pass the verifier.
1262 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1263 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1264 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1265
1266 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001267 B.addAttribute(llvm::Attribute::OptimizeNone);
1268
1269 // OptimizeNone implies noinline; we should not be inlining such functions.
1270 B.addAttribute(llvm::Attribute::NoInline);
1271 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1272 "OptimizeNone and AlwaysInline on same function!");
1273
1274 // We still need to handle naked functions even though optnone subsumes
1275 // much of their semantics.
1276 if (D->hasAttr<NakedAttr>())
1277 B.addAttribute(llvm::Attribute::Naked);
1278
1279 // OptimizeNone wins over OptimizeForSize and MinSize.
1280 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1281 F->removeFnAttr(llvm::Attribute::MinSize);
1282 } else if (D->hasAttr<NakedAttr>()) {
Eli Friedmanc55efe42011-08-22 23:55:33 +00001283 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001284 B.addAttribute(llvm::Attribute::Naked);
1285 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001286 } else if (D->hasAttr<NoDuplicateAttr>()) {
1287 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001288 } else if (D->hasAttr<NoInlineAttr>()) {
1289 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +00001290 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Chandler Carruthfcd33142016-12-23 01:24:49 +00001291 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001292 // (noinline wins over always_inline, and we can't specify both in IR)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001293 B.addAttribute(llvm::Attribute::AlwaysInline);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001294 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1295 // If we're not inlining, then force everything that isn't always_inline to
1296 // carry an explicit noinline attribute.
1297 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1298 B.addAttribute(llvm::Attribute::NoInline);
1299 } else {
1300 // Otherwise, propagate the inline hint attribute and potentially use its
1301 // absence to mark things as noinline.
1302 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Trieu9b36a9c2018-10-23 01:26:28 +00001303 // Search function and template pattern redeclarations for inline.
1304 auto CheckForInline = [](const FunctionDecl *FD) {
1305 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1306 return Redecl->isInlineSpecified();
1307 };
1308 if (any_of(FD->redecls(), CheckRedeclForInline))
1309 return true;
1310 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1311 if (!Pattern)
1312 return false;
1313 return any_of(Pattern->redecls(), CheckRedeclForInline);
1314 };
1315 if (CheckForInline(FD)) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001316 B.addAttribute(llvm::Attribute::InlineHint);
1317 } else if (CodeGenOpts.getInlining() ==
1318 CodeGenOptions::OnlyHintInlining &&
1319 !FD->isInlined() &&
1320 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1321 B.addAttribute(llvm::Attribute::NoInline);
1322 }
1323 }
Eli Friedmanc55efe42011-08-22 23:55:33 +00001324 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +00001325
Chandler Carruthfcd33142016-12-23 01:24:49 +00001326 // Add other optimization related attributes if we are optimizing this
1327 // function.
1328 if (!D->hasAttr<OptimizeNoneAttr>()) {
1329 if (D->hasAttr<ColdAttr>()) {
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001330 if (!ShouldAddOptNone)
1331 B.addAttribute(llvm::Attribute::OptimizeForSize);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001332 B.addAttribute(llvm::Attribute::Cold);
1333 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001334
Chandler Carruthfcd33142016-12-23 01:24:49 +00001335 if (D->hasAttr<MinSizeAttr>())
1336 B.addAttribute(llvm::Attribute::MinSize);
1337 }
Richard Smithb555a762012-09-28 22:46:07 +00001338
Reid Kleckneree4930b2017-05-02 22:07:37 +00001339 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001340
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001341 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1342 if (alignment)
1343 F->setAlignment(alignment);
1344
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00001345 if (!D->hasAttr<AlignedAttr>())
1346 if (LangOpts.FunctionAlignment)
1347 F->setAlignment(1 << LangOpts.FunctionAlignment);
1348
Dan Gohmanc2853072015-09-03 22:51:53 +00001349 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1350 // reserve a bit for differentiating between virtual and non-virtual member
1351 // functions. If the current target's C++ ABI requires this and this is a
1352 // member function, set its alignment accordingly.
1353 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1354 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1355 F->setAlignment(2);
1356 }
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001357
1358 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1359 if (CodeGenOpts.SanitizeCfiCrossDso)
1360 if (auto *FD = dyn_cast<FunctionDecl>(D))
Peter Collingbournee44acad2018-06-26 02:15:47 +00001361 CreateFunctionTypeMetadataForIcall(FD, F);
1362
1363 // Emit type metadata on member functions for member function pointer checks.
1364 // These are only ever necessary on definitions; we're guaranteed that the
1365 // definition will be present in the LTO unit as a result of LTO visibility.
1366 auto *MD = dyn_cast<CXXMethodDecl>(D);
1367 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1368 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1369 llvm::Metadata *Id =
1370 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1371 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1372 F->addTypeMetadata(0, Id);
1373 }
1374 }
Daniel Dunbar449a3392008-09-04 23:41:35 +00001375}
1376
Rafael Espindola75c649c2018-03-01 00:06:55 +00001377void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1378 const Decl *D = GD.getDecl();
Rafael Espindolab7350042018-03-01 00:35:47 +00001379 if (dyn_cast_or_null<NamedDecl>(D))
1380 setGVProperties(GV, GD);
John McCall457a04e2010-10-22 21:05:15 +00001381 else
1382 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +00001383
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001384 if (D && D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +00001385 addUsedGlobal(GV);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00001386
1387 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1388 const auto *VD = cast<VarDecl>(D);
1389 if (VD->getType().isConstQualified() && VD->getStorageClass() == SC_Static)
1390 addUsedGlobal(GV);
1391 }
Rafael Espindola502f65a2014-05-05 20:21:03 +00001392}
1393
Erich Keane93e58662018-02-12 17:01:41 +00001394bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
1395 llvm::AttrBuilder &Attrs) {
1396 // Add target-cpu and target-features attributes to functions. If
1397 // we have a decl for the function and it has a target attribute then
1398 // parse that and add it to the feature set.
1399 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1400 std::vector<std::string> Features;
1401 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
1402 FD = FD ? FD->getMostRecentDecl() : FD;
1403 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
Erich Keane3efe0022018-07-20 14:13:28 +00001404 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
Erich Keane93e58662018-02-12 17:01:41 +00001405 bool AddedAttr = false;
Erich Keane3efe0022018-07-20 14:13:28 +00001406 if (TD || SD) {
Erich Keane93e58662018-02-12 17:01:41 +00001407 llvm::StringMap<bool> FeatureMap;
1408 getFunctionFeatureMap(FeatureMap, FD);
1409
1410 // Produce the canonical string for this set of features.
1411 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1412 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1413
1414 // Now add the target-cpu and target-features to the function.
1415 // While we populated the feature map above, we still need to
1416 // get and parse the target attribute so we can get the cpu for
1417 // the function.
Erich Keane3efe0022018-07-20 14:13:28 +00001418 if (TD) {
1419 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1420 if (ParsedAttr.Architecture != "" &&
1421 getTarget().isValidCPUName(ParsedAttr.Architecture))
1422 TargetCPU = ParsedAttr.Architecture;
1423 }
Erich Keane93e58662018-02-12 17:01:41 +00001424 } else {
1425 // Otherwise just add the existing target cpu and target features to the
1426 // function.
1427 Features = getTarget().getTargetOpts().Features;
1428 }
1429
1430 if (TargetCPU != "") {
1431 Attrs.addAttribute("target-cpu", TargetCPU);
1432 AddedAttr = true;
1433 }
1434 if (!Features.empty()) {
Fangrui Song55fab262018-09-26 22:16:28 +00001435 llvm::sort(Features);
Erich Keane93e58662018-02-12 17:01:41 +00001436 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1437 AddedAttr = true;
1438 }
1439
1440 return AddedAttr;
1441}
1442
Rafael Espindola285271c2018-02-28 23:54:23 +00001443void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
Rafael Espindolaee076a22014-05-13 18:45:53 +00001444 llvm::GlobalObject *GO) {
Rafael Espindola285271c2018-02-28 23:54:23 +00001445 const Decl *D = GD.getDecl();
Rafael Espindola75c649c2018-03-01 00:06:55 +00001446 SetCommonAttributes(GD, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +00001447
Javed Absar2a67c9e2017-06-05 10:11:57 +00001448 if (D) {
1449 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1450 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1451 GV->addAttribute("bss-section", SA->getName());
1452 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1453 GV->addAttribute("data-section", SA->getName());
1454 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1455 GV->addAttribute("rodata-section", SA->getName());
1456 }
1457
1458 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1459 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
Erich Keane30994d22018-02-08 20:04:22 +00001460 if (!D->getAttr<SectionAttr>())
1461 F->addFnAttr("implicit-section-name", SA->getName());
Erich Keane93e58662018-02-12 17:01:41 +00001462
1463 llvm::AttrBuilder Attrs;
1464 if (GetCPUAndFeaturesAttributes(D, Attrs)) {
1465 // We know that GetCPUAndFeaturesAttributes will always have the
1466 // newest set, since it has the newest possible FunctionDecl, so the
1467 // new ones should replace the old.
1468 F->removeFnAttr("target-cpu");
1469 F->removeFnAttr("target-features");
1470 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1471 }
Javed Absar2a67c9e2017-06-05 10:11:57 +00001472 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001473
Erich Keane7963e8b2018-07-18 20:04:48 +00001474 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1475 GO->setSection(CSA->getName());
1476 else if (const auto *SA = D->getAttr<SectionAttr>())
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001477 GO->setSection(SA->getName());
Javed Absar2a67c9e2017-06-05 10:11:57 +00001478 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001479
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001480 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +00001481}
1482
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001483void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001484 llvm::Function *F,
1485 const CGFunctionInfo &FI) {
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001486 const Decl *D = GD.getDecl();
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001487 SetLLVMFunctionAttributes(D, FI, F);
1488 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +00001489
1490 F->setLinkage(llvm::Function::InternalLinkage);
1491
Rafael Espindola285271c2018-02-28 23:54:23 +00001492 setNonAliasAttributes(GD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001493}
1494
Rafael Espindolab7350042018-03-01 00:35:47 +00001495static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
David Majnemerf6acb762014-04-25 17:07:16 +00001496 // Set linkage and visibility in case we never see a definition.
1497 LinkageInfo LV = ND->getLinkageAndVisibility();
Rafael Espindolab7350042018-03-01 00:35:47 +00001498 // Don't set internal linkage on declarations.
1499 // "extern_weak" is overloaded in LLVM; we probably should have
1500 // separate linkage types for this.
1501 if (isExternallyVisible(LV.getLinkage()) &&
1502 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1503 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
David Majnemerf6acb762014-04-25 17:07:16 +00001504}
1505
Peter Collingbournee44acad2018-06-26 02:15:47 +00001506void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1507 llvm::Function *F) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001508 // Only if we are checking indirect calls.
1509 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1510 return;
1511
Peter Collingbournee44acad2018-06-26 02:15:47 +00001512 // Non-static class methods are handled via vtable or member function pointer
1513 // checks elsewhere.
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001514 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1515 return;
1516
1517 // Additionally, if building with cross-DSO support...
1518 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001519 // Skip available_externally functions. They won't be codegen'ed in the
1520 // current module anyway.
1521 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1522 return;
1523 }
1524
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001525 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001526 F->addTypeMetadata(0, MD);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00001527 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001528
1529 // Emit a hash-based bit set entry for cross-DSO calls.
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001530 if (CodeGenOpts.SanitizeCfiCrossDso)
1531 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1532 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001533}
1534
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001535void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1536 bool IsIncompleteFunction,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001537 bool IsThunk) {
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001538
Pete Cooper2f1637a2015-05-20 17:17:45 +00001539 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001540 // If this is an intrinsic function, set the function's attributes
1541 // to the intrinsic's attributes.
Pete Cooper2f1637a2015-05-20 17:17:45 +00001542 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001543 return;
1544 }
1545
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001546 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +00001547
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001548 if (!IsIncompleteFunction) {
John McCalla729c622012-02-17 03:33:10 +00001549 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001550 // Setup target-specific attributes.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001551 if (F->isDeclaration())
1552 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001553 }
Mike Stump11289f42009-09-09 15:08:12 +00001554
Bob Wilsonfc6297f2014-04-01 01:38:16 +00001555 // Add the Returned attribute for "this", except for iOS 5 and earlier
1556 // where substantial code, including the libstdc++ dylib, was compiled with
1557 // GCC and does not actually return "this".
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001558 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00001559 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001560 assert(!F->arg_empty() &&
1561 F->arg_begin()->getType()
1562 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1563 "unexpected this return");
1564 F->addAttribute(1, llvm::Attribute::Returned);
1565 }
1566
Daniel Dunbar38932572009-04-14 08:05:55 +00001567 // Only a few attributes are set on declarations; these may later be
1568 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +00001569
Jake Ehrlichba874ad2017-11-29 00:54:20 +00001570 setLinkageForGV(F, FD);
Rafael Espindola699f5d62018-02-07 22:15:33 +00001571 setGVProperties(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +00001572
Erich Keane7963e8b2018-07-18 20:04:48 +00001573 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1574 F->setSection(CSA->getName());
1575 else if (const auto *SA = FD->getAttr<SectionAttr>())
1576 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +00001577
Richard Smith351241c2016-04-07 21:46:12 +00001578 if (FD->isReplaceableGlobalAllocationFunction()) {
1579 // A replaceable global allocation function does not act like a builtin by
1580 // default, only if it is invoked by a new-expression or delete-expression.
Reid Klecknerde864822017-03-21 16:57:30 +00001581 F->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001582 llvm::Attribute::NoBuiltin);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001583
Richard Smith351241c2016-04-07 21:46:12 +00001584 // A sane operator new returns a non-aliasing pointer.
1585 // FIXME: Also add NonNull attribute to the return value
1586 // for the non-nothrow forms?
1587 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1588 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1589 (Kind == OO_New || Kind == OO_Array_New))
Reid Klecknerde864822017-03-21 16:57:30 +00001590 F->addAttribute(llvm::AttributeList::ReturnIndex,
Richard Smith351241c2016-04-07 21:46:12 +00001591 llvm::Attribute::NoAlias);
1592 }
1593
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001594 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001595 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001596 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1597 if (MD->isVirtual())
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001598 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001599
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001600 // Don't emit entries for function declarations in the cross-DSO mode. This
1601 // is handled with better precision by the receiving DSO.
1602 if (!CodeGenOpts.SanitizeCfiCrossDso)
Peter Collingbournee44acad2018-06-26 02:15:47 +00001603 CreateFunctionTypeMetadataForIcall(FD, F);
Alexey Bataevb952e632017-12-15 16:28:31 +00001604
1605 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1606 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001607}
1608
Rafael Espindola060062a2014-03-06 22:15:10 +00001609void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +00001610 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001611 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001612 LLVMUsed.emplace_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001613}
1614
Rafael Espindola060062a2014-03-06 22:15:10 +00001615void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1616 assert(!GV->isDeclaration() &&
1617 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001618 LLVMCompilerUsed.emplace_back(GV);
Rafael Espindola060062a2014-03-06 22:15:10 +00001619}
1620
1621static void emitUsed(CodeGenModule &CGM, StringRef Name,
Sanjoy Dase369bd92017-05-01 17:08:00 +00001622 std::vector<llvm::WeakTrackingVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001623 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +00001624 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001625 return;
1626
Rafael Espindola060062a2014-03-06 22:15:10 +00001627 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +00001628 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +00001629 UsedArray.resize(List.size());
1630 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001631 UsedArray[i] =
Justin Holewinskif37f3d32015-02-02 21:05:49 +00001632 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1633 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +00001634 }
Mike Stump11289f42009-09-09 15:08:12 +00001635
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001636 if (UsedArray.empty())
1637 return;
Rafael Espindola060062a2014-03-06 22:15:10 +00001638 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +00001639
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001640 auto *GV = new llvm::GlobalVariable(
1641 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1642 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001643
1644 GV->setSection("llvm.metadata");
1645}
1646
Rafael Espindola060062a2014-03-06 22:15:10 +00001647void CodeGenModule::emitLLVMUsed() {
1648 emitUsed(*this, "llvm.used", LLVMUsed);
1649 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1650}
1651
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001652void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001653 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001654 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1655}
1656
Aaron Ballman5d041be2013-06-04 02:07:14 +00001657void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1658 llvm::SmallString<32> Opt;
1659 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001660 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballman5d041be2013-06-04 02:07:14 +00001661 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1662}
1663
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00001664void CodeGenModule::AddELFLibDirective(StringRef Lib) {
1665 auto &C = getLLVMContext();
1666 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1667 C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1668}
1669
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001670void CodeGenModule::AddDependentLib(StringRef Lib) {
1671 llvm::SmallString<24> Opt;
1672 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001673 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001674 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1675}
1676
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001677/// Add link options implied by the given module, including modules
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001678/// it depends on, using a postorder walk.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001679static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
Peter Collingbourne89061b22017-06-12 20:10:48 +00001680 SmallVectorImpl<llvm::MDNode *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001681 llvm::SmallPtrSet<Module *, 16> &Visited) {
1682 // Import this module's parent.
David Blaikie82e95a32014-11-19 07:49:47 +00001683 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001684 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001685 }
1686
1687 // Import this module's dependencies.
1688 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001689 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001690 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001691 }
1692
1693 // Add linker options to link against the libraries/frameworks
1694 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001695 llvm::LLVMContext &Context = CGM.getLLVMContext();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00001696
1697 // For modules that use export_as for linking, use that module
1698 // name instead.
1699 if (Mod->UseExportAsModuleLinkName)
1700 return;
1701
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001702 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001703 // Link against a framework. Frameworks are currently Darwin only, so we
1704 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001705 if (Mod->LinkLibraries[I-1].IsFramework) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001706 llvm::Metadata *Args[2] = {
1707 llvm::MDString::get(Context, "-framework"),
1708 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001709
1710 Metadata.push_back(llvm::MDNode::get(Context, Args));
1711 continue;
1712 }
1713
1714 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001715 llvm::SmallString<24> Opt;
1716 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1717 Mod->LinkLibraries[I-1].Library, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001718 auto *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001719 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1720 }
1721}
1722
1723void CodeGenModule::EmitModuleLinkOptions() {
1724 // Collect the set of all of the modules we want to visit to emit link
1725 // options, which is essentially the imported modules and all of their
1726 // non-explicit child modules.
1727 llvm::SetVector<clang::Module *> LinkModules;
1728 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1729 SmallVector<clang::Module *, 16> Stack;
1730
1731 // Seed the stack with imported modules.
Manman Ren9803ee82017-01-11 18:47:38 +00001732 for (Module *M : ImportedModules) {
1733 // Do not add any link flags when an implementation TU of a module imports
1734 // a header of that same module.
1735 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1736 !getLangOpts().isCompilingModule())
1737 continue;
Yaron Kerenb54db522015-06-11 12:33:25 +00001738 if (Visited.insert(M).second)
1739 Stack.push_back(M);
Manman Ren9803ee82017-01-11 18:47:38 +00001740 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001741
1742 // Find all of the modules to import, making a little effort to prune
1743 // non-leaf modules.
1744 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001745 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001746
1747 bool AnyChildren = false;
1748
1749 // Visit the submodules of this module.
1750 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1751 SubEnd = Mod->submodule_end();
1752 Sub != SubEnd; ++Sub) {
1753 // Skip explicit children; they need to be explicitly imported to be
1754 // linked against.
1755 if ((*Sub)->IsExplicit)
1756 continue;
1757
David Blaikie82e95a32014-11-19 07:49:47 +00001758 if (Visited.insert(*Sub).second) {
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001759 Stack.push_back(*Sub);
1760 AnyChildren = true;
1761 }
1762 }
1763
1764 // We didn't find any children, so add this module to the list of
1765 // modules to link against.
1766 if (!AnyChildren) {
1767 LinkModules.insert(Mod);
1768 }
1769 }
1770
1771 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001772 // order. We don't do anything to try to order import link flags with respect
1773 // to linker options inserted by things like #pragma comment().
Peter Collingbourne89061b22017-06-12 20:10:48 +00001774 SmallVector<llvm::MDNode *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001775 Visited.clear();
Yaron Kerenb54db522015-06-11 12:33:25 +00001776 for (Module *M : LinkModules)
1777 if (Visited.insert(M).second)
1778 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
Daniel Dunbar69e47462013-01-17 01:35:06 +00001779 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001780 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001781
Daniel Dunbar69e47462013-01-17 01:35:06 +00001782 // Add the linker options metadata flag.
Peter Collingbourne89061b22017-06-12 20:10:48 +00001783 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1784 for (auto *MD : LinkerOptionsMetadata)
1785 NMD->addOperand(MD);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001786}
1787
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001788void CodeGenModule::EmitDeferred() {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001789 // Emit deferred declare target declarations.
1790 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1791 getOpenMPRuntime().emitDeferredTargetDecls();
1792
Chris Lattner45470942009-03-21 09:44:56 +00001793 // Emit code for any potentially referenced deferred decls. Since a
1794 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001795 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001796
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001797 if (!DeferredVTables.empty()) {
1798 EmitDeferredVTables();
John McCall6bd2a892013-01-25 22:31:03 +00001799
Eric Christopherd160c502016-01-29 01:35:53 +00001800 // Emitting a vtable doesn't directly cause more vtables to
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001801 // become deferred, although it can cause functions to be
Eric Christopherd160c502016-01-29 01:35:53 +00001802 // emitted that then need those vtables.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001803 assert(DeferredVTables.empty());
1804 }
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001805
Eric Christopherd160c502016-01-29 01:35:53 +00001806 // Stop if we're out of both deferred vtables and deferred declarations.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001807 if (DeferredDeclsToEmit.empty())
1808 return;
John McCall6bd2a892013-01-25 22:31:03 +00001809
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001810 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1811 // work, it will not interfere with this.
Sanjoy Das70a60512017-05-01 06:12:13 +00001812 std::vector<GlobalDecl> CurDeclsToEmit;
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001813 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1814
Sanjoy Das70a60512017-05-01 06:12:13 +00001815 for (GlobalDecl &D : CurDeclsToEmit) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00001816 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1817 // to get GlobalValue with exactly the type we need, not something that
1818 // might had been created for another decl with the same mangled name but
1819 // different type.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001820 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
John McCalld195d4c2016-11-30 23:25:13 +00001821 GetAddrOfGlobal(D, ForDefinition));
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001822
1823 // In case of different address spaces, we may still get a cast, even with
1824 // IsForDefinition equal to true. Query mangled names table to get
1825 // GlobalValue.
1826 if (!GV)
1827 GV = GetGlobalValue(getMangledName(D));
1828
1829 // Make sure GetGlobalValue returned non-null.
1830 assert(GV);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001831
John McCallc2af9392010-05-27 01:45:30 +00001832 // Check to see if we've already emitted this. This is necessary
1833 // for a couple of reasons: first, decls can end up in the
1834 // deferred-decls queue multiple times, and second, decls can end
1835 // up with definitions in unusual ways (e.g. by an extern inline
1836 // function acquiring a strong function redefinition). Just
1837 // ignore these cases.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001838 if (!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001839 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001840
Chris Lattner45470942009-03-21 09:44:56 +00001841 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001842 EmitGlobalDefinition(D, GV);
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001843
1844 // If we found out that we need to emit more decls, do that recursively.
1845 // This has the advantage that the decls are emitted in a DFS and related
1846 // ones are close together, which is convenient for testing.
1847 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1848 EmitDeferred();
1849 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1850 }
Chris Lattner45470942009-03-21 09:44:56 +00001851 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001852}
Chris Lattner09153c02007-06-22 18:48:09 +00001853
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001854void CodeGenModule::EmitVTablesOpportunistically() {
1855 // Try to emit external vtables as available_externally if they have emitted
1856 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1857 // is not allowed to create new references to things that need to be emitted
1858 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1859
Piotr Padlewski05547742017-06-01 09:24:36 +00001860 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1861 && "Only emit opportunistic vtables with optimizations");
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001862
1863 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1864 assert(getVTables().isVTableExternal(RD) &&
1865 "This queue should only contain external vtables");
1866 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1867 VTables.GenerateClassData(RD);
1868 }
1869 OpportunisticVTables.clear();
1870}
1871
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001872void CodeGenModule::EmitGlobalAnnotations() {
1873 if (Annotations.empty())
1874 return;
1875
1876 // Create a new global variable for the ConstantStruct in the Module.
1877 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1878 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001879 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1880 llvm::GlobalValue::AppendingLinkage,
1881 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001882 gv->setSection(AnnotationSection);
1883}
1884
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001885llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001886 llvm::Constant *&AStr = AnnotationStrings[Str];
1887 if (AStr)
1888 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001889
1890 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001891 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001892 auto *gv =
1893 new llvm::GlobalVariable(getModule(), s->getType(), true,
1894 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001895 gv->setSection(AnnotationSection);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001896 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Benjamin Kramereed80612013-11-10 16:55:11 +00001897 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001898 return gv;
1899}
1900
1901llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1902 SourceManager &SM = getContext().getSourceManager();
1903 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1904 if (PLoc.isValid())
1905 return EmitAnnotationString(PLoc.getFilename());
1906 return EmitAnnotationString(SM.getBufferName(Loc));
1907}
1908
1909llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1910 SourceManager &SM = getContext().getSourceManager();
1911 PresumedLoc PLoc = SM.getPresumedLoc(L);
1912 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1913 SM.getExpansionLineNumber(L);
1914 return llvm::ConstantInt::get(Int32Ty, LineNo);
1915}
1916
Mike Stump11289f42009-09-09 15:08:12 +00001917llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001918 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001919 SourceLocation L) {
1920 // Get the globals for file name, annotation, and the line number.
1921 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1922 *UnitGV = EmitAnnotationUnit(L),
1923 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001924
Daniel Dunbar346892a2009-04-14 22:41:13 +00001925 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001926 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001927 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1928 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1929 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1930 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001931 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001932 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001933}
1934
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001935void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1936 llvm::GlobalValue *GV) {
1937 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1938 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001939 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1940 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001941}
1942
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001943bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1944 llvm::Function *Fn,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001945 SourceLocation Loc) const {
1946 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1947 // Blacklist by function name.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001948 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001949 return true;
1950 // Blacklist by location.
Yaron Kerened1fe5d2015-10-03 05:15:57 +00001951 if (Loc.isValid())
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001952 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001953 // If location is unknown, this may be a compiler-generated function. Assume
1954 // it's located in the main file.
1955 auto &SM = Context.getSourceManager();
1956 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001957 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001958 }
1959 return false;
1960}
1961
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001962bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1963 SourceLocation Loc, QualType Ty,
1964 StringRef Category) const {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001965 // For now globals can be blacklisted only in ASan and KASan.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001966 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +00001967 (SanitizerKind::Address | SanitizerKind::KernelAddress |
1968 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001969 if (!EnabledAsanMask)
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001970 return false;
1971 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001972 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001973 return true;
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001974 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001975 return true;
1976 // Check global type.
1977 if (!Ty.isNull()) {
1978 // Drill down the array types: if global variable of a fixed type is
1979 // blacklisted, we also don't instrument arrays of them.
1980 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1981 Ty = AT->getElementType();
1982 Ty = Ty.getCanonicalType().getUnqualifiedType();
1983 // We allow to blacklist only record types (classes, structs etc.)
1984 if (Ty->isRecordType()) {
1985 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001986 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001987 return true;
1988 }
1989 }
1990 return false;
1991}
1992
Dean Michael Berris835832d2017-03-30 00:29:36 +00001993bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1994 StringRef Category) const {
Dean Michael Berris835832d2017-03-30 00:29:36 +00001995 const auto &XRayFilter = getContext().getXRayFilter();
1996 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
Dean Michael Berris488f7c22018-04-13 02:31:58 +00001997 auto Attr = ImbueAttr::NONE;
Dean Michael Berris835832d2017-03-30 00:29:36 +00001998 if (Loc.isValid())
1999 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2000 if (Attr == ImbueAttr::NONE)
2001 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2002 switch (Attr) {
2003 case ImbueAttr::NONE:
2004 return false;
2005 case ImbueAttr::ALWAYS:
2006 Fn->addFnAttr("function-instrument", "xray-always");
2007 break;
Dean Michael Berris170429e2017-05-24 05:46:36 +00002008 case ImbueAttr::ALWAYS_ARG1:
2009 Fn->addFnAttr("function-instrument", "xray-always");
2010 Fn->addFnAttr("xray-log-args", "1");
2011 break;
Dean Michael Berris835832d2017-03-30 00:29:36 +00002012 case ImbueAttr::NEVER:
2013 Fn->addFnAttr("function-instrument", "xray-never");
2014 break;
2015 }
2016 return true;
2017}
2018
Hans Wennborg43a0f992015-01-10 01:19:48 +00002019bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00002020 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002021 if (LangOpts.EmitAllDecls)
Hans Wennborg43a0f992015-01-10 01:19:48 +00002022 return true;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002023
Elizabeth Andrews6593df22018-08-22 19:05:19 +00002024 if (CodeGenOpts.KeepStaticConsts) {
2025 const auto *VD = dyn_cast<VarDecl>(Global);
2026 if (VD && VD->getType().isConstQualified() &&
2027 VD->getStorageClass() == SC_Static)
2028 return true;
2029 }
2030
Hans Wennborg43a0f992015-01-10 01:19:48 +00002031 return getContext().DeclMustBeEmitted(Global);
2032}
2033
2034bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2035 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
2036 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2037 // Implicit template instantiations may change linkage if they are later
2038 // explicitly instantiated, so they should not be emitted eagerly.
2039 return false;
Richard Smithd9b90092016-07-02 01:32:16 +00002040 if (const auto *VD = dyn_cast<VarDecl>(Global))
2041 if (Context.getInlineVariableDefinitionKind(VD) ==
2042 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2043 // A definition of an inline constexpr static data member may change
2044 // linkage later if it's redeclared outside the class.
2045 return false;
Samuel Antaof8b50122015-07-13 22:54:53 +00002046 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2047 // codegen for global variables, because they may be marked as threadprivate.
2048 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
Alexey Bataev96edb2e2018-06-25 15:32:05 +00002049 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
Alexey Bataevd01b7492018-08-15 19:45:12 +00002050 !isTypeConstant(Global->getType(), false) &&
2051 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
Samuel Antaof8b50122015-07-13 22:54:53 +00002052 return false;
Hans Wennborg43a0f992015-01-10 01:19:48 +00002053
2054 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002055}
2056
John McCall7f416cc2015-09-08 08:05:57 +00002057ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
Nico Webercf4ff5862012-10-11 10:13:44 +00002058 const CXXUuidofExpr* E) {
2059 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
2060 // well-formed.
David Majnemer2041b462016-03-28 03:19:50 +00002061 StringRef Uuid = E->getUuidStr();
David Majnemercf963ce2013-08-09 08:35:59 +00002062 std::string Name = "_GUID_" + Uuid.lower();
2063 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00002064
David Majnemer65687602016-03-27 04:46:14 +00002065 // The UUID descriptor should be pointer aligned.
2066 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
John McCall7f416cc2015-09-08 08:05:57 +00002067
Nico Webercf4ff5862012-10-11 10:13:44 +00002068 // Look for an existing global.
2069 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
John McCall7f416cc2015-09-08 08:05:57 +00002070 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00002071
Nico Weber17d3a2c2014-09-08 16:26:36 +00002072 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Webercf4ff5862012-10-11 10:13:44 +00002073 assert(Init && "failed to initialize as constant");
2074
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002075 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00002076 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00002077 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002078 if (supportsCOMDAT())
2079 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolaca08d242018-03-20 15:42:58 +00002080 setDSOLocal(GV);
John McCall7f416cc2015-09-08 08:05:57 +00002081 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00002082}
2083
John McCall7f416cc2015-09-08 08:05:57 +00002084ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002085 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2086 assert(AA && "No alias?");
2087
John McCall7f416cc2015-09-08 08:05:57 +00002088 CharUnits Alignment = getContext().getDeclAlign(VD);
Chris Lattner2192fe52011-07-18 04:24:23 +00002089 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002090
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002091 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00002092 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002093 if (Entry) {
2094 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
John McCall7f416cc2015-09-08 08:05:57 +00002095 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2096 return ConstantAddress(Ptr, Alignment);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002097 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002098
2099 llvm::Constant *Aliasee;
2100 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002101 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2102 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00002103 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002104 else
John McCall7ec50432010-03-19 23:29:14 +00002105 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00002106 llvm::PointerType::getUnqual(DeclTy),
2107 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002108
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002109 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002110 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2111 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002112
John McCall7f416cc2015-09-08 08:05:57 +00002113 return ConstantAddress(Aliasee, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002114}
2115
Chris Lattnere0be0df2009-05-12 21:21:08 +00002116void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002117 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002118
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002119 // Weak references don't produce any output by themselves.
2120 if (Global->hasAttr<WeakRefAttr>())
2121 return;
2122
Chris Lattner54041692009-03-22 21:47:11 +00002123 // If this is an alias definition (which otherwise looks like a declaration)
2124 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002125 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00002126 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002127
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002128 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2129 if (Global->hasAttr<IFuncAttr>())
2130 return emitIFuncDefinition(GD);
2131
Erich Keane3efe0022018-07-20 14:13:28 +00002132 // If this is a cpu_dispatch multiversion function, emit the resolver.
2133 if (Global->hasAttr<CPUDispatchAttr>())
2134 return emitCPUDispatchDefinition(GD);
2135
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002136 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002137 if (LangOpts.CUDA) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00002138 if (LangOpts.CUDAIsDevice) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002139 if (!Global->hasAttr<CUDADeviceAttr>() &&
2140 !Global->hasAttr<CUDAGlobalAttr>() &&
2141 !Global->hasAttr<CUDAConstantAttr>() &&
2142 !Global->hasAttr<CUDASharedAttr>())
2143 return;
2144 } else {
Artem Belevich42e19492016-03-02 18:28:50 +00002145 // We need to emit host-side 'shadows' for all global
2146 // device-side variables because the CUDA runtime needs their
2147 // size and host-side address in order to provide access to
2148 // their device-side incarnations.
2149
2150 // So device-only functions are the only things we skip.
2151 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2152 Global->hasAttr<CUDADeviceAttr>())
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002153 return;
Artem Belevich42e19492016-03-02 18:28:50 +00002154
2155 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2156 "Expected Variable or Function");
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002157 }
2158 }
2159
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002160 if (LangOpts.OpenMP) {
2161 // If this is OpenMP device, check if it is legal to emit this global
2162 // normally.
2163 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2164 return;
2165 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2166 if (MustBeEmitted(Global))
2167 EmitOMPDeclareReduction(DRD);
2168 return;
2169 }
2170 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002171
Chris Lattner45470942009-03-21 09:44:56 +00002172 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002173 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002174 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002175 if (!FD->doesThisDeclarationHaveABody()) {
2176 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2177 return;
2178
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002179 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00002180
2181 // Compute the function info and LLVM type.
2182 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2183 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2184
2185 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2186 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002187 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002188 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00002189 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002190 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002191 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
Artem Belevich42e19492016-03-02 18:28:50 +00002192 // We need to emit device-side global CUDA variables even if a
2193 // variable does not have a definition -- we still need to define
2194 // host-side shadow for it.
2195 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2196 !VD->hasDefinition() &&
2197 (VD->hasAttr<CUDAConstantAttr>() ||
2198 VD->hasAttr<CUDADeviceAttr>());
2199 if (!MustEmitForCuda &&
2200 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
Richard Smithd9b90092016-07-02 01:32:16 +00002201 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00002202 if (LangOpts.OpenMP) {
2203 // Emit declaration of the must-be-emitted declare target variable.
2204 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2205 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2206 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
2207 (void)GetAddrOfGlobalVar(VD);
2208 } else {
2209 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
2210 "link claue expected.");
2211 (void)getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
2212 }
2213 return;
2214 }
2215 }
Richard Smithd9b90092016-07-02 01:32:16 +00002216 // If this declaration may have caused an inline variable definition to
2217 // change linkage, make sure that it's emitted.
2218 if (Context.getInlineVariableDefinitionKind(VD) ==
2219 ASTContext::InlineVariableDefinitionKind::Strong)
2220 GetAddrOfGlobalVar(VD);
Douglas Gregorbeecd582009-04-21 17:11:58 +00002221 return;
Richard Smithd9b90092016-07-02 01:32:16 +00002222 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002223 }
2224
Hans Wennborg43a0f992015-01-10 01:19:48 +00002225 // Defer code generation to first use when possible, e.g. if this is an inline
2226 // function. If the global must always be emitted, do it eagerly if possible
2227 // to benefit from cache locality.
2228 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002229 // Emit the definition if it can't be deferred.
2230 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002231 return;
2232 }
John McCall70013b62010-07-15 23:40:35 +00002233
2234 // If we're deferring emission of a C++ variable with an
2235 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002236 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00002237 cast<VarDecl>(Global)->hasInit()) {
2238 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00002239 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00002240 }
Hans Wennborg43a0f992015-01-10 01:19:48 +00002241
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002242 StringRef MangledName = getMangledName(GD);
Sanjoy Das70a60512017-05-01 06:12:13 +00002243 if (GetGlobalValue(MangledName) != nullptr) {
Hans Wennborg43a0f992015-01-10 01:19:48 +00002244 // The value has already been used and should therefore be emitted.
Sanjoy Das70a60512017-05-01 06:12:13 +00002245 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002246 } else if (MustBeEmitted(Global)) {
2247 // The value must be emitted, but cannot be emitted eagerly.
2248 assert(!MayBeEmittedEagerly(Global));
Sanjoy Das70a60512017-05-01 06:12:13 +00002249 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002250 } else {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002251 // Otherwise, remember that we saw a deferred decl with this name. The
2252 // first use of the mangled name will cause it to move into
2253 // DeferredDeclsToEmit.
2254 DeferredDecls[MangledName] = GD;
2255 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002256}
2257
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002258// Check if T is a class type with a destructor that's not dllimport.
2259static bool HasNonDllImportDtor(QualType T) {
2260 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2261 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2262 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2263 return true;
2264
2265 return false;
2266}
2267
Rafael Espindolac5941352011-10-26 20:41:06 +00002268namespace {
2269 struct FunctionIsDirectlyRecursive :
2270 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2271 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002272 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00002273 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002274 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2275 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002276 }
2277 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2278
2279 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002280 const FunctionDecl *FD = E->getDirectCallee();
2281 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00002282 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002283 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2284 if (Attr && Name == Attr->getLabel()) {
2285 Result = true;
2286 return false;
2287 }
2288 unsigned BuiltinID = FD->getBuiltinID();
David Majnemer41011f62015-06-25 23:50:40 +00002289 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
Rafael Espindolac5941352011-10-26 20:41:06 +00002290 return true;
Eric Christopher02d5d862015-08-06 01:01:12 +00002291 StringRef BuiltinName = BI.getName(BuiltinID);
Nick Lewycky9ed5b152012-01-18 03:41:19 +00002292 if (BuiltinName.startswith("__builtin_") &&
2293 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002294 Result = true;
2295 return false;
2296 }
2297 return true;
2298 }
2299 };
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002300
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002301 // Make sure we're not referencing non-imported vars or functions.
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002302 struct DLLImportFunctionVisitor
2303 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2304 bool SafeToInline = true;
2305
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002306 bool shouldVisitImplicitCode() const { return true; }
2307
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002308 bool VisitVarDecl(VarDecl *VD) {
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002309 if (VD->getTLSKind()) {
2310 // A thread-local variable cannot be imported.
2311 SafeToInline = false;
2312 return SafeToInline;
2313 }
2314
2315 // A variable definition might imply a destructor call.
2316 if (VD->isThisDeclarationADefinition())
2317 SafeToInline = !HasNonDllImportDtor(VD->getType());
2318
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002319 return SafeToInline;
2320 }
2321
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002322 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2323 if (const auto *D = E->getTemporary()->getDestructor())
2324 SafeToInline = D->hasAttr<DLLImportAttr>();
2325 return SafeToInline;
2326 }
2327
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002328 bool VisitDeclRefExpr(DeclRefExpr *E) {
2329 ValueDecl *VD = E->getDecl();
2330 if (isa<FunctionDecl>(VD))
2331 SafeToInline = VD->hasAttr<DLLImportAttr>();
2332 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2333 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2334 return SafeToInline;
2335 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002336
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002337 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2338 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2339 return SafeToInline;
2340 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002341
Hans Wennborg251c2042017-01-23 23:57:50 +00002342 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2343 CXXMethodDecl *M = E->getMethodDecl();
2344 if (!M) {
2345 // Call through a pointer to member function. This is safe to inline.
2346 SafeToInline = true;
2347 } else {
2348 SafeToInline = M->hasAttr<DLLImportAttr>();
2349 }
2350 return SafeToInline;
2351 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002352
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002353 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2354 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2355 return SafeToInline;
2356 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002357
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002358 bool VisitCXXNewExpr(CXXNewExpr *E) {
2359 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2360 return SafeToInline;
2361 }
2362 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002363}
Rafael Espindolac5941352011-10-26 20:41:06 +00002364
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002365// isTriviallyRecursive - Check if this function calls another
2366// decl that, because of the asm attribute or the other decl being a builtin,
2367// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00002368bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002369CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2370 StringRef Name;
2371 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00002372 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002373 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2374 if (!Attr)
2375 return false;
2376 Name = Attr->getLabel();
2377 } else {
2378 Name = FD->getName();
2379 }
Rafael Espindolac5941352011-10-26 20:41:06 +00002380
David Majnemer64b0bdf2015-06-30 04:41:18 +00002381 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002382 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00002383 return Walker.Result;
2384}
2385
Hans Wennborg93f75472016-09-13 21:08:20 +00002386bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002387 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00002388 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002389 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00002390 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00002391 return false;
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002392
2393 if (F->hasAttr<DLLImportAttr>()) {
2394 // Check whether it would be safe to inline this dllimport function.
2395 DLLImportFunctionVisitor Visitor;
2396 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2397 if (!Visitor.SafeToInline)
2398 return false;
Hans Wennborg93f75472016-09-13 21:08:20 +00002399
2400 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2401 // Implicit destructor invocations aren't captured in the AST, so the
2402 // check above can't see them. Check for them manually here.
2403 for (const Decl *Member : Dtor->getParent()->decls())
2404 if (isa<FieldDecl>(Member))
2405 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2406 return false;
2407 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2408 if (HasNonDllImportDtor(B.getType()))
2409 return false;
2410 }
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002411 }
2412
Rafael Espindolac5941352011-10-26 20:41:06 +00002413 // PR9614. Avoid cases where the source code is lying to us. An available
2414 // externally function should have an equivalent function somewhere else,
2415 // but a function that calls itself is clearly not equivalent to the real
2416 // implementation.
2417 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002418 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00002419}
2420
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002421bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2422 return CodeGenOpts.OptimizationLevel > 0;
2423}
2424
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002425void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002426 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002427
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002428 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00002429 Context.getSourceManager(),
2430 "Generating code for declaration");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002431
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002432 if (isa<FunctionDecl>(D)) {
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002433 // At -O0, don't generate IR for functions with available_externally
Douglas Gregora700f682010-07-13 06:02:28 +00002434 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002435 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00002436 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00002437
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002438 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +00002439 // Make sure to emit the definition(s) before we emit the thunks.
2440 // This is necessary for the generation of certain thunks.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002441 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002442 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002443 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002444 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Eli Friedman49a94b12011-05-06 17:27:27 +00002445 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002446 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002447
Douglas Gregora700f682010-07-13 06:02:28 +00002448 if (Method->isVirtual())
2449 getVTables().EmitThunks(GD);
2450
Eli Friedman49a94b12011-05-06 17:27:27 +00002451 return;
Douglas Gregora700f682010-07-13 06:02:28 +00002452 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00002453
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002454 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00002455 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002456
2457 if (const auto *VD = dyn_cast<VarDecl>(D))
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002458 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002459
David Blaikie83d382b2011-09-23 05:06:16 +00002460 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00002461}
2462
Andrey Bokhankocab58582015-08-31 13:20:44 +00002463static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2464 llvm::Function *NewFn);
2465
Erich Keanef353ae12018-09-13 16:58:24 +00002466static unsigned
2467TargetMVPriority(const TargetInfo &TI,
2468 const CodeGenFunction::MultiVersionResolverOption &RO) {
2469 unsigned Priority = 0;
2470 for (StringRef Feat : RO.Conditions.Features)
2471 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2472
2473 if (!RO.Conditions.Architecture.empty())
2474 Priority = std::max(
2475 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2476 return Priority;
2477}
2478
Erich Keane281d20b2018-01-08 21:34:17 +00002479void CodeGenModule::emitMultiVersionFunctions() {
2480 for (GlobalDecl GD : MultiVersionFuncs) {
Erich Keanef353ae12018-09-13 16:58:24 +00002481 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
Erich Keane281d20b2018-01-08 21:34:17 +00002482 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2483 getContext().forEachMultiversionedFunctionVersion(
2484 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2485 GlobalDecl CurGD{
2486 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2487 StringRef MangledName = getMangledName(CurGD);
2488 llvm::Constant *Func = GetGlobalValue(MangledName);
2489 if (!Func) {
2490 if (CurFD->isDefined()) {
2491 EmitGlobalFunctionDefinition(CurGD, nullptr);
2492 Func = GetGlobalValue(MangledName);
2493 } else {
2494 const CGFunctionInfo &FI =
2495 getTypes().arrangeGlobalDeclaration(GD);
2496 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2497 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2498 /*DontDefer=*/false, ForDefinition);
2499 }
2500 assert(Func && "This should have just been created");
2501 }
Erich Keanef353ae12018-09-13 16:58:24 +00002502
2503 const auto *TA = CurFD->getAttr<TargetAttr>();
2504 llvm::SmallVector<StringRef, 8> Feats;
2505 TA->getAddedFeatures(Feats);
2506
2507 Options.emplace_back(cast<llvm::Function>(Func),
2508 TA->getArchitecture(), Feats);
Erich Keane281d20b2018-01-08 21:34:17 +00002509 });
2510
Erich Keane19a8adc2018-10-25 18:57:19 +00002511 llvm::Function *ResolverFunc;
2512 const TargetInfo &TI = getTarget();
2513
2514 if (TI.supportsIFunc() || FD->isTargetMultiVersion())
2515 ResolverFunc = cast<llvm::Function>(
2516 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2517 else
2518 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2519
Erich Keane0a6fde42018-01-16 19:49:52 +00002520 if (supportsCOMDAT())
2521 ResolverFunc->setComdat(
2522 getModule().getOrInsertComdat(ResolverFunc->getName()));
Erich Keanef353ae12018-09-13 16:58:24 +00002523
Erich Keane281d20b2018-01-08 21:34:17 +00002524 std::stable_sort(
2525 Options.begin(), Options.end(),
Erich Keanef353ae12018-09-13 16:58:24 +00002526 [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
2527 const CodeGenFunction::MultiVersionResolverOption &RHS) {
2528 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
2529 });
Erich Keane281d20b2018-01-08 21:34:17 +00002530 CodeGenFunction CGF(*this);
Erich Keanef353ae12018-09-13 16:58:24 +00002531 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
Erich Keane281d20b2018-01-08 21:34:17 +00002532 }
2533}
2534
Erich Keane3efe0022018-07-20 14:13:28 +00002535void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2536 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2537 assert(FD && "Not a FunctionDecl?");
2538 const auto *DD = FD->getAttr<CPUDispatchAttr>();
2539 assert(DD && "Not a cpu_dispatch Function?");
2540 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(FD->getType());
2541
2542 StringRef ResolverName = getMangledName(GD);
Erich Keane19a8adc2018-10-25 18:57:19 +00002543
2544 llvm::Type *ResolverType;
2545 GlobalDecl ResolverGD;
2546 if (getTarget().supportsIFunc())
2547 ResolverType = llvm::FunctionType::get(
2548 llvm::PointerType::get(DeclTy,
2549 Context.getTargetAddressSpace(FD->getType())),
2550 false);
2551 else {
2552 ResolverType = DeclTy;
2553 ResolverGD = GD;
2554 }
2555
2556 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2557 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
Erich Keane3efe0022018-07-20 14:13:28 +00002558
Erich Keanef353ae12018-09-13 16:58:24 +00002559 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
Erich Keane3efe0022018-07-20 14:13:28 +00002560 const TargetInfo &Target = getTarget();
2561 for (const IdentifierInfo *II : DD->cpus()) {
2562 // Get the name of the target function so we can look it up/create it.
2563 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
2564 getCPUSpecificMangling(*this, II->getName());
2565 llvm::Constant *Func = GetOrCreateLLVMFunction(
2566 MangledName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/false,
2567 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
2568 llvm::SmallVector<StringRef, 32> Features;
2569 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
2570 llvm::transform(Features, Features.begin(),
2571 [](StringRef Str) { return Str.substr(1); });
2572 Features.erase(std::remove_if(
2573 Features.begin(), Features.end(), [&Target](StringRef Feat) {
2574 return !Target.validateCpuSupports(Feat);
2575 }), Features.end());
Erich Keanef353ae12018-09-13 16:58:24 +00002576 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
Erich Keane3efe0022018-07-20 14:13:28 +00002577 }
2578
2579 llvm::sort(
Fangrui Song1d38c132018-09-30 21:41:11 +00002580 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
2581 const CodeGenFunction::MultiVersionResolverOption &RHS) {
Erich Keanef353ae12018-09-13 16:58:24 +00002582 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
2583 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
2584 });
Erich Keane3efe0022018-07-20 14:13:28 +00002585 CodeGenFunction CGF(*this);
Erich Keanef353ae12018-09-13 16:58:24 +00002586 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
Erich Keane3efe0022018-07-20 14:13:28 +00002587}
2588
Erich Keane19a8adc2018-10-25 18:57:19 +00002589/// If a dispatcher for the specified mangled name is not in the module, create
2590/// and return an llvm Function with the specified type.
2591llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
2592 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
Erich Keane3efe0022018-07-20 14:13:28 +00002593 std::string MangledName =
2594 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
Erich Keane19a8adc2018-10-25 18:57:19 +00002595
2596 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
2597 // a separate resolver).
2598 std::string ResolverName = MangledName;
2599 if (getTarget().supportsIFunc())
2600 ResolverName += ".ifunc";
2601 else if (FD->isTargetMultiVersion())
2602 ResolverName += ".resolver";
2603
2604 // If this already exists, just return that one.
2605 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
2606 return ResolverGV;
Erich Keane281d20b2018-01-08 21:34:17 +00002607
2608 // Since this is the first time we've created this IFunc, make sure
2609 // that we put this multiversioned function into the list to be
Erich Keane3efe0022018-07-20 14:13:28 +00002610 // replaced later if necessary (target multiversioning only).
2611 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
2612 MultiVersionFuncs.push_back(GD);
Erich Keane281d20b2018-01-08 21:34:17 +00002613
Erich Keane19a8adc2018-10-25 18:57:19 +00002614 if (getTarget().supportsIFunc()) {
2615 llvm::Type *ResolverType = llvm::FunctionType::get(
2616 llvm::PointerType::get(
2617 DeclTy, getContext().getTargetAddressSpace(FD->getType())),
2618 false);
2619 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2620 MangledName + ".resolver", ResolverType, GlobalDecl{},
2621 /*ForVTable=*/false);
2622 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2623 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2624 GIF->setName(ResolverName);
2625 SetCommonAttributes(FD, GIF);
Erich Keane281d20b2018-01-08 21:34:17 +00002626
Erich Keane19a8adc2018-10-25 18:57:19 +00002627 return GIF;
2628 }
2629
2630 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2631 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
2632 assert(isa<llvm::GlobalValue>(Resolver) &&
2633 "Resolver should be created for the first time");
2634 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
2635 return Resolver;
Erich Keane281d20b2018-01-08 21:34:17 +00002636}
2637
Chris Lattnerd4808922009-03-22 21:03:39 +00002638/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2639/// module, create and return an llvm Function with the specified type. If there
2640/// is something in the module with the specified name, return it potentially
2641/// bitcasted to the right type.
2642///
2643/// If D is non-null, it specifies a decl that correspond to this. This is used
2644/// to set the attributes on the function when it is first created.
Reid Klecknerde864822017-03-21 16:57:30 +00002645llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2646 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2647 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2648 ForDefinition_t IsForDefinition) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002649 const Decl *D = GD.getDecl();
2650
Erich Keane281d20b2018-01-08 21:34:17 +00002651 // Any attempts to use a MultiVersion function should result in retrieving
2652 // the iFunc instead. Name Mangling will handle the rest of the changes.
2653 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002654 // For the device mark the function as one that should be emitted.
2655 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
Alexey Bataev6d944102018-05-02 15:45:28 +00002656 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002657 !DontDefer && !IsForDefinition) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002658 if (const FunctionDecl *FDDef = FD->getDefinition()) {
2659 GlobalDecl GDDef;
2660 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2661 GDDef = GlobalDecl(CD, GD.getCtorType());
2662 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2663 GDDef = GlobalDecl(DD, GD.getDtorType());
2664 else
2665 GDDef = GlobalDecl(FDDef);
2666 EmitGlobal(GDDef);
2667 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002668 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002669
Erich Keane3efe0022018-07-20 14:13:28 +00002670 if (FD->isMultiVersion()) {
2671 const auto *TA = FD->getAttr<TargetAttr>();
2672 if (TA && TA->isDefaultVersion())
2673 UpdateMultiVersionNames(GD, FD);
Erich Keane281d20b2018-01-08 21:34:17 +00002674 if (!IsForDefinition)
Erich Keane19a8adc2018-10-25 18:57:19 +00002675 return GetOrCreateMultiVersionResolver(GD, Ty, FD);
Erich Keane281d20b2018-01-08 21:34:17 +00002676 }
2677 }
2678
Chris Lattnera85d68e2009-03-21 09:25:43 +00002679 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002680 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002681 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002682 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002683 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002684 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002685 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002686 }
2687
Hans Wennborg0a20f542014-08-29 00:16:06 +00002688 // Handle dropped DLL attributes.
Rafael Espindolac9643d82018-03-29 16:45:18 +00002689 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
Hans Wennborg0a20f542014-08-29 00:16:06 +00002690 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
Rafael Espindolac9643d82018-03-29 16:45:18 +00002691 setDSOLocal(Entry);
2692 }
Hans Wennborg0a20f542014-08-29 00:16:06 +00002693
Andrey Bokhankocab58582015-08-31 13:20:44 +00002694 // If there are two attempts to define the same mangled name, issue an
2695 // error.
2696 if (IsForDefinition && !Entry->isDeclaration()) {
2697 GlobalDecl OtherGD;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002698 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2699 // to make sure that we issue an error only once.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002700 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2701 (GD.getCanonicalDecl().getDecl() !=
2702 OtherGD.getCanonicalDecl().getDecl()) &&
2703 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00002704 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2705 << MangledName;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002706 getDiags().Report(OtherGD.getDecl()->getLocation(),
2707 diag::note_previous_definition);
2708 }
2709 }
2710
2711 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2712 (Entry->getType()->getElementType() == Ty)) {
Chris Lattnera85d68e2009-03-21 09:25:43 +00002713 return Entry;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002714 }
Mike Stump11289f42009-09-09 15:08:12 +00002715
Chris Lattnera85d68e2009-03-21 09:25:43 +00002716 // Make sure the result is of the correct type.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002717 // (If function is requested for a definition, we always need to create a new
2718 // function, not just return a bitcast.)
2719 if (!IsForDefinition)
2720 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00002721 }
Mike Stump11289f42009-09-09 15:08:12 +00002722
Eli Friedmancc522d92009-11-09 05:07:37 +00002723 // This function doesn't have a complete type (for example, the return
2724 // type is an incomplete struct). Use a fake type instead, and make
2725 // sure not to try to set attributes.
2726 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00002727
Chris Lattner2192fe52011-07-18 04:24:23 +00002728 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00002729 if (isa<llvm::FunctionType>(Ty)) {
2730 FTy = cast<llvm::FunctionType>(Ty);
2731 } else {
John McCall9dc0db22011-05-15 01:53:33 +00002732 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00002733 IsIncompleteFunction = true;
2734 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002735
2736 llvm::Function *F =
2737 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2738 Entry ? StringRef() : MangledName, &getModule());
2739
2740 // If we already created a function with the same mangled name (but different
2741 // type) before, take its name and add it to the list of functions to be
2742 // replaced with F at the end of CodeGen.
2743 //
2744 // This happens if there is a prototype for a function (e.g. "int f()") and
2745 // then a definition of a different type (e.g. "int f(int x)").
2746 if (Entry) {
2747 F->takeName(Entry);
2748
2749 // This might be an implementation of a function without a prototype, in
2750 // which case, try to do special replacement of calls which match the new
2751 // prototype. The really key thing here is that we also potentially drop
2752 // arguments from the call site so as to make a direct call, which makes the
2753 // inliner happier and suppresses a number of optimizer warnings (!) about
2754 // dropping arguments.
2755 if (!Entry->use_empty()) {
2756 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2757 Entry->removeDeadConstantUsers();
2758 }
2759
2760 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2761 F, Entry->getType()->getElementType()->getPointerTo());
2762 addGlobalValReplacement(Entry, BC);
2763 }
2764
John McCall7ec50432010-03-19 23:29:14 +00002765 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002766 if (D)
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002767 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Reid Klecknerde864822017-03-21 16:57:30 +00002768 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2769 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
Reid Kleckneree4930b2017-05-02 22:07:37 +00002770 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Bill Wendling9a677922013-01-23 00:21:06 +00002771 }
Eli Friedmancc522d92009-11-09 05:07:37 +00002772
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002773 if (!DontDefer) {
2774 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2775 // each other bottoming out with the base dtor. Therefore we emit non-base
2776 // dtors on usage, even if there is no dtor definition in the TU.
2777 if (D && isa<CXXDestructorDecl>(D) &&
2778 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2779 GD.getDtorType()))
Sanjoy Das70a60512017-05-01 06:12:13 +00002780 addDeferredDeclToEmit(GD);
John McCall357d0f32010-12-15 04:00:32 +00002781
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002782 // This is the first use or definition of a mangled name. If there is a
2783 // deferred decl with this name, remember that we need to emit it at the end
2784 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002785 auto DDI = DeferredDecls.find(MangledName);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002786 if (DDI != DeferredDecls.end()) {
2787 // Move the potentially referenced deferred decl to the
2788 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2789 // don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002790 addDeferredDeclToEmit(DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002791 DeferredDecls.erase(DDI);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002792
2793 // Otherwise, there are cases we have to worry about where we're
2794 // using a declaration for which we must emit a definition but where
2795 // we might not find a top-level definition:
2796 // - member functions defined inline in their classes
2797 // - friend functions defined inline in some class
2798 // - special member functions with implicit definitions
2799 // If we ever change our AST traversal to walk into class methods,
2800 // this will be unnecessary.
2801 //
2802 // We also don't emit a definition for a function if it's going to be an
Richard Smith46bb5812014-08-01 01:56:39 +00002803 // entry in a vtable, unless it's already marked as used.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002804 } else if (getLangOpts().CPlusPlus && D) {
2805 // Look for a declaration that's lexically in a record.
Richard Smith46bb5812014-08-01 01:56:39 +00002806 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2807 FD = FD->getPreviousDecl()) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002808 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Richard Smith46bb5812014-08-01 01:56:39 +00002809 if (FD->doesThisDeclarationHaveABody()) {
Sanjoy Das70a60512017-05-01 06:12:13 +00002810 addDeferredDeclToEmit(GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002811 break;
2812 }
John McCall357d0f32010-12-15 04:00:32 +00002813 }
Richard Smith46bb5812014-08-01 01:56:39 +00002814 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002815 }
Chris Lattner45470942009-03-21 09:44:56 +00002816 }
Mike Stump11289f42009-09-09 15:08:12 +00002817
John McCalld06fb862010-04-28 00:00:30 +00002818 // Make sure the result is of the requested type.
2819 if (!IsIncompleteFunction) {
2820 assert(F->getType()->getElementType() == Ty);
2821 return F;
2822 }
2823
Chris Lattnera5f58b02011-07-09 17:41:47 +00002824 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00002825 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002826}
2827
Chris Lattnerd4808922009-03-22 21:03:39 +00002828/// GetAddrOfFunction - Return the address of the given function. If Ty is
2829/// non-null, then this function will use the specified type if it has to
2830/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00002831llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00002832 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002833 bool ForVTable,
Andrey Bokhankocab58582015-08-31 13:20:44 +00002834 bool DontDefer,
John McCalld195d4c2016-11-30 23:25:13 +00002835 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002836 // If there was no specific requested type, just convert it now.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002837 if (!Ty) {
2838 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2839 auto CanonTy = Context.getCanonicalType(FD->getType());
2840 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2841 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002842
Reid Kleckner28103252018-03-16 22:20:57 +00002843 // Devirtualized destructor calls may come through here instead of via
2844 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2845 // of the complete destructor when necessary.
2846 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
2847 if (getTarget().getCXXABI().isMicrosoft() &&
2848 GD.getDtorType() == Dtor_Complete &&
2849 DD->getParent()->getNumVBases() == 0)
2850 GD = GlobalDecl(DD, Dtor_Base);
2851 }
2852
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002853 StringRef MangledName = getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002854 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +00002855 /*IsThunk=*/false, llvm::AttributeList(),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002856 IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002857}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002858
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002859static const FunctionDecl *
2860GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2861 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2862 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2863
2864 IdentifierInfo &CII = C.Idents.get(Name);
2865 for (const auto &Result : DC->lookup(&CII))
2866 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2867 return FD;
2868
2869 if (!C.getLangOpts().CPlusPlus)
2870 return nullptr;
2871
2872 // Demangle the premangled name from getTerminateFn()
2873 IdentifierInfo &CXXII =
Reid Klecknerfb931542018-03-16 20:36:49 +00002874 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002875 ? C.Idents.get("terminate")
2876 : C.Idents.get(Name);
2877
2878 for (const auto &N : {"__cxxabiv1", "std"}) {
2879 IdentifierInfo &NS = C.Idents.get(N);
2880 for (const auto &Result : DC->lookup(&NS)) {
2881 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2882 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2883 for (const auto &Result : LSD->lookup(&NS))
2884 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2885 break;
2886
2887 if (ND)
2888 for (const auto &Result : ND->lookup(&CXXII))
2889 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2890 return FD;
2891 }
2892 }
2893
2894 return nullptr;
2895}
2896
Chris Lattnerd4808922009-03-22 21:03:39 +00002897/// CreateRuntimeFunction - Create a new runtime function with the specified
2898/// type and name.
2899llvm::Constant *
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002900CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
Reid Klecknerde864822017-03-21 16:57:30 +00002901 llvm::AttributeList ExtraAttrs,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002902 bool Local) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002903 llvm::Constant *C =
2904 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002905 /*DontDefer=*/false, /*IsThunk=*/false,
2906 ExtraAttrs);
2907
2908 if (auto *F = dyn_cast<llvm::Function>(C)) {
2909 if (F->empty()) {
John McCall882987f2013-02-28 19:01:20 +00002910 F->setCallingConv(getRuntimeCC());
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002911
2912 if (!Local && getTriple().isOSBinFormatCOFF() &&
Martell Maloneb22e6002017-11-04 02:15:49 +00002913 !getCodeGenOpts().LTOVisibilityPublicStd &&
2914 !getTriple().isWindowsGNUEnvironment()) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002915 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2916 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2917 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2918 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2919 }
2920 }
Rafael Espindola3c9be622018-03-20 20:27:30 +00002921 setDSOLocal(F);
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002922 }
2923 }
2924
John McCall882987f2013-02-28 19:01:20 +00002925 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00002926}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002927
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002928/// CreateBuiltinFunction - Create a new builtin function with the specified
2929/// type and name.
2930llvm::Constant *
Reid Klecknerde864822017-03-21 16:57:30 +00002931CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2932 llvm::AttributeList ExtraAttrs) {
Rafael Espindola1193c372018-03-22 18:03:13 +00002933 return CreateRuntimeFunction(FTy, Name, ExtraAttrs, true);
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002934}
2935
Richard Smithe070fd22012-02-17 06:48:11 +00002936/// isTypeConstant - Determine whether an object of this type can be emitted
2937/// as a constant.
2938///
2939/// If ExcludeCtor is true, the duration when the object's constructor runs
2940/// will not be considered. The caller will need to verify that the object is
2941/// not written to during its construction.
2942bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2943 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00002944 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00002945
David Blaikiebbafb8a2012-03-11 07:00:24 +00002946 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00002947 if (const CXXRecordDecl *Record
2948 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2949 return ExcludeCtor && !Record->hasMutableFields() &&
2950 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00002951 }
Richard Smithe070fd22012-02-17 06:48:11 +00002952
Eli Friedmanb095e152009-12-11 21:23:03 +00002953 return true;
2954}
2955
Chris Lattnerd4808922009-03-22 21:03:39 +00002956/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2957/// create and return an llvm GlobalVariable with the specified type. If there
2958/// is something in the module with the specified name, return it potentially
2959/// bitcasted to the right type.
2960///
2961/// If D is non-null, it specifies a decl that correspond to this. This is used
2962/// to set the attributes on the global when it is first created.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002963///
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002964/// If IsForDefinition is true, it is guaranteed that an actual global with
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002965/// type Ty will be returned, not conversion of a variable with the same
2966/// mangled name but some other type.
John McCall7ec50432010-03-19 23:29:14 +00002967llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002968CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00002969 llvm::PointerType *Ty,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002970 const VarDecl *D,
John McCalld195d4c2016-11-30 23:25:13 +00002971 ForDefinition_t IsForDefinition) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00002972 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002973 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00002974 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002975 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002976 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002977 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002978 }
2979
Hans Wennborg0a20f542014-08-29 00:16:06 +00002980 // Handle dropped DLL attributes.
2981 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2982 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2983
Alexey Bataev03f270c2018-03-30 18:31:07 +00002984 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
2985 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
2986
Chris Lattnerd4808922009-03-22 21:03:39 +00002987 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00002988 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00002989
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002990 // If there are two attempts to define the same mangled name, issue an
2991 // error.
2992 if (IsForDefinition && !Entry->isDeclaration()) {
2993 GlobalDecl OtherGD;
2994 const VarDecl *OtherD;
2995
2996 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2997 // to make sure that we issue an error only once.
Artem Belevich2c323a02016-05-19 18:00:18 +00002998 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002999 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3000 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3001 OtherD->hasInit() &&
3002 DiagnosedConflictingDefinitions.insert(D).second) {
Richard Smithb5345102018-05-30 01:52:16 +00003003 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3004 << MangledName;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003005 getDiags().Report(OtherGD.getDecl()->getLocation(),
3006 diag::note_previous_definition);
3007 }
3008 }
3009
Chris Lattner3bfce182009-03-21 08:03:33 +00003010 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00003011 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3012 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3013
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003014 // (If global is requested for a definition, we always need to create a new
3015 // global, not just return a bitcast.)
3016 if (!IsForDefinition)
3017 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00003018 }
Mike Stump11289f42009-09-09 15:08:12 +00003019
Yaxun Liucbf647c2017-07-08 13:24:52 +00003020 auto AddrSpace = GetGlobalVarAddressSpace(D);
3021 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3022
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003023 auto *GV = new llvm::GlobalVariable(
3024 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00003025 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Yaxun Liucbf647c2017-07-08 13:24:52 +00003026 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00003027
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003028 // If we already created a global with the same mangled name (but different
3029 // type) before, take its name and remove it from its parent.
3030 if (Entry) {
3031 GV->takeName(Entry);
3032
3033 if (!Entry->use_empty()) {
3034 llvm::Constant *NewPtrForOldDecl =
3035 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3036 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3037 }
3038
3039 Entry->eraseFromParent();
3040 }
3041
Chris Lattner45470942009-03-21 09:44:56 +00003042 // This is the first use or definition of a mangled name. If there is a
3043 // deferred decl with this name, remember that we need to emit it at the end
3044 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00003045 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00003046 if (DDI != DeferredDecls.end()) {
3047 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3048 // list, and remove it from DeferredDecls (since we don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00003049 addDeferredDeclToEmit(DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00003050 DeferredDecls.erase(DDI);
3051 }
Mike Stump11289f42009-09-09 15:08:12 +00003052
Chris Lattner3bfce182009-03-21 08:03:33 +00003053 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00003054 if (D) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003055 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3056 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3057
Mike Stump18bb9282009-05-16 07:57:57 +00003058 // FIXME: This code is overly simple and should be merged with other global
3059 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00003060 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00003061
Ulrich Weigand46084382015-04-21 17:27:59 +00003062 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3063
Jake Ehrlichba874ad2017-11-29 00:54:20 +00003064 setLinkageForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00003065
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003066 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00003067 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003068 CXXThreadLocals.push_back(D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +00003069 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003070 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00003071
Rafael Espindola3dd49812018-02-23 00:22:15 +00003072 setGVProperties(GV, D);
3073
Hans Wennborgfeedf852013-11-21 00:15:56 +00003074 // If required by the ABI, treat declarations of static data members with
3075 // inline initializers as definitions.
Hans Wennborg56fc62b2014-07-17 20:25:23 +00003076 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Hans Wennborgfeedf852013-11-21 00:15:56 +00003077 EmitGlobalVarDefinition(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +00003078 }
Robert Lyttonf80d6882014-05-02 09:33:30 +00003079
Erich Keane99fdfb62017-09-26 23:42:34 +00003080 // Emit section information for extern variables.
3081 if (D->hasExternalStorage()) {
3082 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3083 GV->setSection(SA->getName());
3084 }
3085
Robert Lyttonf80d6882014-05-02 09:33:30 +00003086 // Handle XCore specific ABI requirements.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003087 if (getTriple().getArch() == llvm::Triple::xcore &&
Robert Lyttonf80d6882014-05-02 09:33:30 +00003088 D->getLanguageLinkage() == CLanguageLinkage &&
3089 D->getType().isConstant(Context) &&
3090 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3091 GV->setSection(".cp.rodata");
Mehdi Amini7cb1b302017-09-05 03:58:35 +00003092
3093 // Check if we a have a const declaration with an initializer, we may be
3094 // able to emit it as available_externally to expose it's value to the
3095 // optimizer.
3096 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3097 D->getType().isConstQualified() && !GV->hasInitializer() &&
3098 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3099 const auto *Record =
3100 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3101 bool HasMutableFields = Record && Record->hasMutableFields();
3102 if (!HasMutableFields) {
3103 const VarDecl *InitDecl;
3104 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3105 if (InitExpr) {
3106 ConstantEmitter emitter(*this);
3107 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3108 if (Init) {
3109 auto *InitType = Init->getType();
3110 if (GV->getType()->getElementType() != InitType) {
3111 // The type of the initializer does not match the definition.
3112 // This happens when an initializer has a different type from
3113 // the type of the global (because of padding at the end of a
3114 // structure for instance).
3115 GV->setName(StringRef());
3116 // Make a new global with the correct type, this is now guaranteed
3117 // to work.
3118 auto *NewGV = cast<llvm::GlobalVariable>(
3119 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
3120
3121 // Erase the old global, since it is no longer used.
George Burgess IV00f70bd2018-03-01 05:43:23 +00003122 GV->eraseFromParent();
Mehdi Amini7cb1b302017-09-05 03:58:35 +00003123 GV = NewGV;
3124 } else {
3125 GV->setInitializer(Init);
3126 GV->setConstant(true);
3127 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3128 }
3129 emitter.finalize(GV);
3130 }
3131 }
3132 }
3133 }
Chris Lattnerd4808922009-03-22 21:03:39 +00003134 }
Mike Stump11289f42009-09-09 15:08:12 +00003135
Alexander Richardson6d989432017-10-15 18:48:14 +00003136 LangAS ExpectedAS =
Yaxun Liucbf647c2017-07-08 13:24:52 +00003137 D ? D->getType().getAddressSpace()
Alexander Richardson6d989432017-10-15 18:48:14 +00003138 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
Benjamin Kramer6fbfdec2017-07-08 14:14:57 +00003139 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3140 Ty->getPointerAddressSpace());
Yaxun Liucbf647c2017-07-08 13:24:52 +00003141 if (AddrSpace != ExpectedAS)
3142 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3143 ExpectedAS, Ty);
Matt Arsenault00e65b22013-11-15 02:19:52 +00003144
3145 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00003146}
3147
Andrey Bokhankocab58582015-08-31 13:20:44 +00003148llvm::Constant *
3149CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
John McCalld195d4c2016-11-30 23:25:13 +00003150 ForDefinition_t IsForDefinition) {
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003151 const Decl *D = GD.getDecl();
3152 if (isa<CXXConstructorDecl>(D))
3153 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00003154 getFromCtorType(GD.getCtorType()),
3155 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3156 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003157 else if (isa<CXXDestructorDecl>(D))
3158 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00003159 getFromDtorType(GD.getDtorType()),
3160 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3161 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003162 else if (isa<CXXMethodDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00003163 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003164 cast<CXXMethodDecl>(D));
Andrey Bokhankocab58582015-08-31 13:20:44 +00003165 auto Ty = getTypes().GetFunctionType(*FInfo);
3166 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3167 IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003168 } else if (isa<FunctionDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00003169 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3170 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3171 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3172 IsForDefinition);
3173 } else
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003174 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003175 IsForDefinition);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003176}
Chris Lattnerd4808922009-03-22 21:03:39 +00003177
David Greenbe0c5b62018-09-12 14:09:06 +00003178llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3179 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3180 unsigned Alignment) {
Anders Carlssonda80af32011-01-29 18:20:20 +00003181 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00003182 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00003183
Anders Carlssonda80af32011-01-29 18:20:20 +00003184 if (GV) {
3185 // Check if the variable has the right type.
3186 if (GV->getType()->getElementType() == Ty)
3187 return GV;
3188
3189 // Because C++ name mangling, the only way we can end up with an already
3190 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00003191 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00003192 OldGV = GV;
3193 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003194
Anders Carlssonda80af32011-01-29 18:20:20 +00003195 // Create a new variable.
3196 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00003197 Linkage, nullptr, Name);
3198
Anders Carlssonda80af32011-01-29 18:20:20 +00003199 if (OldGV) {
3200 // Replace occurrences of the old variable if needed.
3201 GV->takeName(OldGV);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003202
Anders Carlssonda80af32011-01-29 18:20:20 +00003203 if (!OldGV->use_empty()) {
3204 llvm::Constant *NewPtrForOldDecl =
3205 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3206 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3207 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003208
Anders Carlssonda80af32011-01-29 18:20:20 +00003209 OldGV->eraseFromParent();
3210 }
Rafael Espindolacb92c192015-01-15 23:18:01 +00003211
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003212 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3213 !GV->hasAvailableExternallyLinkage())
3214 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00003215
David Greenbe0c5b62018-09-12 14:09:06 +00003216 GV->setAlignment(Alignment);
3217
Anders Carlssonda80af32011-01-29 18:20:20 +00003218 return GV;
3219}
3220
Chris Lattnerd4808922009-03-22 21:03:39 +00003221/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3222/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00003223/// then it will be created with the specified type instead of whatever the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003224/// normal requested type would be. If IsForDefinition is true, it is guaranteed
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003225/// that an actual global with type Ty will be returned, not conversion of a
3226/// variable with the same mangled name but some other type.
Chris Lattnerd4808922009-03-22 21:03:39 +00003227llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003228 llvm::Type *Ty,
John McCalld195d4c2016-11-30 23:25:13 +00003229 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00003230 assert(D->hasGlobalStorage() && "Not a global variable");
3231 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00003232 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00003233 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00003234
Chris Lattner2192fe52011-07-18 04:24:23 +00003235 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003236 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00003237
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003238 StringRef MangledName = getMangledName(D);
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003239 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00003240}
3241
3242/// CreateRuntimeVariable - Create a new runtime global variable with the
3243/// specified type and name.
3244llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00003245CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003246 StringRef Name) {
Rafael Espindola6ab4ae42018-03-21 01:30:16 +00003247 auto *Ret =
3248 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
3249 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3250 return Ret;
Chris Lattnerd4808922009-03-22 21:03:39 +00003251}
3252
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003253void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3254 assert(!D->getInit() && "Cannot emit definite definitions here!");
3255
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003256 StringRef MangledName = getMangledName(D);
3257 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3258
3259 // We already have a definition, not declaration, with the same mangled name.
3260 // Emitting of declaration is not required (and actually overwrites emitted
3261 // definition).
3262 if (GV && !GV->isDeclaration())
3263 return;
3264
3265 // If we have not seen a reference to this variable yet, place it into the
3266 // deferred declarations table to be emitted if needed later.
3267 if (!MustBeEmitted(D) && !GV) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003268 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003269 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00003270 }
3271
3272 // The tentative definition is the only definition.
Reid Kleckner953fe032015-12-05 01:52:14 +00003273 EmitGlobalVarDefinition(D);
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003274}
3275
Chris Lattner2192fe52011-07-18 04:24:23 +00003276CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00003277 return Context.toCharUnitsFromBits(
3278 getDataLayout().getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00003279}
3280
Alexander Richardson6d989432017-10-15 18:48:14 +00003281LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3282 LangAS AddrSpace = LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003283 if (LangOpts.OpenCL) {
Alexander Richardson6d989432017-10-15 18:48:14 +00003284 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003285 assert(AddrSpace == LangAS::opencl_global ||
3286 AddrSpace == LangAS::opencl_constant ||
3287 AddrSpace == LangAS::opencl_local ||
3288 AddrSpace >= LangAS::FirstTargetAddressSpace);
3289 return AddrSpace;
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003290 }
3291
Yaxun Liucbf647c2017-07-08 13:24:52 +00003292 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3293 if (D && D->hasAttr<CUDAConstantAttr>())
3294 return LangAS::cuda_constant;
3295 else if (D && D->hasAttr<CUDASharedAttr>())
3296 return LangAS::cuda_shared;
Yaxun Liua4005e12018-07-28 03:05:25 +00003297 else if (D && D->hasAttr<CUDADeviceAttr>())
3298 return LangAS::cuda_device;
3299 else if (D && D->getType().isConstQualified())
3300 return LangAS::cuda_constant;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003301 else
3302 return LangAS::cuda_device;
3303 }
3304
3305 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003306}
3307
Yaxun Liudaceb1e2018-05-14 19:20:12 +00003308LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3309 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3310 if (LangOpts.OpenCL)
3311 return LangAS::opencl_constant;
3312 if (auto AS = getTarget().getConstantAddressSpace())
3313 return AS.getValue();
3314 return LangAS::Default;
3315}
3316
3317// In address space agnostic languages, string literals are in default address
3318// space in AST. However, certain targets (e.g. amdgcn) request them to be
3319// emitted in constant address space in LLVM IR. To be consistent with other
3320// parts of AST, string literal global variables in constant address space
3321// need to be casted to default address space before being put into address
3322// map and referenced by other part of CodeGen.
3323// In OpenCL, string literals are in constant address space in AST, therefore
3324// they should not be casted to default address space.
3325static llvm::Constant *
3326castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3327 llvm::GlobalVariable *GV) {
3328 llvm::Constant *Cast = GV;
3329 if (!CGM.getLangOpts().OpenCL) {
3330 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3331 if (AS != LangAS::Default)
3332 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3333 CGM, GV, AS.getValue(), LangAS::Default,
3334 GV->getValueType()->getPointerTo(
3335 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3336 }
3337 }
3338 return Cast;
3339}
3340
Richard Smithdf931ce2013-04-06 05:00:46 +00003341template<typename SomeDecl>
3342void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3343 llvm::GlobalValue *GV) {
3344 if (!getLangOpts().CPlusPlus)
3345 return;
3346
3347 // Must have 'used' attribute, or else inline assembly can't rely on
3348 // the name existing.
3349 if (!D->template hasAttr<UsedAttr>())
3350 return;
3351
3352 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00003353 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00003354 return;
3355
3356 // Must be in an extern "C" context. Entities declared directly within
3357 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003358 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00003359 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00003360 return;
3361
3362 // OK, this is an internal linkage entity inside an extern "C" linkage
3363 // specification. Make a note of that so we can give it the "expected"
3364 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00003365 std::pair<StaticExternCMap::iterator, bool> R =
3366 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00003367
3368 // If we have multiple internal linkage entities with the same name
3369 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00003370 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00003371 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00003372}
3373
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003374static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3375 if (!CGM.supportsCOMDAT())
3376 return false;
3377
3378 if (D.hasAttr<SelectAnyAttr>())
3379 return true;
3380
3381 GVALinkage Linkage;
3382 if (auto *VD = dyn_cast<VarDecl>(&D))
3383 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3384 else
3385 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3386
3387 switch (Linkage) {
3388 case GVA_Internal:
3389 case GVA_AvailableExternally:
3390 case GVA_StrongExternal:
3391 return false;
3392 case GVA_DiscardableODR:
3393 case GVA_StrongODR:
3394 return true;
3395 }
3396 llvm_unreachable("No such linkage");
3397}
3398
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003399void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3400 llvm::GlobalObject &GO) {
3401 if (!shouldBeInCOMDAT(*this, D))
3402 return;
3403 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3404}
3405
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003406/// Pass IsTentative as true if you want to create a tentative definition.
3407void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3408 bool IsTentative) {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003409 // OpenCL global variables of sampler type are translated to function calls,
3410 // therefore no need to be translated.
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003411 QualType ASTTy = D->getType();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003412 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3413 return;
3414
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00003415 // If this is OpenMP device, check if it is legal to emit this global
3416 // normally.
3417 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3418 OpenMPRuntime->emitTargetGlobalVariable(D))
3419 return;
3420
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003421 llvm::Constant *Init = nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00003422 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3423 bool NeedsGlobalCtor = false;
3424 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00003425
Richard Smithdafff942012-01-14 04:30:29 +00003426 const VarDecl *InitDecl;
3427 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003428
John McCallde0fe072017-08-15 21:42:52 +00003429 Optional<ConstantEmitter> emitter;
3430
Artem Belevich97c01c32016-02-02 22:29:48 +00003431 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3432 // as part of their declaration." Sema has already checked for
3433 // error cases, so we just need to set Init to UndefValue.
3434 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
3435 D->hasAttr<CUDASharedAttr>())
Jingyue Wu284ebe22015-08-22 05:49:28 +00003436 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
Artem Belevich97c01c32016-02-02 22:29:48 +00003437 else if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00003438 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003439 // implicitly initialized with { 0 }.
3440 //
3441 // Note that tentative definitions are only emitted at the end of
3442 // a translation unit, so they should never have incomplete
3443 // type. In addition, EmitTentativeDefinition makes sure that we
3444 // never attempt to emit a tentative definition if a real one
3445 // exists. A use may still exists, however, so we still may need
3446 // to do a RAUW.
3447 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00003448 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003449 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003450 initializedGlobalDecl = GlobalDecl(D);
John McCallde0fe072017-08-15 21:42:52 +00003451 emitter.emplace(*this);
3452 Init = emitter->tryEmitForInitializer(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003453
Fariborz Jahanian63628032012-06-26 16:06:38 +00003454 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00003455 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00003456 if (D->getType()->isReferenceType())
3457 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00003458
David Blaikiebbafb8a2012-03-11 07:00:24 +00003459 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003460 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00003461 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003462 } else {
3463 ErrorUnsupported(D, "static initializer");
3464 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3465 }
John McCall70013b62010-07-15 23:40:35 +00003466 } else {
3467 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00003468 // initializer position (just in case this entry was delayed) if we
3469 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003470 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00003471 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00003472 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003473 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003474
Chris Lattner2192fe52011-07-18 04:24:23 +00003475 llvm::Type* InitType = Init->getType();
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003476 llvm::Constant *Entry =
John McCalld195d4c2016-11-30 23:25:13 +00003477 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
Mike Stump11289f42009-09-09 15:08:12 +00003478
Chris Lattner149927c2009-03-21 09:16:30 +00003479 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003480 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00003481 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00003482 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3483 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00003484 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00003485 Entry = CE->getOperand(0);
3486 }
Mike Stump11289f42009-09-09 15:08:12 +00003487
Chris Lattner149927c2009-03-21 09:16:30 +00003488 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003489 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003490
Chris Lattner149927c2009-03-21 09:16:30 +00003491 // We have a definition after a declaration with the wrong type.
3492 // We must make a new GlobalVariable* and update everything that used OldGV
3493 // (a declaration or tentative definition) with the new GlobalVariable*
3494 // (which will be a definition).
3495 //
3496 // This happens if there is a prototype for a global (e.g.
3497 // "extern int x[];") and then a definition of a different type (e.g.
3498 // "int x[10];"). This also happens when an initializer has a different type
3499 // from the type of the global (this happens with unions).
Yaxun Liucbf647c2017-07-08 13:24:52 +00003500 if (!GV || GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003501 GV->getType()->getAddressSpace() !=
Yaxun Liucbf647c2017-07-08 13:24:52 +00003502 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
Mike Stump11289f42009-09-09 15:08:12 +00003503
John McCall7ec50432010-03-19 23:29:14 +00003504 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003505 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00003506
Chris Lattner149927c2009-03-21 09:16:30 +00003507 // Make a new global with the correct type, this is now guaranteed to work.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003508 GV = cast<llvm::GlobalVariable>(
John McCalld195d4c2016-11-30 23:25:13 +00003509 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
Chris Lattnera85d68e2009-03-21 09:25:43 +00003510
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003511 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00003512 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00003513 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00003514 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003515
3516 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00003517 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00003518 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00003519
Richard Smithdf931ce2013-04-06 05:00:46 +00003520 MaybeHandleStaticInExternC(D, GV);
3521
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003522 if (D->hasAttr<AnnotateAttr>())
3523 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00003524
Artem Belevich42e19492016-03-02 18:28:50 +00003525 // Set the llvm linkage type as appropriate.
3526 llvm::GlobalValue::LinkageTypes Linkage =
3527 getLLVMLinkageVarDefinition(D, GV->isConstant());
3528
Jingyue Wu284ebe22015-08-22 05:49:28 +00003529 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3530 // the device. [...]"
3531 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3532 // __device__, declares a variable that: [...]
3533 // Is accessible from all the threads within the grid and from the host
3534 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3535 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
Artem Belevich42e19492016-03-02 18:28:50 +00003536 if (GV && LangOpts.CUDA) {
3537 if (LangOpts.CUDAIsDevice) {
3538 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3539 GV->setExternallyInitialized(true);
3540 } else {
3541 // Host-side shadows of external declarations of device-side
3542 // global variables become internal definitions. These have to
3543 // be internal in order to prevent name conflicts with global
3544 // host variables with the same name in a different TUs.
3545 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3546 Linkage = llvm::GlobalValue::InternalLinkage;
3547
3548 // Shadow variables and their properties must be registered
3549 // with CUDA runtime.
3550 unsigned Flags = 0;
3551 if (!D->hasDefinition())
3552 Flags |= CGCUDARuntime::ExternDeviceVar;
3553 if (D->hasAttr<CUDAConstantAttr>())
3554 Flags |= CGCUDARuntime::ConstantDeviceVar;
3555 getCUDARuntime().registerDeviceVar(*GV, Flags);
3556 } else if (D->hasAttr<CUDASharedAttr>())
3557 // __shared__ variables are odd. Shadows do get created, but
3558 // they are not registered with the CUDA runtime, so they
3559 // can't really be used to access their device-side
3560 // counterparts. It's not clear yet whether it's nvcc's bug or
3561 // a feature, but we've got to do the same for compatibility.
3562 Linkage = llvm::GlobalValue::InternalLinkage;
3563 }
Jingyue Wu284ebe22015-08-22 05:49:28 +00003564 }
John McCallde0fe072017-08-15 21:42:52 +00003565
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003566 GV->setInitializer(Init);
John McCallde0fe072017-08-15 21:42:52 +00003567 if (emitter) emitter->finalize(GV);
Chris Lattnerf49573d2009-08-05 05:20:29 +00003568
3569 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00003570 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3571 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00003572
Hans Wennborg899ded92014-10-16 20:52:46 +00003573 // If it is in a read-only section, mark it 'constant'.
3574 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3575 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3576 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3577 GV->setConstant(true);
3578 }
3579
Ken Dyck160146e2010-01-27 17:10:57 +00003580 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00003581
David Majnemer35ab3282014-06-11 04:08:55 +00003582
Manman Ren68150262015-11-11 22:42:31 +00003583 // On Darwin, if the normal linkage of a C++ thread_local variable is
3584 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3585 // copies within a linkage unit; otherwise, the backing variable has
3586 // internal linkage and all accesses should just be calls to the
David Majnemer35ab3282014-06-11 04:08:55 +00003587 // Itanium-specified entry point, which has the normal linkage of the
Manman Ren68150262015-11-11 22:42:31 +00003588 // variable. This is to preserve the ability to change the implementation
3589 // behind the scenes.
David Majnemerbb525f7c2014-10-15 22:38:23 +00003590 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00003591 Context.getTargetInfo().getTriple().isOSDarwin() &&
Manman Ren68150262015-11-11 22:42:31 +00003592 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3593 !llvm::GlobalVariable::isWeakLinkage(Linkage))
David Majnemerbb525f7c2014-10-15 22:38:23 +00003594 Linkage = llvm::GlobalValue::InternalLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00003595
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003596 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00003597 if (D->hasAttr<DLLImportAttr>())
3598 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3599 else if (D->hasAttr<DLLExportAttr>())
3600 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00003601 else
3602 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00003603
Yaxun Liu402804b2016-12-15 08:09:08 +00003604 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
Chris Lattnerf49573d2009-08-05 05:20:29 +00003605 // common vars aren't constant even if declared const.
3606 GV->setConstant(false);
Yaxun Liu402804b2016-12-15 08:09:08 +00003607 // Tentative definition of global variables may be initialized with
3608 // non-zero null pointers. In this case they should have weak linkage
3609 // since common linkage must have zero initializer and must not have
3610 // explicit section therefore cannot have non-zero initial value.
3611 if (!GV->getInitializer()->isNullValue())
3612 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3613 }
Daniel Dunbard272cca2009-04-10 20:26:50 +00003614
Rafael Espindola502f65a2014-05-05 20:21:03 +00003615 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00003616
David Majnemerbb525f7c2014-10-15 22:38:23 +00003617 if (D->getTLSKind() && !GV->isThreadLocal()) {
3618 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003619 CXXThreadLocals.push_back(D);
David Majnemerbb525f7c2014-10-15 22:38:23 +00003620 setTLSMode(GV, *D);
3621 }
3622
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003623 maybeSetTrivialComdat(*D, *GV);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003624
John McCallcdf7ef52010-11-06 09:44:32 +00003625 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00003626 if (NeedsGlobalCtor || NeedsGlobalDtor)
3627 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00003628
Alexey Samsonov4b8de112014-08-01 21:35:28 +00003629 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany28a26c82012-08-21 06:53:28 +00003630
Sanjiv Gupta158143a2008-06-05 08:59:10 +00003631 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00003632 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00003633 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00003634 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003635}
Chris Lattner09153c02007-06-22 18:48:09 +00003636
David Majnemerc017d362014-08-05 00:01:13 +00003637static bool isVarDeclStrongDefinition(const ASTContext &Context,
Nico Weber608e7682015-04-15 23:04:24 +00003638 CodeGenModule &CGM, const VarDecl *D,
3639 bool NoCommon) {
David Majnemer9832a3d2014-04-10 16:53:16 +00003640 // Don't give variables common linkage if -fno-common was specified unless it
3641 // was overridden by a NoCommon attribute.
3642 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3643 return true;
3644
3645 // C11 6.9.2/2:
3646 // A declaration of an identifier for an object that has file scope without
3647 // an initializer, and without a storage-class specifier or with the
3648 // storage-class specifier static, constitutes a tentative definition.
3649 if (D->getInit() || D->hasExternalStorage())
3650 return true;
3651
3652 // A variable cannot be both common and exist in a section.
3653 if (D->hasAttr<SectionAttr>())
3654 return true;
3655
Javed Absar2a67c9e2017-06-05 10:11:57 +00003656 // A variable cannot be both common and exist in a section.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003657 // We don't try to determine which is the right section in the front-end.
Javed Absar2a67c9e2017-06-05 10:11:57 +00003658 // If no specialized section name is applicable, it will resort to default.
3659 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3660 D->hasAttr<PragmaClangDataSectionAttr>() ||
3661 D->hasAttr<PragmaClangRodataSectionAttr>())
3662 return true;
3663
David Majnemer9832a3d2014-04-10 16:53:16 +00003664 // Thread local vars aren't considered common linkage.
3665 if (D->getTLSKind())
3666 return true;
3667
3668 // Tentative definitions marked with WeakImportAttr are true definitions.
3669 if (D->hasAttr<WeakImportAttr>())
3670 return true;
3671
Nico Weber608e7682015-04-15 23:04:24 +00003672 // A variable cannot be both common and exist in a comdat.
3673 if (shouldBeInCOMDAT(CGM, *D))
3674 return true;
3675
Sanjay Patel2f9303a2016-06-30 21:02:40 +00003676 // Declarations with a required alignment do not have common linkage in MSVC
David Majnemerc017d362014-08-05 00:01:13 +00003677 // mode.
David Majnemer3f021502015-10-08 04:53:31 +00003678 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemere1a0b2e2015-02-03 08:49:32 +00003679 if (D->hasAttr<AlignedAttr>())
3680 return true;
3681 QualType VarType = D->getType();
3682 if (Context.isAlignmentRequired(VarType))
3683 return true;
3684
3685 if (const auto *RT = VarType->getAs<RecordType>()) {
3686 const RecordDecl *RD = RT->getDecl();
3687 for (const FieldDecl *FD : RD->fields()) {
3688 if (FD->isBitField())
3689 continue;
3690 if (FD->hasAttr<AlignedAttr>())
3691 return true;
3692 if (Context.isAlignmentRequired(FD->getType()))
3693 return true;
3694 }
3695 }
3696 }
David Majnemerc017d362014-08-05 00:01:13 +00003697
David Majnemer9832a3d2014-04-10 16:53:16 +00003698 return false;
3699}
3700
Hans Wennborg1a3a0742014-05-14 19:54:53 +00003701llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00003702 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003703 if (Linkage == GVA_Internal)
3704 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003705
3706 if (D->hasAttr<WeakAttr>()) {
3707 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003708 return llvm::GlobalVariable::WeakODRLinkage;
3709 else
3710 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003711 }
3712
Erich Keane7ef210d2018-10-22 21:20:45 +00003713 if (const auto *FD = D->getAsFunction())
3714 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
3715 return llvm::GlobalVariable::LinkOnceAnyLinkage;
3716
David Majnemer27d69db2014-04-28 22:17:59 +00003717 // We are guaranteed to have a strong definition somewhere else,
3718 // so we can use available_externally linkage.
3719 if (Linkage == GVA_AvailableExternally)
David Blaikie9ffe5a32017-01-30 05:00:26 +00003720 return llvm::GlobalValue::AvailableExternallyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003721
David Majnemer27d69db2014-04-28 22:17:59 +00003722 // Note that Apple's kernel linker doesn't support symbol
3723 // coalescing, so we need to avoid linkonce and weak linkages there.
3724 // Normally, this means we just map to internal, but for explicit
3725 // instantiations we'll map to external.
3726
3727 // In C++, the compiler has to emit a definition in every translation unit
3728 // that references the function. We should use linkonce_odr because
3729 // a) if all references in this translation unit are optimized away, we
3730 // don't need to codegen it. b) if the function persists, it needs to be
3731 // merged with other definitions. c) C++ has the ODR, so we know the
3732 // definition is dependable.
3733 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00003734 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00003735 : llvm::Function::InternalLinkage;
3736
3737 // An explicit instantiation of a template has weak linkage, since
3738 // explicit instantiations can occur in multiple translation units
3739 // and must all be equivalent. However, we are not allowed to
3740 // throw away these explicit instantiations.
Justin Lebar27ee1302016-06-30 18:41:33 +00003741 //
3742 // We don't currently support CUDA device code spread out across multiple TUs,
3743 // so say that CUDA templates are either external (for kernels) or internal.
3744 // This lets llvm perform aggressive inter-procedural optimizations.
3745 if (Linkage == GVA_StrongODR) {
3746 if (Context.getLangOpts().AppleKext)
3747 return llvm::Function::ExternalLinkage;
3748 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3749 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3750 : llvm::Function::InternalLinkage;
3751 return llvm::Function::WeakODRLinkage;
3752 }
David Majnemer27d69db2014-04-28 22:17:59 +00003753
David Majnemer27d69db2014-04-28 22:17:59 +00003754 // C++ doesn't have tentative definitions and thus cannot have common
3755 // linkage.
3756 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Nico Weber608e7682015-04-15 23:04:24 +00003757 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
David Majnemerc017d362014-08-05 00:01:13 +00003758 CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00003759 return llvm::GlobalVariable::CommonLinkage;
3760
David Majnemer27d69db2014-04-28 22:17:59 +00003761 // selectany symbols are externally visible, so use weak instead of
3762 // linkonce. MSVC optimizes away references to const selectany globals, so
3763 // all definitions should be the same and ODR linkage should be used.
3764 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3765 if (D->hasAttr<SelectAnyAttr>())
3766 return llvm::GlobalVariable::WeakODRLinkage;
3767
3768 // Otherwise, we have strong external linkage.
3769 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003770 return llvm::GlobalVariable::ExternalLinkage;
3771}
3772
David Majnemer27d69db2014-04-28 22:17:59 +00003773llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3774 const VarDecl *VD, bool IsConstant) {
3775 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00003776 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00003777}
3778
John McCall49954ca2012-12-12 22:21:47 +00003779/// Replace the uses of a function that was declared with a non-proto type.
3780/// We want to silently drop extra arguments from call sites
3781static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3782 llvm::Function *newFn) {
3783 // Fast path.
3784 if (old->use_empty()) return;
3785
3786 llvm::Type *newRetTy = newFn->getReturnType();
3787 SmallVector<llvm::Value*, 4> newArgs;
David Majnemer0b17d442015-12-15 21:27:59 +00003788 SmallVector<llvm::OperandBundleDef, 1> newBundles;
John McCall49954ca2012-12-12 22:21:47 +00003789
3790 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3791 ui != ue; ) {
3792 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003793 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00003794
3795 // Recognize and replace uses of bitcasts. Most calls to
3796 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003797 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00003798 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3799 replaceUsesOfNonProtoConstant(bitcast, newFn);
3800 continue;
3801 }
3802
3803 // Recognize calls to the function.
3804 llvm::CallSite callSite(user);
3805 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003806 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00003807
3808 // If the return types don't match exactly, then we can't
3809 // transform this call unless it's dead.
3810 if (callSite->getType() != newRetTy && !callSite->use_empty())
3811 continue;
3812
3813 // Get the call site's attribute list.
Reid Kleckner7f720332017-04-13 00:58:09 +00003814 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
Reid Klecknerde864822017-03-21 16:57:30 +00003815 llvm::AttributeList oldAttrs = callSite.getAttributes();
John McCall49954ca2012-12-12 22:21:47 +00003816
John McCall49954ca2012-12-12 22:21:47 +00003817 // If the function was passed too few arguments, don't transform.
3818 unsigned newNumArgs = newFn->arg_size();
3819 if (callSite.arg_size() < newNumArgs) continue;
3820
3821 // If extra arguments were passed, we silently drop them.
3822 // If any of the types mismatch, we don't transform.
3823 unsigned argNo = 0;
3824 bool dontTransform = false;
Reid Kleckner7f720332017-04-13 00:58:09 +00003825 for (llvm::Argument &A : newFn->args()) {
3826 if (callSite.getArgument(argNo)->getType() != A.getType()) {
John McCall49954ca2012-12-12 22:21:47 +00003827 dontTransform = true;
3828 break;
3829 }
3830
3831 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00003832 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
Reid Kleckner7f720332017-04-13 00:58:09 +00003833 argNo++;
John McCall49954ca2012-12-12 22:21:47 +00003834 }
3835 if (dontTransform)
3836 continue;
3837
John McCall49954ca2012-12-12 22:21:47 +00003838 // Okay, we can transform this. Create the new call instruction and copy
3839 // over the required information.
3840 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3841
David Majnemer0b17d442015-12-15 21:27:59 +00003842 // Copy over any operand bundles.
3843 callSite.getOperandBundlesAsDefs(newBundles);
3844
John McCall49954ca2012-12-12 22:21:47 +00003845 llvm::CallSite newCall;
3846 if (callSite.isCall()) {
David Majnemer0b17d442015-12-15 21:27:59 +00003847 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003848 callSite.getInstruction());
3849 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003850 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCall49954ca2012-12-12 22:21:47 +00003851 newCall = llvm::InvokeInst::Create(newFn,
3852 oldInvoke->getNormalDest(),
3853 oldInvoke->getUnwindDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003854 newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003855 callSite.getInstruction());
3856 }
3857 newArgs.clear(); // for the next iteration
3858
3859 if (!newCall->getType()->isVoidTy())
3860 newCall->takeName(callSite.getInstruction());
Reid Kleckner7f720332017-04-13 00:58:09 +00003861 newCall.setAttributes(llvm::AttributeList::get(
3862 newFn->getContext(), oldAttrs.getFnAttributes(),
3863 oldAttrs.getRetAttributes(), newArgAttrs));
John McCall49954ca2012-12-12 22:21:47 +00003864 newCall.setCallingConv(callSite.getCallingConv());
3865
3866 // Finally, remove the old call, replacing any uses with the new one.
3867 if (!callSite->use_empty())
3868 callSite->replaceAllUsesWith(newCall.getInstruction());
3869
3870 // Copy debug location attached to CI.
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00003871 if (callSite->getDebugLoc())
John McCall49954ca2012-12-12 22:21:47 +00003872 newCall->setDebugLoc(callSite->getDebugLoc());
David Majnemer0b17d442015-12-15 21:27:59 +00003873
John McCall49954ca2012-12-12 22:21:47 +00003874 callSite->eraseFromParent();
3875 }
3876}
3877
Chris Lattner36797ab2009-05-05 06:16:31 +00003878/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3879/// implement a function with no prototype, e.g. "int foo() {}". If there are
3880/// existing call uses of the old function in the module, this adjusts them to
3881/// call the new function directly.
3882///
3883/// This is not just a cleanup: the always_inline pass requires direct calls to
3884/// functions to be able to inline them. If there is a bitcast in the way, it
3885/// won't inline them. Instcombine normally deletes these calls, but it isn't
3886/// run at -O0.
3887static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3888 llvm::Function *NewFn) {
3889 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00003890 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00003891
John McCall49954ca2012-12-12 22:21:47 +00003892 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00003893}
3894
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003895void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
David Majnemer60e5bdc2016-07-11 04:28:21 +00003896 auto DK = VD->isThisDeclarationADefinition();
3897 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3898 return;
3899
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003900 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3901 // If we have a definition, this might be a deferred decl. If the
3902 // instantiation is explicit, make sure we emit it at the end.
3903 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3904 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003905
3906 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00003907}
Daniel Dunbar9c426522008-07-29 23:18:29 +00003908
Rafael Espindolacd7743b2013-12-09 16:01:03 +00003909void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3910 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003911 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00003912
John McCall46288ef2011-03-09 08:12:35 +00003913 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00003914 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3915 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00003916
Chris Lattnereb7466d2009-05-12 20:58:15 +00003917 // Get or create the prototype for the function.
Andrey Bokhankocab58582015-08-31 13:20:44 +00003918 if (!GV || (GV->getType()->getElementType() != Ty))
3919 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3920 /*DontDefer=*/true,
John McCalld195d4c2016-11-30 23:25:13 +00003921 ForDefinition));
Mike Stump11289f42009-09-09 15:08:12 +00003922
Andrey Bokhankocab58582015-08-31 13:20:44 +00003923 // Already emitted.
3924 if (!GV->isDeclaration())
Renato Golinc640ff62015-04-15 08:44:40 +00003925 return;
Mike Stump11289f42009-09-09 15:08:12 +00003926
John McCall8e7cb6d2010-11-02 21:04:24 +00003927 // We need to set linkage and visibility on the function before
3928 // generating code for it because various parts of IR generation
3929 // want to propagate this information down (e.g. to local static
3930 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003931 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00003932 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003933
Rafael Espindolae033c8c2014-05-08 15:26:12 +00003934 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Rafael Espindolab7350042018-03-01 00:35:47 +00003935 setGVProperties(Fn, GD);
John McCall8e7cb6d2010-11-02 21:04:24 +00003936
Richard Smithdf931ce2013-04-06 05:00:46 +00003937 MaybeHandleStaticInExternC(D, Fn);
3938
Yaxun Liu4306f202018-04-20 17:01:03 +00003939
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003940 maybeSetTrivialComdat(*D, *Fn);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003941
John McCalla738c252011-03-09 04:27:21 +00003942 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00003943
Rafael Espindolae4e78132018-03-01 00:00:02 +00003944 setNonAliasAttributes(GD, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00003945 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00003946
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003947 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003948 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003949 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003950 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003951 if (D->hasAttr<AnnotateAttr>())
3952 AddGlobalAnnotations(D, Fn);
Erich Keane3efe0022018-07-20 14:13:28 +00003953
3954 if (D->isCPUSpecificMultiVersion()) {
3955 auto *Spec = D->getAttr<CPUSpecificAttr>();
3956 // If there is another specific version we need to emit, do so here.
3957 if (Spec->ActiveArgIndex + 1 < Spec->cpus_size()) {
3958 ++Spec->ActiveArgIndex;
3959 EmitGlobalFunctionDefinition(GD, nullptr);
3960 }
3961 }
Daniel Dunbar9c426522008-07-29 23:18:29 +00003962}
3963
John McCall7ec50432010-03-19 23:29:14 +00003964void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003965 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003966 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00003967 assert(AA && "Not an alias?");
3968
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003969 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00003970
Hal Finkel0e2b9752015-09-04 21:49:21 +00003971 if (AA->getAliasee() == MangledName) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003972 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Hal Finkel0e2b9752015-09-04 21:49:21 +00003973 return;
3974 }
3975
John McCall7ec50432010-03-19 23:29:14 +00003976 // If there is a definition in the module, then it wins over the alias.
3977 // This is dubious, but allow it to be safe. Just ignore the alias.
3978 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3979 if (Entry && !Entry->isDeclaration())
3980 return;
3981
Rafael Espindola208b5c02013-10-22 19:26:13 +00003982 Aliases.push_back(GD);
3983
Chris Lattner2192fe52011-07-18 04:24:23 +00003984 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00003985
3986 // Create a reference to the named value. This ensures that it is emitted
3987 // if a deferred decl.
3988 llvm::Constant *Aliasee;
3989 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00003990 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00003991 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00003992 else
John McCall7ec50432010-03-19 23:29:14 +00003993 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00003994 llvm::PointerType::getUnqual(DeclTy),
David Majnemerbb525f7c2014-10-15 22:38:23 +00003995 /*D=*/nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00003996
3997 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00003998 auto *GA = llvm::GlobalAlias::create(
David Blaikie2a791d72015-09-14 18:38:22 +00003999 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00004000
Chris Lattner54041692009-03-22 21:47:11 +00004001 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00004002 if (GA->getAliasee() == Entry) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004003 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Rafael Espindolab2633b92014-05-16 19:35:48 +00004004 return;
4005 }
4006
John McCall7ec50432010-03-19 23:29:14 +00004007 assert(Entry->isDeclaration());
4008
Chris Lattner54041692009-03-22 21:47:11 +00004009 // If there is a declaration in the module, then we had an extern followed
4010 // by the alias, as in:
4011 // extern int test6();
4012 // ...
4013 // int test6() __attribute__((alias("test7")));
4014 //
4015 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00004016 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00004017
Owen Andersonade90fd2009-07-29 18:54:39 +00004018 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00004019 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00004020 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00004021 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00004022 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00004023 }
Mike Stump11289f42009-09-09 15:08:12 +00004024
Daniel Dunbar38932572009-04-14 08:05:55 +00004025 // Set attributes which are particular to an alias; this is a
4026 // specialization of the attributes which may be set on a global
4027 // variable/function.
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00004028 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4029 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00004030 GA->setLinkage(llvm::Function::WeakAnyLinkage);
4031 }
4032
David Majnemerbb525f7c2014-10-15 22:38:23 +00004033 if (const auto *VD = dyn_cast<VarDecl>(D))
4034 if (VD->getTLSKind())
4035 setTLSMode(GA, *VD);
4036
Rafael Espindolab7350042018-03-01 00:35:47 +00004037 SetCommonAttributes(GD, GA);
Chris Lattner54041692009-03-22 21:47:11 +00004038}
4039
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004040void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4041 const auto *D = cast<ValueDecl>(GD.getDecl());
4042 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4043 assert(IFA && "Not an ifunc?");
4044
4045 StringRef MangledName = getMangledName(GD);
4046
4047 if (IFA->getResolver() == MangledName) {
4048 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4049 return;
4050 }
4051
4052 // Report an error if some definition overrides ifunc.
4053 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4054 if (Entry && !Entry->isDeclaration()) {
4055 GlobalDecl OtherGD;
4056 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4057 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00004058 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4059 << MangledName;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004060 Diags.Report(OtherGD.getDecl()->getLocation(),
4061 diag::note_previous_definition);
4062 }
4063 return;
4064 }
4065
4066 Aliases.push_back(GD);
4067
4068 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4069 llvm::Constant *Resolver =
4070 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4071 /*ForVTable=*/false);
4072 llvm::GlobalIFunc *GIF =
4073 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4074 "", Resolver, &getModule());
4075 if (Entry) {
4076 if (GIF->getResolver() == Entry) {
4077 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4078 return;
4079 }
4080 assert(Entry->isDeclaration());
4081
4082 // If there is a declaration in the module, then we had an extern followed
4083 // by the ifunc, as in:
4084 // extern int test();
4085 // ...
4086 // int test() __attribute__((ifunc("resolver")));
4087 //
4088 // Remove it and replace uses of it with the ifunc.
4089 GIF->takeName(Entry);
4090
4091 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4092 Entry->getType()));
4093 Entry->eraseFromParent();
4094 } else
4095 GIF->setName(MangledName);
4096
Rafael Espindola75c649c2018-03-01 00:06:55 +00004097 SetCommonAttributes(GD, GIF);
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004098}
4099
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00004100llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00004101 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00004102 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00004103 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00004104}
Chris Lattner1eec6602007-08-31 04:31:45 +00004105
David Blaikie2e804282015-04-05 22:47:07 +00004106static llvm::StringMapEntry<llvm::GlobalVariable *> &
4107GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4108 const StringLiteral *Literal, bool TargetIsLSB,
4109 bool &IsUTF16, unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004110 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004111 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00004112
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00004113 // Check for simple case.
4114 if (!Literal->containsNonAsciiOrNull()) {
4115 StringLength = NumBytes;
David Blaikie13156b62014-11-19 03:06:06 +00004116 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00004117 }
4118
Bill Wendling82b87f12012-03-30 00:26:17 +00004119 // Otherwise, convert the UTF8 literals into a string of shorts.
4120 IsUTF16 = true;
4121
Justin Lebar90910552016-09-30 00:38:45 +00004122 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4123 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4124 llvm::UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00004125
Justin Lebar90910552016-09-30 00:38:45 +00004126 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4127 ToPtr + NumBytes, llvm::strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00004128
Daniel Dunbar91ade142009-07-23 23:41:22 +00004129 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00004130 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00004131
Bill Wendling82b87f12012-03-30 00:26:17 +00004132 // Add an explicit null.
4133 *ToPtr = 0;
David Blaikie13156b62014-11-19 03:06:06 +00004134 return *Map.insert(std::make_pair(
4135 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4136 (StringLength + 1) * 2),
4137 nullptr)).first;
Daniel Dunbar64509b22009-07-23 22:52:48 +00004138}
4139
John McCall7f416cc2015-09-08 08:05:57 +00004140ConstantAddress
Daniel Dunbar64509b22009-07-23 22:52:48 +00004141CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4142 unsigned StringLength = 0;
4143 bool isUTF16 = false;
David Blaikie2e804282015-04-05 22:47:07 +00004144 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4145 GetConstantCFStringEntry(CFConstantStringMap, Literal,
4146 getDataLayout().isLittleEndian(), isUTF16,
4147 StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00004148
David Blaikie13156b62014-11-19 03:06:06 +00004149 if (auto *C = Entry.second)
John McCall7f416cc2015-09-08 08:05:57 +00004150 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Mike Stump11289f42009-09-09 15:08:12 +00004151
Chris Lattnerece04092012-02-07 00:39:47 +00004152 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00004153 llvm::Constant *Zeros[] = { Zero, Zero };
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004154
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004155 const ASTContext &Context = getContext();
4156 const llvm::Triple &Triple = getTriple();
4157
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004158 const auto CFRuntime = getLangOpts().CFRuntime;
4159 const bool IsSwiftABI =
4160 static_cast<unsigned>(CFRuntime) >=
4161 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4162 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4163
Chris Lattneraa64ca22009-07-16 16:48:25 +00004164 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00004165 if (!CFConstantStringClassRef) {
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004166 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
Chris Lattner2192fe52011-07-18 04:24:23 +00004167 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00004168 Ty = llvm::ArrayType::get(Ty, 0);
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004169
4170 switch (CFRuntime) {
4171 default: break;
4172 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
Saleem Abdulrasool0c16a132018-10-25 17:52:13 +00004173 case LangOptions::CoreFoundationABI::Swift5_0:
4174 CFConstantStringClassName =
4175 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4176 : "$S10Foundation19_NSCFConstantStringCN";
4177 Ty = IntPtrTy;
4178 break;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004179 case LangOptions::CoreFoundationABI::Swift4_2:
4180 CFConstantStringClassName =
4181 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4182 : "$s10Foundation19_NSCFConstantStringCN";
4183 Ty = IntPtrTy;
4184 break;
4185 case LangOptions::CoreFoundationABI::Swift4_1:
4186 CFConstantStringClassName =
4187 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4188 : "__T010Foundation19_NSCFConstantStringCN";
4189 Ty = IntPtrTy;
4190 break;
4191 }
4192
4193 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004194
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004195 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
Kristina Brooks34e24d52018-09-25 22:27:40 +00004196 llvm::GlobalValue *GV = nullptr;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004197
Kristina Brooks34e24d52018-09-25 22:27:40 +00004198 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004199 IdentifierInfo &II = Context.Idents.get(GV->getName());
4200 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
Kristina Brooks34e24d52018-09-25 22:27:40 +00004201 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00004202
Kristina Brooks34e24d52018-09-25 22:27:40 +00004203 const VarDecl *VD = nullptr;
4204 for (const auto &Result : DC->lookup(&II))
4205 if ((VD = dyn_cast<VarDecl>(Result)))
4206 break;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004207
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004208 if (Triple.isOSBinFormatELF()) {
Kristina Brooks34e24d52018-09-25 22:27:40 +00004209 if (!VD)
4210 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004211 } else {
4212 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4213 if (!VD || !VD->hasAttr<DLLExportAttr>())
Kristina Brooks34e24d52018-09-25 22:27:40 +00004214 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004215 else
Kristina Brooks34e24d52018-09-25 22:27:40 +00004216 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Kristina Brooks34e24d52018-09-25 22:27:40 +00004217 }
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004218
Kristina Brooks34e24d52018-09-25 22:27:40 +00004219 setDSOLocal(GV);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00004220 }
4221 }
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004222
Daniel Dunbard644ad62008-08-23 18:37:06 +00004223 // Decay array -> ptr
Saleem Abdulrasool4fab7452016-09-11 01:25:15 +00004224 CFConstantStringClassRef =
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004225 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4226 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004227 }
Mike Stump11289f42009-09-09 15:08:12 +00004228
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004229 QualType CFTy = Context.getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00004230
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004231 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00004232
John McCall23c9dc62016-11-28 22:18:27 +00004233 ConstantInitBuilder Builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00004234 auto Fields = Builder.beginStruct(STy);
Douglas Gregor91f84212008-12-11 16:49:14 +00004235
Anders Carlssonb04ea612007-08-21 00:21:21 +00004236 // Class pointer.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004237 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
Mike Stump11289f42009-09-09 15:08:12 +00004238
Anders Carlssonb04ea612007-08-21 00:21:21 +00004239 // Flags.
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004240 if (IsSwiftABI) {
4241 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4242 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4243 } else {
4244 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4245 }
Anders Carlsson157c3212009-08-16 05:55:31 +00004246
Anders Carlssonb04ea612007-08-21 00:21:21 +00004247 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00004248 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00004249 if (isUTF16) {
Craig Topperc005cc02015-09-27 03:44:08 +00004250 auto Arr = llvm::makeArrayRef(
David Blaikie13156b62014-11-19 03:06:06 +00004251 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4252 Entry.first().size() / 2);
Bill Wendling82b87f12012-03-30 00:26:17 +00004253 C = llvm::ConstantDataArray::get(VMContext, Arr);
4254 } else {
David Blaikie13156b62014-11-19 03:06:06 +00004255 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling82b87f12012-03-30 00:26:17 +00004256 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00004257
Bill Wendling86131f22012-01-10 08:46:39 +00004258 // Note: -fwritable-strings doesn't make the backing store strings of
4259 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004260 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00004261 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4262 llvm::GlobalValue::PrivateLinkage, C, ".str");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004263 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigandfa806422013-05-06 16:23:57 +00004264 // Don't enforce the target's minimum global alignment, since the only use
4265 // of the string is via this class initializer.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004266 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4267 : Context.getTypeAlignInChars(Context.CharTy);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004268 GV->setAlignment(Align.getQuantity());
4269
4270 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4271 // Without it LLVM can merge the string with a non unnamed_addr one during
4272 // LTO. Doing that changes the section it ends in, which surprises ld64.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004273 if (Triple.isOSBinFormatMachO())
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004274 GV->setSection(isUTF16 ? "__TEXT,__ustring"
4275 : "__TEXT,__cstring,cstring_literals");
Kristina Brooks34e24d52018-09-25 22:27:40 +00004276 // Make sure the literal ends up in .rodata to allow for safe ICF and for
4277 // the static linker to adjust permissions to read-only later on.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004278 else if (Triple.isOSBinFormatELF())
Kristina Brooks34e24d52018-09-25 22:27:40 +00004279 GV->setSection(".rodata");
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004280
Bill Wendling82b87f12012-03-30 00:26:17 +00004281 // String.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004282 llvm::Constant *Str =
David Blaikied3c127e2015-05-07 17:27:56 +00004283 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00004284
Bill Wendling82b87f12012-03-30 00:26:17 +00004285 if (isUTF16)
4286 // Cast the UTF16 string to the correct type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004287 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4288 Fields.add(Str);
Bill Wendling82b87f12012-03-30 00:26:17 +00004289
Anders Carlssonb04ea612007-08-21 00:21:21 +00004290 // String length.
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004291 llvm::IntegerType *LengthTy =
4292 llvm::IntegerType::get(getModule().getContext(),
4293 Context.getTargetInfo().getLongWidth());
4294 if (IsSwiftABI) {
4295 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4296 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4297 LengthTy = Int32Ty;
4298 else
4299 LengthTy = IntPtrTy;
4300 }
4301 Fields.addInt(LengthTy, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00004302
John McCall7f416cc2015-09-08 08:05:57 +00004303 CharUnits Alignment = getPointerAlign();
4304
Anders Carlssonb04ea612007-08-21 00:21:21 +00004305 // The struct.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004306 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4307 /*isConstant=*/false,
4308 llvm::GlobalVariable::PrivateLinkage);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004309 switch (Triple.getObjectFormat()) {
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004310 case llvm::Triple::UnknownObjectFormat:
4311 llvm_unreachable("unknown file format");
4312 case llvm::Triple::COFF:
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004313 case llvm::Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00004314 case llvm::Triple::Wasm:
Saleem Abdulrasool0295f8c2016-07-09 01:59:51 +00004315 GV->setSection("cfstring");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004316 break;
4317 case llvm::Triple::MachO:
4318 GV->setSection("__DATA,__cfstring");
4319 break;
4320 }
David Blaikie13156b62014-11-19 03:06:06 +00004321 Entry.second = GV;
Mike Stump11289f42009-09-09 15:08:12 +00004322
John McCall7f416cc2015-09-08 08:05:57 +00004323 return ConstantAddress(GV, Alignment);
Anders Carlssonb04ea612007-08-21 00:21:21 +00004324}
Chris Lattnerfb300092007-11-28 05:34:05 +00004325
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +00004326bool CodeGenModule::getExpressionLocationsEnabled() const {
4327 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4328}
4329
Douglas Gregor636e2002011-08-09 17:23:49 +00004330QualType CodeGenModule::getObjCFastEnumerationStateType() {
4331 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004332 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00004333 D->startDefinition();
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004334
Douglas Gregor636e2002011-08-09 17:23:49 +00004335 QualType FieldTypes[] = {
4336 Context.UnsignedLongTy,
4337 Context.getPointerType(Context.getObjCIdType()),
4338 Context.getPointerType(Context.UnsignedLongTy),
4339 Context.getConstantArrayType(Context.UnsignedLongTy,
4340 llvm::APInt(32, 5), ArrayType::Normal, 0)
4341 };
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004342
Douglas Gregor636e2002011-08-09 17:23:49 +00004343 for (size_t i = 0; i < 4; ++i) {
4344 FieldDecl *Field = FieldDecl::Create(Context,
4345 D,
4346 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004347 SourceLocation(), nullptr,
4348 FieldTypes[i], /*TInfo=*/nullptr,
4349 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00004350 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004351 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00004352 Field->setAccess(AS_public);
4353 D->addDecl(Field);
4354 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004355
Douglas Gregor636e2002011-08-09 17:23:49 +00004356 D->completeDefinition();
4357 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4358 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004359
Douglas Gregor636e2002011-08-09 17:23:49 +00004360 return ObjCFastEnumerationStateType;
4361}
4362
Eli Friedmanfcec6302011-11-01 02:23:42 +00004363llvm::Constant *
4364CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4365 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004366
Eli Friedmanfcec6302011-11-01 02:23:42 +00004367 // Don't emit it as the address of the string, emit the string data itself
4368 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00004369 if (E->getCharByteWidth() == 1) {
4370 SmallString<64> Str(E->getString());
4371
4372 // Resize the string to the right size, which is indicated by its type.
4373 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4374 Str.resize(CAT->getSize().getZExtValue());
4375 return llvm::ConstantDataArray::getString(VMContext, Str, false);
4376 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004377
4378 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00004379 llvm::Type *ElemTy = AType->getElementType();
4380 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00004381
4382 // Wide strings have either 2-byte or 4-byte elements.
4383 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4384 SmallVector<uint16_t, 32> Elements;
4385 Elements.reserve(NumElements);
4386
4387 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4388 Elements.push_back(E->getCodeUnit(i));
4389 Elements.resize(NumElements);
4390 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00004391 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004392
Chris Lattner02cb1712012-02-06 22:52:04 +00004393 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4394 SmallVector<uint32_t, 32> Elements;
4395 Elements.reserve(NumElements);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004396
Chris Lattner02cb1712012-02-06 22:52:04 +00004397 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4398 Elements.push_back(E->getCodeUnit(i));
4399 Elements.resize(NumElements);
4400 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00004401}
4402
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004403static llvm::GlobalVariable *
4404GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4405 CodeGenModule &CGM, StringRef GlobalName,
John McCall7f416cc2015-09-08 08:05:57 +00004406 CharUnits Alignment) {
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004407 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4408 CGM.getStringLiteralAddressSpace());
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004409
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004410 llvm::Module &M = CGM.getModule();
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004411 // Create a global variable for this string
4412 auto *GV = new llvm::GlobalVariable(
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004413 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4414 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +00004415 GV->setAlignment(Alignment.getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004416 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004417 if (GV->isWeakForLinker()) {
4418 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4419 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4420 }
Rafael Espindola0d40f122018-03-20 20:42:55 +00004421 CGM.setDSOLocal(GV);
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004422
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004423 return GV;
4424}
4425
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004426/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4427/// constant array for the given string literal.
John McCall7f416cc2015-09-08 08:05:57 +00004428ConstantAddress
Alexey Bataevec474782014-10-09 08:45:04 +00004429CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4430 StringRef Name) {
John McCall7f416cc2015-09-08 08:05:57 +00004431 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
James Molloye735b2b2014-05-09 16:28:56 +00004432
Richard Smith00db2f12014-07-29 21:20:12 +00004433 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4434 llvm::GlobalVariable **Entry = nullptr;
David Majnemer58e5bee2014-03-24 21:43:36 +00004435 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004436 Entry = &ConstantStringMap[C];
4437 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004438 if (Alignment.getQuantity() > GV->getAlignment())
4439 GV->setAlignment(Alignment.getQuantity());
4440 return ConstantAddress(GV, Alignment);
David Majnemer58e5bee2014-03-24 21:43:36 +00004441 }
Eli Friedman49ddc5f2009-11-16 05:55:46 +00004442 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00004443
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004444 SmallString<256> MangledNameBuffer;
4445 StringRef GlobalVariableName;
4446 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00004447
Reid Kleckner7a368962018-09-06 18:25:39 +00004448 // Mangle the string literal if that's how the ABI merges duplicate strings.
4449 // Don't do it if they are writable, since we don't want writes in one TU to
4450 // affect strings in another.
4451 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4452 !LangOpts.WritableStrings) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004453 llvm::raw_svector_ostream Out(MangledNameBuffer);
4454 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004455 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4456 GlobalVariableName = MangledNameBuffer;
4457 } else {
4458 LT = llvm::GlobalValue::PrivateLinkage;
Alexey Bataevec474782014-10-09 08:45:04 +00004459 GlobalVariableName = Name;
David Majnemer58e5bee2014-03-24 21:43:36 +00004460 }
4461
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004462 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4463 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004464 *Entry = GV;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00004465
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00004466 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4467 QualType());
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004468
4469 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4470 Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004471}
4472
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004473/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4474/// array for the given ObjCEncodeExpr node.
John McCall7f416cc2015-09-08 08:05:57 +00004475ConstantAddress
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004476CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4477 std::string Str;
4478 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00004479
4480 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004481}
4482
Alexey Samsonovadc90372014-06-04 20:25:57 +00004483/// GetAddrOfConstantCString - Returns a pointer to a character array containing
4484/// the literal and a terminating '\0' character.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004485/// The result has pointer to array type.
John McCall7f416cc2015-09-08 08:05:57 +00004486ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4487 const std::string &Str, const char *GlobalName) {
Alexey Samsonovadc90372014-06-04 20:25:57 +00004488 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall7f416cc2015-09-08 08:05:57 +00004489 CharUnits Alignment =
4490 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004491
Richard Smith00db2f12014-07-29 21:20:12 +00004492 llvm::Constant *C =
4493 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4494
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004495 // Don't share any string literals if strings aren't constant.
Richard Smith00db2f12014-07-29 21:20:12 +00004496 llvm::GlobalVariable **Entry = nullptr;
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004497 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004498 Entry = &ConstantStringMap[C];
4499 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004500 if (Alignment.getQuantity() > GV->getAlignment())
4501 GV->setAlignment(Alignment.getQuantity());
4502 return ConstantAddress(GV, Alignment);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004503 }
4504 }
4505
Daniel Dunbar08b216a2009-03-31 23:42:16 +00004506 // Get the default prefix if a name wasn't specified.
4507 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00004508 GlobalName = ".str";
Chris Lattnerfb300092007-11-28 05:34:05 +00004509 // Create a global variable for this.
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004510 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4511 GlobalName, Alignment);
4512 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004513 *Entry = GV;
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004514
4515 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4516 Alignment);
Chris Lattnerfb300092007-11-28 05:34:05 +00004517}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004518
John McCall7f416cc2015-09-08 08:05:57 +00004519ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00004520 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00004521 assert((E->getStorageDuration() == SD_Static ||
4522 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004523 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00004524
4525 // If we're not materializing a subobject of the temporary, keep the
4526 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00004527 QualType MaterializedType = Init->getType();
4528 if (Init == E->GetTemporaryExpr())
4529 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004530
John McCall7f416cc2015-09-08 08:05:57 +00004531 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4532
David Majnemer2dcef9e2015-08-13 23:50:15 +00004533 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
John McCall7f416cc2015-09-08 08:05:57 +00004534 return ConstantAddress(Slot, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004535
4536 // FIXME: If an externally-visible declaration extends multiple temporaries,
4537 // we need to give each temporary the same name in every translation unit (and
4538 // we also need to make the temporaries externally-visible).
4539 SmallString<256> Name;
4540 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00004541 getCXXABI().getMangleContext().mangleReferenceTemporary(
4542 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00004543
Craig Topper8a13c412014-05-21 05:09:00 +00004544 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004545 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00004546 // We might have a cached constant initializer for this temporary. Note
4547 // that this might have a different value from the value computed by
4548 // evaluating the initializer if the surrounding constant expression
4549 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00004550 Value = getContext().getMaterializedTemporaryValue(E, false);
4551 if (Value && Value->isUninit())
Craig Topper8a13c412014-05-21 05:09:00 +00004552 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004553 }
4554
Richard Smitha509f2f2013-06-14 03:07:01 +00004555 // Try evaluating it now, it might have a constant initializer.
4556 Expr::EvalResult EvalResult;
4557 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4558 !EvalResult.hasSideEffects())
4559 Value = &EvalResult.Val;
4560
Alexander Richardson6d989432017-10-15 18:48:14 +00004561 LangAS AddrSpace =
John McCallde0fe072017-08-15 21:42:52 +00004562 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4563
4564 Optional<ConstantEmitter> emitter;
Craig Topper8a13c412014-05-21 05:09:00 +00004565 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00004566 bool Constant = false;
4567 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00004568 if (Value) {
4569 // The temporary has a constant initializer, use it.
John McCallde0fe072017-08-15 21:42:52 +00004570 emitter.emplace(*this);
4571 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4572 MaterializedType);
Richard Smitha509f2f2013-06-14 03:07:01 +00004573 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4574 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004575 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00004576 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00004577 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00004578 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00004579 }
4580
4581 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00004582 llvm::GlobalValue::LinkageTypes Linkage =
4583 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004584 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4585 const VarDecl *InitVD;
4586 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4587 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4588 // Temporaries defined inside a class get linkonce_odr linkage because the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004589 // class can be defined in multiple translation units.
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004590 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4591 } else {
4592 // There is no need for this temporary to have external linkage if the
4593 // VarDecl has external linkage.
4594 Linkage = llvm::GlobalVariable::InternalLinkage;
4595 }
4596 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00004597 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004598 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00004599 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
Yaxun Liucbf647c2017-07-08 13:24:52 +00004600 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
John McCallde0fe072017-08-15 21:42:52 +00004601 if (emitter) emitter->finalize(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +00004602 setGVProperties(GV, VD);
John McCall7f416cc2015-09-08 08:05:57 +00004603 GV->setAlignment(Align.getQuantity());
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004604 if (supportsCOMDAT() && GV->isWeakForLinker())
4605 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smithe6c01442013-06-05 00:46:14 +00004606 if (VD->getTLSKind())
4607 setTLSMode(GV, *VD);
Yaxun Liucbf647c2017-07-08 13:24:52 +00004608 llvm::Constant *CV = GV;
4609 if (AddrSpace != LangAS::Default)
4610 CV = getTargetCodeGenInfo().performAddrSpaceCast(
4611 *this, GV, AddrSpace, LangAS::Default,
4612 Type->getPointerTo(
4613 getContext().getTargetAddressSpace(LangAS::Default)));
4614 MaterializedGlobalTemporaryMap[E] = CV;
4615 return ConstantAddress(CV, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004616}
4617
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004618/// EmitObjCPropertyImplementations - Emit information for synthesized
4619/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00004620void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004621 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004622 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004623 // Dynamic is just for type-checking.
4624 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4625 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4626
4627 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00004628 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004629 // we want, that just indicates if the decl came from a
4630 // property. What we want to know is if the method is defined in
4631 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004632 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004633 CodeGenFunction(*this).GenerateObjCGetter(
4634 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004635 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004636 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004637 CodeGenFunction(*this).GenerateObjCSetter(
4638 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004639 }
4640 }
4641}
4642
John McCall6a4fa522011-03-22 07:05:39 +00004643static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004644 const ObjCInterfaceDecl *iface = impl->getClassInterface();
4645 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00004646 ivar; ivar = ivar->getNextIvar())
4647 if (ivar->getType().isDestructedType())
4648 return true;
4649
4650 return false;
4651}
4652
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004653static bool AllTrivialInitializers(CodeGenModule &CGM,
4654 ObjCImplementationDecl *D) {
4655 CodeGenFunction CGF(CGM);
4656 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4657 E = D->init_end(); B != E; ++B) {
4658 CXXCtorInitializer *CtorInitExp = *B;
4659 Expr *Init = CtorInitExp->getInit();
4660 if (!CGF.isTrivialInitializer(Init))
4661 return false;
4662 }
4663 return true;
4664}
4665
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004666/// EmitObjCIvarInitializations - Emit information for ivar initialization
4667/// for an implementation.
4668void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00004669 // We might need a .cxx_destruct even if we don't have any ivar initializers.
4670 if (needsDestructMethod(D)) {
4671 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4672 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4673 ObjCMethodDecl *DTORMethod =
4674 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004675 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004676 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004677 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004678 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00004679 D->addInstanceMethod(DTORMethod);
4680 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00004681 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00004682 }
4683
4684 // If the implementation doesn't have any ivar initializers, we don't need
4685 // a .cxx_construct.
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004686 if (D->getNumIvarInitializers() == 0 ||
4687 AllTrivialInitializers(*this, D))
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004688 return;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004689
John McCall6a4fa522011-03-22 07:05:39 +00004690 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4691 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004692 // The constructor returns 'self'.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004693 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004694 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004695 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004696 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00004697 getContext().getObjCIdType(),
4698 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004699 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004700 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004701 /*isImplicitlyDeclared=*/true,
4702 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004703 ObjCMethodDecl::Required);
4704 D->addInstanceMethod(CTORMethod);
4705 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00004706 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004707}
4708
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004709// EmitLinkageSpec - Emit all declarations in a linkage spec.
4710void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00004711 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4712 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004713 ErrorUnsupported(LSD, "linkage spec");
4714 return;
4715 }
4716
Richard Smith8df390f2016-09-08 23:14:54 +00004717 EmitDeclContext(LSD);
4718}
4719
4720void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4721 for (auto *I : DC->decls()) {
4722 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4723 // are themselves considered "top-level", so EmitTopLevelDecl on an
4724 // ObjCImplDecl does not recursively visit them. We need to do that in
4725 // case they're nested inside another construct (LinkageSpecDecl /
4726 // ExportDecl) that does stop them from being considered "top-level".
Aaron Ballman629afae2014-03-07 19:56:05 +00004727 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004728 for (auto *M : OID->methods())
4729 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004730 }
Richard Smith8df390f2016-09-08 23:14:54 +00004731
Aaron Ballman629afae2014-03-07 19:56:05 +00004732 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004733 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004734}
4735
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004736/// EmitTopLevelDecl - Emit code for a single top level declaration.
4737void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00004738 // Ignore dependent declarations.
Richard Smith32b615c2018-02-01 00:28:36 +00004739 if (D->isTemplated())
Douglas Gregor70d83e22009-06-29 17:30:29 +00004740 return;
Mike Stump11289f42009-09-09 15:08:12 +00004741
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004742 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00004743 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00004744 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004745 case Decl::Function:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004746 EmitGlobal(cast<FunctionDecl>(D));
Alex Lorenzee024992014-08-04 18:41:51 +00004747 // Always provide some coverage mapping
4748 // even for the functions that aren't emitted.
4749 AddDeferredUnusedCoverageMapping(D);
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004750 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004751
Richard Smithada08882017-04-19 21:15:45 +00004752 case Decl::CXXDeductionGuide:
4753 // Function-like, but does not result in code emission.
4754 break;
4755
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004756 case Decl::Var:
Richard Smithbdb84f32016-07-22 23:36:59 +00004757 case Decl::Decomposition:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004758 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004759 EmitGlobal(cast<VarDecl>(D));
Richard Smithda383632016-08-15 01:33:41 +00004760 if (auto *DD = dyn_cast<DecompositionDecl>(D))
4761 for (auto *B : DD->bindings())
4762 if (auto *HD = B->getHoldingVar())
4763 EmitGlobal(HD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004764 break;
4765
John McCall32f44bd2011-04-12 01:01:22 +00004766 // Indirect fields from global anonymous structs and unions can be
4767 // ignored; only the actual variable requires IR gen support.
4768 case Decl::IndirectField:
4769 break;
4770
Anders Carlssonf7475242009-04-15 15:55:24 +00004771 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004772 case Decl::Namespace:
Richard Smith8df390f2016-09-08 23:14:54 +00004773 EmitDeclContext(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004774 break;
Richard Smithe1246122017-11-03 01:26:01 +00004775 case Decl::ClassTemplateSpecialization: {
4776 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4777 if (DebugInfo &&
4778 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4779 Spec->hasDefinition())
4780 DebugInfo->completeTemplateDefinition(*Spec);
4781 } LLVM_FALLTHROUGH;
Richard Smith62f19e72016-06-25 00:15:56 +00004782 case Decl::CXXRecord:
David Blaikie1ac9c982017-04-11 21:13:37 +00004783 if (DebugInfo) {
4784 if (auto *ES = D->getASTContext().getExternalSource())
4785 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4786 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4787 }
Richard Smith62f19e72016-06-25 00:15:56 +00004788 // Emit any static data members, they may be definitions.
4789 for (auto *I : cast<CXXRecordDecl>(D)->decls())
4790 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4791 EmitTopLevelDecl(I);
4792 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00004793 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00004794 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004795 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004796 case Decl::VarTemplate:
4797 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004798 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00004799 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00004800 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00004801 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00004802 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00004803 case Decl::Using: // using X; [C++]
4804 if (CGDebugInfo *DI = getModuleDebugInfo())
4805 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4806 return;
David Blaikief121b932013-05-20 22:50:41 +00004807 case Decl::NamespaceAlias:
4808 if (CGDebugInfo *DI = getModuleDebugInfo())
4809 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4810 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00004811 case Decl::UsingDirective: // using namespace X; [C++]
4812 if (CGDebugInfo *DI = getModuleDebugInfo())
4813 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4814 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00004815 case Decl::CXXConstructor:
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00004816 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00004817 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004818 case Decl::CXXDestructor:
Reid Klecknere7de47e2013-07-22 13:51:44 +00004819 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004820 break;
Anders Carlsson87835432009-06-11 21:22:55 +00004821
4822 case Decl::StaticAssert:
4823 // Nothing to do.
4824 break;
4825
Anders Carlssonf7475242009-04-15 15:55:24 +00004826 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00004827
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004828 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00004829 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00004830 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00004831 break;
4832
Douglas Gregorf6102672012-01-01 21:23:57 +00004833 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004834 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00004835 if (Proto->isThisDeclarationADefinition())
4836 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004837 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00004838 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004839
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004840 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004841 // Categories have properties but don't support synthesize so we
4842 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00004843 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004844 break;
4845
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004846 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004847 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004848 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004849 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00004850 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00004851 // Emit global variable debug information.
4852 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00004853 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00004854 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4855 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004856 break;
Mike Stump11289f42009-09-09 15:08:12 +00004857 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004858 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004859 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004860 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004861 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004862 CodeGenFunction(*this).GenerateObjCMethod(OMD);
4863 break;
4864 }
Mike Stump11289f42009-09-09 15:08:12 +00004865 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00004866 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004867 break;
4868
Nico Weber66220292016-03-02 17:28:48 +00004869 case Decl::PragmaComment: {
4870 const auto *PCD = cast<PragmaCommentDecl>(D);
4871 switch (PCD->getCommentKind()) {
4872 case PCK_Unknown:
4873 llvm_unreachable("unexpected pragma comment kind");
4874 case PCK_Linker:
4875 AppendLinkerOptions(PCD->getArg());
4876 break;
4877 case PCK_Lib:
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00004878 if (getTarget().getTriple().isOSBinFormatELF() &&
4879 !getTarget().getTriple().isPS4())
4880 AddELFLibDirective(PCD->getArg());
4881 else
4882 AddDependentLib(PCD->getArg());
Nico Weber66220292016-03-02 17:28:48 +00004883 break;
4884 case PCK_Compiler:
4885 case PCK_ExeStr:
4886 case PCK_User:
4887 break; // We ignore all of these.
4888 }
4889 break;
4890 }
4891
Nico Webercbbaeb12016-03-02 19:28:54 +00004892 case Decl::PragmaDetectMismatch: {
4893 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4894 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4895 break;
4896 }
4897
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004898 case Decl::LinkageSpec:
4899 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004900 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004901
4902 case Decl::FileScopeAsm: {
Artem Belevich0488d1e2015-04-27 18:52:00 +00004903 // File-scope asm is ignored during device-side CUDA compilation.
4904 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4905 break;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004906 // File-scope asm is ignored during device-side OpenMP compilation.
4907 if (LangOpts.OpenMPIsDevice)
4908 break;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004909 auto *AD = cast<FileScopeAsmDecl>(D);
Joerg Sonnenbergerdfd511e2015-03-13 00:54:30 +00004910 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004911 break;
4912 }
Mike Stump11289f42009-09-09 15:08:12 +00004913
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004914 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004915 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004916
Richard Smithdc1f0422016-07-20 19:10:16 +00004917 // If we've already imported this module, we're done.
4918 if (!ImportedModules.insert(Import->getImportedModule()))
Richard Smithc52efa72015-08-19 02:30:28 +00004919 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004920
Richard Smithdc1f0422016-07-20 19:10:16 +00004921 // Emit debug information for direct imports.
4922 if (!Import->getImportedOwningModule()) {
4923 if (CGDebugInfo *DI = getModuleDebugInfo())
4924 DI->EmitImportDecl(*Import);
4925 }
4926
Manman Ren3b5dbf22016-10-14 18:55:44 +00004927 // Find all of the submodules and emit the module initializers.
4928 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4929 SmallVector<clang::Module *, 16> Stack;
4930 Visited.insert(Import->getImportedModule());
4931 Stack.push_back(Import->getImportedModule());
4932
4933 while (!Stack.empty()) {
4934 clang::Module *Mod = Stack.pop_back_val();
4935 if (!EmittedModuleInitializers.insert(Mod).second)
4936 continue;
4937
4938 for (auto *D : Context.getModuleInitializers(Mod))
4939 EmitTopLevelDecl(D);
4940
4941 // Visit the submodules of this module.
4942 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4943 SubEnd = Mod->submodule_end();
4944 Sub != SubEnd; ++Sub) {
4945 // Skip explicit children; they need to be explicitly imported to emit
4946 // the initializers.
4947 if ((*Sub)->IsExplicit)
4948 continue;
4949
4950 if (Visited.insert(*Sub).second)
4951 Stack.push_back(*Sub);
4952 }
4953 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004954 break;
David Blaikie0e716b42014-03-03 23:48:23 +00004955 }
4956
Richard Smith8df390f2016-09-08 23:14:54 +00004957 case Decl::Export:
4958 EmitDeclContext(cast<ExportDecl>(D));
4959 break;
4960
Alexey Bataev97720002014-11-11 04:05:39 +00004961 case Decl::OMPThreadPrivate:
4962 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4963 break;
4964
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004965 case Decl::OMPDeclareReduction:
4966 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4967 break;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004968
Kelvin Li1408f912018-09-26 04:28:39 +00004969 case Decl::OMPRequires:
4970 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
4971 break;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004972
Mike Stump11289f42009-09-09 15:08:12 +00004973 default:
Mike Stump18bb9282009-05-16 07:57:57 +00004974 // Make sure we handled everything we should, every other kind is a
4975 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4976 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004977 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Richard Smitha634ff22014-12-01 18:59:10 +00004978 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004979 }
4980}
John McCall09ae0322010-07-06 23:57:41 +00004981
Alex Lorenzee024992014-08-04 18:41:51 +00004982void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4983 // Do we need to generate coverage mapping?
4984 if (!CodeGenOpts.CoverageMapping)
4985 return;
4986 switch (D->getKind()) {
4987 case Decl::CXXConversion:
4988 case Decl::CXXMethod:
4989 case Decl::Function:
4990 case Decl::ObjCMethod:
4991 case Decl::CXXConstructor:
4992 case Decl::CXXDestructor: {
Justin Bogner203f0922015-07-28 00:41:51 +00004993 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
Alex Lorenzee024992014-08-04 18:41:51 +00004994 return;
Vedant Kumar0acf3432017-09-22 18:23:04 +00004995 SourceManager &SM = getContext().getSourceManager();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004996 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
Vedant Kumar0acf3432017-09-22 18:23:04 +00004997 return;
Alex Lorenzee024992014-08-04 18:41:51 +00004998 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4999 if (I == DeferredEmptyCoverageMappingDecls.end())
5000 DeferredEmptyCoverageMappingDecls[D] = true;
5001 break;
5002 }
5003 default:
5004 break;
5005 };
5006}
5007
5008void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5009 // Do we need to generate coverage mapping?
5010 if (!CodeGenOpts.CoverageMapping)
5011 return;
5012 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5013 if (Fn->isTemplateInstantiation())
5014 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5015 }
5016 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5017 if (I == DeferredEmptyCoverageMappingDecls.end())
5018 DeferredEmptyCoverageMappingDecls[D] = false;
5019 else
5020 I->second = false;
5021}
5022
5023void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
Eli Friedman8516b7f2017-12-19 01:54:09 +00005024 // We call takeVector() here to avoid use-after-free.
5025 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5026 // we deserialize function bodies to emit coverage info for them, and that
5027 // deserializes more declarations. How should we handle that case?
5028 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
Eli Friedmandbcfade2017-12-13 00:14:17 +00005029 if (!Entry.second)
Alex Lorenzee024992014-08-04 18:41:51 +00005030 continue;
Eli Friedmandbcfade2017-12-13 00:14:17 +00005031 const Decl *D = Entry.first;
Alex Lorenzee024992014-08-04 18:41:51 +00005032 switch (D->getKind()) {
5033 case Decl::CXXConversion:
5034 case Decl::CXXMethod:
5035 case Decl::Function:
5036 case Decl::ObjCMethod: {
5037 CodeGenPGO PGO(*this);
5038 GlobalDecl GD(cast<FunctionDecl>(D));
5039 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5040 getFunctionLinkage(GD));
5041 break;
5042 }
5043 case Decl::CXXConstructor: {
5044 CodeGenPGO PGO(*this);
5045 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5046 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5047 getFunctionLinkage(GD));
5048 break;
5049 }
5050 case Decl::CXXDestructor: {
5051 CodeGenPGO PGO(*this);
5052 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5053 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5054 getFunctionLinkage(GD));
5055 break;
5056 }
5057 default:
5058 break;
5059 };
5060 }
5061}
5062
John McCall09ae0322010-07-06 23:57:41 +00005063/// Turns the given pointer into a constant.
5064static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5065 const void *Ptr) {
5066 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00005067 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00005068 return llvm::ConstantInt::get(i64, PtrInt);
5069}
5070
5071static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5072 llvm::NamedMDNode *&GlobalMetadata,
5073 GlobalDecl D,
5074 llvm::GlobalValue *Addr) {
5075 if (!GlobalMetadata)
5076 GlobalMetadata =
5077 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5078
5079 // TODO: should we report variant information for ctors/dtors?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005080 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5081 llvm::ConstantAsMetadata::get(GetPointerConstant(
5082 CGM.getLLVMContext(), D.getDecl()))};
Jay Foadea324f12011-04-21 19:59:12 +00005083 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00005084}
5085
Richard Smithdf931ce2013-04-06 05:00:46 +00005086/// For each function which is declared within an extern "C" region and marked
5087/// as 'used', but has internal linkage, create an alias from the unmangled
5088/// name to the mangled name if possible. People expect to be able to refer
5089/// to such functions with an unmangled name from inline assembly within the
5090/// same translation unit.
5091void CodeGenModule::EmitStaticExternCAliases() {
Yaxun Liub0eee292018-03-29 14:50:00 +00005092 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
Justin Lebarcd2f6bb2016-01-25 22:36:37 +00005093 return;
Yaron Kerenb54db522015-06-11 12:33:25 +00005094 for (auto &I : StaticExternCValues) {
5095 IdentifierInfo *Name = I.first;
5096 llvm::GlobalValue *Val = I.second;
Richard Smith85465e62013-04-06 07:07:44 +00005097 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola27c60b52014-06-03 02:42:01 +00005098 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith85465e62013-04-06 07:07:44 +00005099 }
Richard Smithdf931ce2013-04-06 05:00:46 +00005100}
5101
Alp Tokerfb8d02b2014-06-05 22:10:59 +00005102bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5103 GlobalDecl &Result) const {
5104 auto Res = Manglings.find(MangledName);
5105 if (Res == Manglings.end())
5106 return false;
5107 Result = Res->getValue();
5108 return true;
5109}
5110
John McCall09ae0322010-07-06 23:57:41 +00005111/// Emits metadata nodes associating all the global values in the
5112/// current module with the Decls they came from. This is useful for
5113/// projects using IR gen as a subroutine.
5114///
5115/// Since there's currently no way to associate an MDNode directly
5116/// with an llvm::GlobalValue, we create a global named metadata
5117/// with the name 'clang.global.decl.ptrs'.
5118void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00005119 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00005120
Robert Lytton5b88f78f2014-07-03 09:30:29 +00005121 for (auto &I : MangledDeclNames) {
5122 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
Keno Fischer0e2d4222015-11-05 23:18:44 +00005123 // Some mangled names don't necessarily have an associated GlobalValue
5124 // in this module, e.g. if we mangled it for DebugInfo.
5125 if (Addr)
5126 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall09ae0322010-07-06 23:57:41 +00005127 }
5128}
5129
5130/// Emits metadata nodes for all the local variables in the current
5131/// function.
5132void CodeGenFunction::EmitDeclMetadata() {
5133 if (LocalDeclMap.empty()) return;
5134
5135 llvm::LLVMContext &Context = getLLVMContext();
5136
5137 // Find the unique metadata ID for this name.
5138 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5139
Craig Topper8a13c412014-05-21 05:09:00 +00005140 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00005141
Robert Lytton5b88f78f2014-07-03 09:30:29 +00005142 for (auto &I : LocalDeclMap) {
5143 const Decl *D = I.first;
John McCall7f416cc2015-09-08 08:05:57 +00005144 llvm::Value *Addr = I.second.getPointer();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005145 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00005146 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005147 Alloca->setMetadata(
5148 DeclPtrKind, llvm::MDNode::get(
5149 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005150 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00005151 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5152 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5153 }
5154 }
5155}
Daniel Dunbar900546d2010-07-16 00:00:15 +00005156
Rafael Espindola3bfa4682013-10-16 19:28:50 +00005157void CodeGenModule::EmitVersionIdentMetadata() {
5158 llvm::NamedMDNode *IdentMetadata =
5159 TheModule.getOrInsertNamedMetadata("llvm.ident");
5160 std::string Version = getClangFullVersion();
5161 llvm::LLVMContext &Ctx = TheModule.getContext();
5162
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005163 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola3bfa4682013-10-16 19:28:50 +00005164 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5165}
5166
Robert Lytton57765d52014-07-03 09:30:33 +00005167void CodeGenModule::EmitTargetMetadata() {
Richard Smith1ba0a072014-08-01 20:39:36 +00005168 // Warning, new MangledDeclNames may be appended within this loop.
5169 // We rely on MapVector insertions adding new elements to the end
5170 // of the container.
5171 // FIXME: Move this loop into the one target that needs it, and only
5172 // loop over those declarations for which we couldn't emit the target
5173 // metadata when we emitted the declaration.
5174 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
Richard Smith570706d2014-08-01 22:17:28 +00005175 auto Val = *(MangledDeclNames.begin() + I);
Richard Smith1ba0a072014-08-01 20:39:36 +00005176 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
5177 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Robert Lytton57765d52014-07-03 09:30:33 +00005178 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
5179 }
5180}
5181
Nick Lewycky85c011d2011-05-05 00:08:20 +00005182void CodeGenModule::EmitCoverageFile() {
Nick Lewycky97e49ac2016-08-31 23:04:32 +00005183 if (getCodeGenOpts().CoverageDataFile.empty() &&
5184 getCodeGenOpts().CoverageNotesFile.empty())
5185 return;
5186
5187 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5188 if (!CUNode)
5189 return;
5190
5191 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5192 llvm::LLVMContext &Ctx = TheModule.getContext();
5193 auto *CoverageDataFile =
5194 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5195 auto *CoverageNotesFile =
5196 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5197 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5198 llvm::MDNode *CU = CUNode->getOperand(i);
5199 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5200 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky480cb992011-05-04 20:46:58 +00005201 }
5202}
Nico Webercf4ff5862012-10-11 10:13:44 +00005203
Nico Weber17d3a2c2014-09-08 16:26:36 +00005204llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Webercf4ff5862012-10-11 10:13:44 +00005205 // Sema has checked that all uuid strings are of the form
5206 // "12345678-1234-1234-1234-1234567890ab".
5207 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00005208 for (unsigned i = 0; i < 36; ++i) {
5209 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5210 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00005211 }
Nico Webercf4ff5862012-10-11 10:13:44 +00005212
Nico Weberdfa274e2014-09-08 16:11:15 +00005213 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemerbbecd092013-08-15 19:59:14 +00005214 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00005215
David Majnemerbbecd092013-08-15 19:59:14 +00005216 llvm::Constant *Field3[8];
5217 for (unsigned Idx = 0; Idx < 8; ++Idx)
5218 Field3[Idx] = llvm::ConstantInt::get(
5219 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5220
5221 llvm::Constant *Fields[4] = {
5222 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
5223 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
5224 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5225 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5226 };
5227
5228 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00005229}
David Majnemere2cb8d12014-07-07 06:20:47 +00005230
5231llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5232 bool ForEH) {
5233 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5234 // FIXME: should we even be calling this method if RTTI is disabled
5235 // and it's not for EH?
Yaxun Liu6328f9a2018-06-05 15:11:02 +00005236 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
David Majnemere2cb8d12014-07-07 06:20:47 +00005237 return llvm::Constant::getNullValue(Int8PtrTy);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00005238
David Majnemere2cb8d12014-07-07 06:20:47 +00005239 if (ForEH && Ty->isObjCObjectPointerType() &&
5240 LangOpts.ObjCRuntime.isGNUFamily())
5241 return ObjCRuntime->GetEHType(Ty);
5242
David Majnemer443250f2015-03-17 20:35:00 +00005243 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
David Majnemere2cb8d12014-07-07 06:20:47 +00005244}
5245
Alexey Bataev97720002014-11-11 04:05:39 +00005246void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005247 // Do not emit threadprivates in simd-only mode.
5248 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5249 return;
Alexey Bataev97720002014-11-11 04:05:39 +00005250 for (auto RefExpr : D->varlists()) {
5251 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5252 bool PerformInit =
5253 VD->getAnyInitializer() &&
5254 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5255 /*ForRef=*/false);
John McCall7f416cc2015-09-08 08:05:57 +00005256
5257 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
Alexey Bataev3eff5f42015-02-25 08:32:46 +00005258 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005259 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
Alexey Bataev97720002014-11-11 04:05:39 +00005260 CXXGlobalInits.push_back(InitFunction);
5261 }
5262}
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005263
Peter Collingbournee44acad2018-06-26 02:15:47 +00005264llvm::Metadata *
5265CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5266 StringRef Suffix) {
5267 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00005268 if (InternalId)
5269 return InternalId;
5270
5271 if (isExternallyVisible(T->getLinkage())) {
5272 std::string OutName;
5273 llvm::raw_string_ostream Out(OutName);
5274 getCXXABI().getMangleContext().mangleTypeName(T, Out);
Peter Collingbournee44acad2018-06-26 02:15:47 +00005275 Out << Suffix;
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00005276
5277 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5278 } else {
5279 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5280 llvm::ArrayRef<llvm::Metadata *>());
5281 }
5282
5283 return InternalId;
5284}
5285
Peter Collingbournee44acad2018-06-26 02:15:47 +00005286llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5287 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5288}
5289
5290llvm::Metadata *
5291CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5292 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5293}
5294
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005295// Generalize pointer types to a void pointer with the qualifiers of the
5296// originally pointed-to type, e.g. 'const char *' and 'char * const *'
5297// generalize to 'const void *' while 'char *' and 'const char **' generalize to
5298// 'void *'.
5299static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5300 if (!Ty->isPointerType())
5301 return Ty;
5302
5303 return Ctx.getPointerType(
5304 QualType(Ctx.VoidTy).withCVRQualifiers(
5305 Ty->getPointeeType().getCVRQualifiers()));
5306}
5307
5308// Apply type generalization to a FunctionType's return and argument types
5309static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5310 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5311 SmallVector<QualType, 8> GeneralizedParams;
5312 for (auto &Param : FnType->param_types())
5313 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5314
5315 return Ctx.getFunctionType(
5316 GeneralizeType(Ctx, FnType->getReturnType()),
5317 GeneralizedParams, FnType->getExtProtoInfo());
5318 }
5319
5320 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5321 return Ctx.getFunctionNoProtoType(
5322 GeneralizeType(Ctx, FnType->getReturnType()));
5323
5324 llvm_unreachable("Encountered unknown FunctionType");
5325}
5326
5327llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
Peter Collingbournee44acad2018-06-26 02:15:47 +00005328 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5329 GeneralizedMetadataIdMap, ".generalized");
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005330}
5331
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005332/// Returns whether this module needs the "all-vtables" type identifier.
5333bool CodeGenModule::NeedAllVtablesTypeId() const {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005334 // Returns true if at least one of vtable-based CFI checkers is enabled and
5335 // is not in the trapping mode.
5336 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5337 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5338 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5339 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5340 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5341 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5342 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5343 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5344}
5345
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005346void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5347 CharUnits Offset,
5348 const CXXRecordDecl *RD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005349 llvm::Metadata *MD =
5350 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005351 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005352
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005353 if (CodeGenOpts.SanitizeCfiCrossDso)
5354 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5355 VTable->addTypeMetadata(Offset.getQuantity(),
5356 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005357
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005358 if (NeedAllVtablesTypeId()) {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005359 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005360 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005361 }
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005362}
Eric Christopher2b90a642015-11-11 23:05:08 +00005363
Gabor Buella1a83d062018-06-07 08:48:36 +00005364TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5365 assert(TD != nullptr);
5366 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5367
5368 ParsedAttr.Features.erase(
5369 llvm::remove_if(ParsedAttr.Features,
5370 [&](const std::string &Feat) {
5371 return !Target.isValidFeatureName(
5372 StringRef{Feat}.substr(1));
5373 }),
5374 ParsedAttr.Features.end());
5375 return ParsedAttr;
5376}
5377
5378
Eric Christopher2b90a642015-11-11 23:05:08 +00005379// Fills in the supplied string map with the set of target features for the
5380// passed in function.
5381void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
5382 const FunctionDecl *FD) {
5383 StringRef TargetCPU = Target.getTargetOpts().CPU;
5384 if (const auto *TD = FD->getAttr<TargetAttr>()) {
Gabor Buella1a83d062018-06-07 08:48:36 +00005385 TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
Erich Keanecf8807c2017-10-27 18:32:23 +00005386
Eric Christopher2b90a642015-11-11 23:05:08 +00005387 // Make a copy of the features as passed on the command line into the
5388 // beginning of the additional features from the function to override.
Erich Keaneb0d44232017-07-18 20:41:02 +00005389 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
Eric Christopher2b90a642015-11-11 23:05:08 +00005390 Target.getTargetOpts().FeaturesAsWritten.begin(),
5391 Target.getTargetOpts().FeaturesAsWritten.end());
5392
Erich Keanecf8807c2017-10-27 18:32:23 +00005393 if (ParsedAttr.Architecture != "" &&
5394 Target.isValidCPUName(ParsedAttr.Architecture))
5395 TargetCPU = ParsedAttr.Architecture;
Eric Christopher2b90a642015-11-11 23:05:08 +00005396
5397 // Now populate the feature map, first with the TargetCPU which is either
5398 // the default or a new one from the target attribute string. Then we'll use
5399 // the passed in features (FeaturesAsWritten) along with the new ones from
5400 // the attribute.
Erich Keaneb0d44232017-07-18 20:41:02 +00005401 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5402 ParsedAttr.Features);
Erich Keane3efe0022018-07-20 14:13:28 +00005403 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
5404 llvm::SmallVector<StringRef, 32> FeaturesTmp;
5405 Target.getCPUSpecificCPUDispatchFeatures(SD->getCurCPUName()->getName(),
5406 FeaturesTmp);
5407 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5408 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
Eric Christopher2b90a642015-11-11 23:05:08 +00005409 } else {
5410 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5411 Target.getTargetOpts().Features);
5412 }
5413}
Peter Collingbournedc134532016-01-16 00:31:22 +00005414
5415llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5416 if (!SanStats)
5417 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5418
5419 return *SanStats;
5420}
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005421llvm::Value *
5422CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5423 CodeGenFunction &CGF) {
John McCallde0fe072017-08-15 21:42:52 +00005424 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00005425 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005426 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5427 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5428 "__translate_sampler_initializer"),
5429 {C});
5430}