blob: 89185c89518a39f4536ada8fe0e957f288ae7f19 [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"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000026#include "CodeGenTBAA.h"
John McCallde0fe072017-08-15 21:42:52 +000027#include "ConstantEmitter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000028#include "CoverageMappingGen.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000029#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000030#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000031#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000032#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000034#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000035#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000036#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000037#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000038#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000039#include "clang/Basic/CharInfo.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000040#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000041#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000042#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000043#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000044#include "clang/Basic/Version.h"
John McCall5ad74072017-03-02 20:04:19 +000045#include "clang/CodeGen/ConstantInitBuilder.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000046#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindola208b5c02013-10-22 19:26:13 +000047#include "clang/Sema/SemaDiagnostic.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"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000057#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000058#include "llvm/Support/ErrorHandling.h"
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +000059#include "llvm/Support/MD5.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000060
Chris Lattnerbed31442007-05-28 01:07:47 +000061using namespace clang;
62using namespace CodeGen;
63
Vedant Kumar0acf3432017-09-22 18:23:04 +000064static llvm::cl::opt<bool> LimitedCoverage(
65 "limited-coverage-experimental", llvm::cl::ZeroOrMore,
66 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
67 llvm::cl::init(false));
68
Julien Lerouge5a6b6982011-09-09 22:41:49 +000069static const char AnnotationSection[] = "llvm.metadata";
70
Alp Toker82862252013-12-28 21:58:40 +000071static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000072 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000073 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000074 case TargetCXXABI::GenericARM:
75 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000076 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +000077 case TargetCXXABI::WatchOS:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000078 case TargetCXXABI::GenericMIPS:
John McCall57625922013-01-25 23:36:14 +000079 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +000080 case TargetCXXABI::WebAssembly:
Alp Toker82862252013-12-28 21:58:40 +000081 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000082 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000083 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000084 }
85
86 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000087}
88
Adrian Prantle74f5252015-06-30 02:26:03 +000089CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
90 const PreprocessorOptions &PPO,
91 const CodeGenOptions &CGO, llvm::Module &M,
Alex Lorenzee024992014-08-04 18:41:51 +000092 DiagnosticsEngine &diags,
93 CoverageSourceInfo *CoverageInfo)
Adrian Prantle74f5252015-06-30 02:26:03 +000094 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
95 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
Mehdi Aminica3cf9e2015-07-24 16:04:29 +000096 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
Reid Kleckner9305fd12016-04-13 23:37:17 +000097 VMContext(M.getContext()), Types(*this), VTables(*this),
Peter Collingbourne3afb2662016-04-28 17:09:37 +000098 SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietzf54319c2013-01-18 11:30:38 +000099
Chris Lattnerece04092012-02-07 00:39:47 +0000100 // Initialize the type cache.
101 llvm::LLVMContext &LLVMContext = M.getContext();
102 VoidTy = llvm::Type::getVoidTy(LLVMContext);
103 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
104 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
105 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
106 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
107 FloatTy = llvm::Type::getFloatTy(LLVMContext);
108 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
109 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
110 PointerAlignInBytes =
John McCall7f416cc2015-09-08 08:05:57 +0000111 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
Yaxun Liu26f75662016-08-19 05:17:25 +0000112 SizeSizeInBytes =
113 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +0000114 IntAlignInBytes =
115 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
Chris Lattnerece04092012-02-07 00:39:47 +0000116 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
Yaxun Liu26f75662016-08-19 05:17:25 +0000117 IntPtrTy = llvm::IntegerType::get(LLVMContext,
118 C.getTargetInfo().getMaxPointerWidth());
Chris Lattnerece04092012-02-07 00:39:47 +0000119 Int8PtrTy = Int8Ty->getPointerTo(0);
120 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000121 AllocaInt8PtrTy = Int8Ty->getPointerTo(
122 M.getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000123 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
Chris Lattnerece04092012-02-07 00:39:47 +0000124
John McCall882987f2013-02-28 19:01:20 +0000125 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
Anton Korobeynikovd90dd792014-12-02 16:04:58 +0000126 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
John McCall882987f2013-02-28 19:01:20 +0000127
David Blaikiebbafb8a2012-03-11 07:00:24 +0000128 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000129 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000130 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000131 createOpenCLRuntime();
Alexey Bataev9959db52014-05-06 10:08:46 +0000132 if (LangOpts.OpenMP)
133 createOpenMPRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000134 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000135 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000136
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000137 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000138 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000139 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
Reid Kleckner9305fd12016-04-13 23:37:17 +0000140 TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
141 getCXXABI().getMangleContext()));
Dan Gohman947c9af2010-10-14 23:06:10 +0000142
Nick Lewycky207bce32011-04-21 23:44:07 +0000143 // If debug info or coverage generation is enabled, create the CGDebugInfo
144 // object.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000145 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
146 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000147 DebugInfo.reset(new CGDebugInfo(*this));
John McCallad7c5c12011-02-08 08:22:06 +0000148
149 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000150
John McCallb04ecb72015-10-21 18:06:43 +0000151 if (C.getLangOpts().ObjC1)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000152 ObjCData.reset(new ObjCEntrypoints());
Justin Bogneref512b92014-01-06 22:27:43 +0000153
Rong Xu9c6f1532016-03-02 20:59:36 +0000154 if (CodeGenOpts.hasProfileClangUse()) {
155 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
156 CodeGenOpts.ProfileInstrumentUsePath);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000157 if (auto E = ReaderOrErr.takeError()) {
Justin Bogner837a6f62014-04-18 21:52:00 +0000158 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
Diego Novillo5aecacb2015-06-25 22:56:00 +0000159 "Could not read profile %0: %1");
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000160 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
161 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
162 << EI.message();
163 });
Nico Weber176efac2015-04-06 04:16:48 +0000164 } else
165 PGOReader = std::move(ReaderOrErr.get());
Justin Bogner837a6f62014-04-18 21:52:00 +0000166 }
Alex Lorenzee024992014-08-04 18:41:51 +0000167
168 // If coverage mapping generation is enabled, create the
169 // CoverageMappingModuleGen object.
170 if (CodeGenOpts.CoverageMapping)
171 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattnera087ff92008-03-01 08:45:05 +0000172}
173
Reid Kleckner9305fd12016-04-13 23:37:17 +0000174CodeGenModule::~CodeGenModule() {}
Ted Kremenek2c674f62008-08-05 18:50:11 +0000175
David Chisnall481e3a82010-01-23 02:40:42 +0000176void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000177 // This is just isGNUFamily(), but we want to force implementors of
178 // new ABIs to decide how best to do this.
179 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000180 case ObjCRuntime::GNUstep:
181 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000182 case ObjCRuntime::ObjFW:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000183 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000184 return;
185
186 case ObjCRuntime::FragileMacOSX:
187 case ObjCRuntime::MacOSX:
188 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000189 case ObjCRuntime::WatchOS:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000190 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000191 return;
192 }
193 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000194}
195
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000196void CodeGenModule::createOpenCLRuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000197 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000198}
199
Alexey Bataev9959db52014-05-06 10:08:46 +0000200void CodeGenModule::createOpenMPRuntime() {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000201 // Select a specialized code generation class based on the target, if any.
202 // If it does not exist use the default implementation.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000203 switch (getTriple().getArch()) {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000204 case llvm::Triple::nvptx:
205 case llvm::Triple::nvptx64:
206 assert(getLangOpts().OpenMPIsDevice &&
207 "OpenMP NVPTX is only prepared to deal with device code.");
Reid Kleckner9305fd12016-04-13 23:37:17 +0000208 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000209 break;
210 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000211 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000212 break;
213 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000214}
215
Peter Collingbournefe883422011-10-06 18:29:37 +0000216void CodeGenModule::createCUDARuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000217 CUDARuntime.reset(CreateNVCUDARuntime(*this));
Peter Collingbournefe883422011-10-06 18:29:37 +0000218}
219
Rafael Espindola1e4df922014-09-16 15:18:21 +0000220void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
221 Replacements[Name] = C;
222}
223
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000224void CodeGenModule::applyReplacements() {
Yaron Kerenb54db522015-06-11 12:33:25 +0000225 for (auto &I : Replacements) {
226 StringRef MangledName = I.first();
227 llvm::Constant *Replacement = I.second;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000228 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
229 if (!Entry)
230 continue;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000231 auto *OldF = cast<llvm::Function>(Entry);
232 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000233 if (!NewF) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000234 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
Rafael Espindola0fcad882014-05-16 22:20:18 +0000235 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Reid Klecknerb78257d2014-02-03 18:54:51 +0000236 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000237 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Reid Klecknerb78257d2014-02-03 18:54:51 +0000238 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
239 CE->getOpcode() == llvm::Instruction::GetElementPtr);
240 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
241 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000242 }
243
244 // Replace old with new, but keep the old order.
245 OldF->replaceAllUsesWith(Replacement);
246 if (NewF) {
247 NewF->removeFromParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000248 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
249 NewF);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000250 }
251 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000252 }
253}
254
Andrey Bokhankocab58582015-08-31 13:20:44 +0000255void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
256 GlobalValReplacements.push_back(std::make_pair(GV, C));
257}
258
259void CodeGenModule::applyGlobalValReplacements() {
260 for (auto &I : GlobalValReplacements) {
261 llvm::GlobalValue *GV = I.first;
262 llvm::Constant *C = I.second;
263
264 GV->replaceAllUsesWith(C);
265 GV->eraseFromParent();
266 }
267}
268
Rafael Espindola27c60b52014-06-03 02:42:01 +0000269// This is only used in aliases that we created and we know they have a
270// linear structure.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000271static const llvm::GlobalObject *getAliasedGlobal(
272 const llvm::GlobalIndirectSymbol &GIS) {
273 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
274 const llvm::Constant *C = &GIS;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000275 for (;;) {
Rafael Espindolae11f40a2014-06-04 19:03:20 +0000276 C = C->stripPointerCasts();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000277 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
278 return GO;
279 // stripPointerCasts will not walk over weak aliases.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000280 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
281 if (!GIS2)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000282 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000283 if (!Visited.insert(GIS2).second)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000284 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000285 C = GIS2->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000286 }
287}
288
Rafael Espindola208b5c02013-10-22 19:26:13 +0000289void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000290 // Check if the constructed aliases are well formed. It is really unfortunate
291 // that we have to do this in CodeGen, but we only construct mangled names
292 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000293 bool Error = false;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000294 DiagnosticsEngine &Diags = getDiags();
Yaron Kerenb54db522015-06-11 12:33:25 +0000295 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000296 const auto *D = cast<ValueDecl>(GD.getDecl());
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000297 SourceLocation Location;
298 bool IsIFunc = D->hasAttr<IFuncAttr>();
299 if (const Attr *A = D->getDefiningAttr())
300 Location = A->getLocation();
301 else
302 llvm_unreachable("Not an alias or ifunc?");
Rafael Espindola208b5c02013-10-22 19:26:13 +0000303 StringRef MangledName = getMangledName(GD);
304 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000305 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000306 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
307 if (!GV) {
308 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000309 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000310 } else if (GV->isDeclaration()) {
Rafael Espindola93c7a652014-03-13 15:47:50 +0000311 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000312 Diags.Report(Location, diag::err_alias_to_undefined)
313 << IsIFunc << IsIFunc;
314 } else if (IsIFunc) {
315 // Check resolver function type.
316 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
317 GV->getType()->getPointerElementType());
318 assert(FTy);
319 if (!FTy->getReturnType()->isPointerTy())
320 Diags.Report(Location, diag::err_ifunc_resolver_return);
321 if (FTy->getNumParams())
322 Diags.Report(Location, diag::err_ifunc_resolver_params);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000323 }
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000324
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000325 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000326 llvm::GlobalValue *AliaseeGV;
327 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
328 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
329 else
330 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
331
Rafael Espindola502f65a2014-05-05 20:21:03 +0000332 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
333 StringRef AliasSection = SA->getName();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000334 if (AliasSection != AliaseeGV->getSection())
Rafael Espindola502f65a2014-05-05 20:21:03 +0000335 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000336 << AliasSection << IsIFunc << IsIFunc;
Rafael Espindola502f65a2014-05-05 20:21:03 +0000337 }
Rafael Espindola27c60b52014-06-03 02:42:01 +0000338
339 // We have to handle alias to weak aliases in here. LLVM itself disallows
340 // this since the object semantics would not match the IL one. For
341 // compatibility with gcc we implement it by just pointing the alias
342 // to its aliasee's aliasee. We also warn, since the user is probably
343 // expecting the link to be weak.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000344 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
Sanjoy Dasf60a0d72016-04-08 01:31:02 +0000345 if (GA->isInterposable()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000346 Diags.Report(Location, diag::warn_alias_to_weak_alias)
347 << GV->getName() << GA->getName() << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000348 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000349 GA->getIndirectSymbol(), Alias->getType());
350 Alias->setIndirectSymbol(Aliasee);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000351 }
352 }
Rafael Espindola208b5c02013-10-22 19:26:13 +0000353 }
354 if (!Error)
355 return;
356
Yaron Kerenb54db522015-06-11 12:33:25 +0000357 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola208b5c02013-10-22 19:26:13 +0000358 StringRef MangledName = getMangledName(GD);
359 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000360 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000361 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
362 Alias->eraseFromParent();
363 }
364}
365
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000366void CodeGenModule::clear() {
367 DeferredDeclsToEmit.clear();
Alexey Bataev91797552015-03-18 04:13:55 +0000368 if (OpenMPRuntime)
369 OpenMPRuntime->clear();
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000370}
371
Justin Bogner40b8ba12014-06-26 01:45:07 +0000372void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
373 StringRef MainFile) {
374 if (!hasDiagnostics())
375 return;
376 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
377 if (MainFile.empty())
378 MainFile = "<stdin>";
379 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
Vedant Kumar96d6ca72017-04-27 17:30:58 +0000380 } else {
381 if (Mismatched > 0)
382 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
383
384 if (Missing > 0)
385 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
386 }
Justin Bogner40b8ba12014-06-26 01:45:07 +0000387}
388
Ted Kremenek2c674f62008-08-05 18:50:11 +0000389void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000390 EmitDeferred();
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000391 EmitVTablesOpportunistically();
Andrey Bokhankocab58582015-08-31 13:20:44 +0000392 applyGlobalValReplacements();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000393 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000394 checkAliases();
Eli Friedman5866fe32010-01-08 00:50:11 +0000395 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000396 EmitCXXGlobalDtorFunc();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000397 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000398 if (ObjCRuntime)
399 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000400 AddGlobalCtor(ObjCInitFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000401 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
402 CUDARuntime) {
403 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
404 AddGlobalCtor(CudaCtorFunction);
405 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
406 AddGlobalDtor(CudaDtorFunction);
407 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000408 if (OpenMPRuntime)
409 if (llvm::Function *OpenMPRegistrationFunction =
George Rokos29d0f002017-05-27 03:03:13 +0000410 OpenMPRuntime->emitRegistrationFunction()) {
411 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
412 OpenMPRegistrationFunction : nullptr;
413 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
414 }
Easwaran Raman695890c2015-12-17 19:14:27 +0000415 if (PGOReader) {
Easwaran Raman81608122016-03-24 21:32:25 +0000416 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
Easwaran Raman695890c2015-12-17 19:14:27 +0000417 if (PGOStats.hasDiagnostics())
418 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
419 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000420 EmitCtorList(GlobalCtors, "llvm.global_ctors");
421 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000422 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000423 EmitStaticExternCAliases();
Alex Lorenzee024992014-08-04 18:41:51 +0000424 EmitDeferredUnusedCoverageMappings();
425 if (CoverageMapping)
426 CoverageMapping->emit();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000427 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000428 CodeGenFunction(*this).EmitCfiCheckFail();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000429 CodeGenFunction(*this).EmitCfiCheckStub();
430 }
Alex Lorenza8fbef42017-03-23 11:14:27 +0000431 emitAtAvailableLinkGuard();
Rafael Espindola060062a2014-03-06 22:15:10 +0000432 emitLLVMUsed();
Peter Collingbournedc134532016-01-16 00:31:22 +0000433 if (SanStats)
434 SanStats->finish();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000435
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000436 if (CodeGenOpts.Autolink &&
437 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000438 EmitModuleLinkOptions();
439 }
Nirav Dave8497ef42017-03-18 00:43:39 +0000440
Nirav Dave741dea02017-03-30 13:41:44 +0000441 // Record mregparm value now so it is visible through rest of codegen.
442 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
443 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
444 CodeGenOpts.NumRegisterParameters);
445
Reid Kleckner124955a2015-08-05 18:51:13 +0000446 if (CodeGenOpts.DwarfVersion) {
Manman Ren9691f7f2013-06-19 01:46:49 +0000447 // We actually want the latest version when there are conflicts.
448 // We can change from Warning to Latest if such mode is supported.
449 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
450 CodeGenOpts.DwarfVersion);
Reid Kleckner124955a2015-08-05 18:51:13 +0000451 }
452 if (CodeGenOpts.EmitCodeView) {
453 // Indicate that we want CodeView in the metadata.
454 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
455 }
Piotr Padlewski9d0ecf22015-09-15 21:46:50 +0000456 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
457 // We don't support LTO with 2 with different StrictVTablePointers
458 // FIXME: we could support it by stripping all the information introduced
459 // by StrictVTablePointers.
460
461 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
462
463 llvm::Metadata *Ops[2] = {
464 llvm::MDString::get(VMContext, "StrictVTablePointers"),
465 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
466 llvm::Type::getInt32Ty(VMContext), 1))};
467
468 getModule().addModuleFlag(llvm::Module::Require,
469 "StrictVTablePointersRequirement",
470 llvm::MDNode::get(VMContext, Ops));
471 }
Manman Ren4b7f23d2013-11-22 19:42:45 +0000472 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000473 // We support a single version in the linked module. The LLVM
474 // parser will drop debug info with a different version number
475 // (and warn about it, too).
476 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000477 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000478
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000479 // We need to record the widths of enums and wchar_t, so that we can generate
Matthias Brauna4519532017-05-20 01:29:55 +0000480 // the correct build attributes in the ARM backend. wchar_size is also used by
481 // TargetLibraryInfo.
Matthias Braunbffc1bb2017-09-26 02:37:23 +0000482 uint64_t WCharWidth =
483 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
Matthias Brauna4519532017-05-20 01:29:55 +0000484 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
485
Justin Bogner9bb7f152014-06-23 20:03:28 +0000486 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000487 if ( Arch == llvm::Triple::arm
488 || Arch == llvm::Triple::armeb
489 || Arch == llvm::Triple::thumb
490 || Arch == llvm::Triple::thumbeb) {
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000491 // The minimum width of an enum in bytes
492 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
493 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
494 }
495
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000496 if (CodeGenOpts.SanitizeCfiCrossDso) {
497 // Indicate that we want cross-DSO control flow integrity checks.
498 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
499 }
500
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000501 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
Justin Lebard3a44f62016-04-05 18:26:20 +0000502 // Indicate whether __nvvm_reflect should be configured to flush denormal
503 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
504 // property.)
505 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
506 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
507 }
508
Alexey Bader364a1162017-06-20 14:30:18 +0000509 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
510 if (LangOpts.OpenCL) {
511 EmitOpenCLMetadata();
512 // Emit SPIR version.
513 if (getTriple().getArch() == llvm::Triple::spir ||
514 getTriple().getArch() == llvm::Triple::spir64) {
515 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
516 // opencl.spir.version named metadata.
517 llvm::Metadata *SPIRVerElts[] = {
518 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
519 Int32Ty, LangOpts.OpenCLVersion / 100)),
520 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
521 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
522 llvm::NamedMDNode *SPIRVerMD =
523 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
524 llvm::LLVMContext &Ctx = TheModule.getContext();
525 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
526 }
527 }
528
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000529 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
Sriraman Tallam70e70e62016-04-28 22:34:00 +0000530 assert(PLevel < 3 && "Invalid PIC Level");
531 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
Rafael Espindolac9d336e2016-06-23 15:07:32 +0000532 if (Context.getLangOpts().PIE)
533 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000534 }
535
John McCall0bdb1fd2010-09-16 06:16:50 +0000536 SimplifyPersonality();
537
John McCall09ae0322010-07-06 23:57:41 +0000538 if (getCodeGenOpts().EmitDeclMetadata)
539 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000540
541 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000542 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000543
544 if (DebugInfo)
545 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000546
547 EmitVersionIdentMetadata();
Robert Lytton57765d52014-07-03 09:30:33 +0000548
549 EmitTargetMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000550}
551
Alexey Bader364a1162017-06-20 14:30:18 +0000552void CodeGenModule::EmitOpenCLMetadata() {
553 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
554 // opencl.ocl.version named metadata node.
555 llvm::Metadata *OCLVerElts[] = {
556 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
557 Int32Ty, LangOpts.OpenCLVersion / 100)),
558 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
559 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
560 llvm::NamedMDNode *OCLVerMD =
561 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
562 llvm::LLVMContext &Ctx = TheModule.getContext();
563 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
564}
565
Devang Patel945b8ae2011-03-23 16:29:39 +0000566void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
567 // Make sure that this type is translated.
568 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000569}
570
David Majnemer929025d2016-01-26 19:30:26 +0000571void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
572 // Make sure that this type is translated.
573 Types.RefreshTypeCacheForClass(RD);
574}
575
Dan Gohman947c9af2010-10-14 23:06:10 +0000576llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
577 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000578 return nullptr;
Dan Gohman947c9af2010-10-14 23:06:10 +0000579 return TBAA->getTBAAInfo(QTy);
580}
581
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000582llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
583 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000584 return nullptr;
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000585 return TBAA->getTBAAInfoForVTablePtr();
586}
587
Dan Gohman22695fc2012-09-28 21:58:29 +0000588llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
589 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000590 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000591 return TBAA->getTBAAStructInfo(QTy);
592}
593
Manman Renc451e572013-04-04 21:53:22 +0000594llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
595 llvm::MDNode *AccessN,
596 uint64_t O) {
597 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000598 return nullptr;
Manman Renc451e572013-04-04 21:53:22 +0000599 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
600}
601
Manman Ren4f755de2013-10-08 00:08:49 +0000602/// Decorate the instruction with a TBAA tag. For both scalar TBAA
603/// and struct-path aware TBAA, the tag has the same format:
604/// base type, access type and offset.
Manman Rene1ad74e2013-04-11 23:02:56 +0000605/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000606void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
607 llvm::MDNode *TBAAInfo,
608 bool ConvertTypeToTag) {
Manman Ren4f755de2013-10-08 00:08:49 +0000609 if (ConvertTypeToTag && TBAA)
Manman Rene1ad74e2013-04-11 23:02:56 +0000610 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
611 TBAA->getTBAAScalarTagInfo(TBAAInfo));
612 else
613 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
Dan Gohman947c9af2010-10-14 23:06:10 +0000614}
615
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000616void CodeGenModule::DecorateInstructionWithInvariantGroup(
617 llvm::Instruction *I, const CXXRecordDecl *RD) {
Piotr Padlewski34046bd2017-04-24 12:58:43 +0000618 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
619 llvm::MDNode::get(getLLVMContext(), {}));
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000620}
621
Alp Toker29cb66b2014-01-26 06:17:37 +0000622void CodeGenModule::Error(SourceLocation loc, StringRef message) {
623 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
624 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000625}
626
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000627/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000628/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000629void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000630 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000631 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000632 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000633 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
634 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000635}
Chris Lattner41af8182007-12-02 06:27:33 +0000636
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000637/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000638/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000639void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000640 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000641 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000642 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000643 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000644}
645
John McCall23c29fe2011-06-24 21:55:10 +0000646llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
647 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
648}
649
Mike Stump11289f42009-09-09 15:08:12 +0000650void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000651 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000652 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000653 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000654 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000655 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000656 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000657
John McCallc273f242010-10-30 11:50:40 +0000658 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000659 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000660 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
661 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000662}
663
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000664static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
665 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
666 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
667 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
668 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
669 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
670}
671
672static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
673 CodeGenOptions::TLSModel M) {
674 switch (M) {
675 case CodeGenOptions::GeneralDynamicTLSModel:
676 return llvm::GlobalVariable::GeneralDynamicTLSModel;
677 case CodeGenOptions::LocalDynamicTLSModel:
678 return llvm::GlobalVariable::LocalDynamicTLSModel;
679 case CodeGenOptions::InitialExecTLSModel:
680 return llvm::GlobalVariable::InitialExecTLSModel;
681 case CodeGenOptions::LocalExecTLSModel:
682 return llvm::GlobalVariable::LocalExecTLSModel;
683 }
684 llvm_unreachable("Invalid TLS model!");
685}
686
David Majnemerbb525f7c2014-10-15 22:38:23 +0000687void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000688 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000689
David Majnemerbb525f7c2014-10-15 22:38:23 +0000690 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000691 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000692
693 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000694 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000695 TLM = GetLLVMTLSModel(Attr->getModel());
696 }
697
698 GV->setThreadLocalMode(TLM);
699}
700
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000701StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
David Majnemerd2385c02016-01-08 20:48:26 +0000702 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
703
704 // Some ABIs don't have constructor variants. Make sure that base and
705 // complete constructors get mangled the same.
706 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
707 if (!getTarget().getCXXABI().hasConstructorVariants()) {
708 CXXCtorType OrigCtorType = GD.getCtorType();
709 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
710 if (OrigCtorType == Ctor_Base)
711 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
712 }
713 }
714
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +0000715 auto FoundName = MangledDeclNames.find(CanonicalGD);
716 if (FoundName != MangledDeclNames.end())
717 return FoundName->second;
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000718
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000719 const auto *ND = cast<NamedDecl>(GD.getDecl());
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000720 SmallString<256> Buffer;
721 StringRef Str;
722 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
723 llvm::raw_svector_ostream Out(Buffer);
724 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
725 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
726 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
727 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
728 else
729 getCXXABI().getMangleContext().mangleName(ND, Out);
730 Str = Out.str();
731 } else {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000732 IdentifierInfo *II = ND->getIdentifier();
733 assert(II && "Attempt to mangle unnamed decl.");
Erich Keane757d3172016-11-02 18:29:35 +0000734 const auto *FD = dyn_cast<FunctionDecl>(ND);
735
736 if (FD &&
737 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
738 llvm::raw_svector_ostream Out(Buffer);
739 Out << "__regcall3__" << II->getName();
740 Str = Out.str();
741 } else {
742 Str = II->getName();
743 }
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000744 }
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000745
Richard Smith6d0e97a2014-08-02 00:50:16 +0000746 // Keep the first result in the case of a mangling collision.
747 auto Result = Manglings.insert(std::make_pair(Str, GD));
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +0000748 return MangledDeclNames[CanonicalGD] = Result.first->first();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000749}
750
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000751StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
752 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000753 MangleContext &MangleCtx = getCXXABI().getMangleContext();
754 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +0000755
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000756 SmallString<256> Buffer;
757 llvm::raw_svector_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +0000758 if (!D)
Fariborz Jahanian63628032012-06-26 16:06:38 +0000759 MangleCtx.mangleGlobalBlock(BD,
760 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000761 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000762 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000763 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000764 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000765 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000766 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +0000767
Richard Smith6d0e97a2014-08-02 00:50:16 +0000768 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
769 return Result.first->first();
Anders Carlsson635186a2010-06-09 02:36:32 +0000770}
771
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000772llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +0000773 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000774}
775
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000776/// AddGlobalCtor - Add a function to the list that will be called before
777/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000778void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
779 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000780 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000781 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000782}
783
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000784/// AddGlobalDtor - Add a function to the list that will be called
785/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000786void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000787 // FIXME: Type coercion of void()* types.
Craig Topper4b566922014-06-09 02:04:02 +0000788 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000789}
790
Vassil Vassilev188ad3a2016-10-27 09:12:20 +0000791void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +0000792 if (Fns.empty()) return;
793
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000794 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +0000795 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000796 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000797
Reid Kleckner563f0e82014-05-23 21:13:45 +0000798 // Get the type of a ctor entry, { i32, void ()*, i8* }.
799 llvm::StructType *CtorStructTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +0000800 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000801
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000802 // Construct the constructor and destructor arrays.
John McCall23c9dc62016-11-28 22:18:27 +0000803 ConstantInitBuilder builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000804 auto ctors = builder.beginArray(CtorStructTy);
Yaron Kerenb54db522015-06-11 12:33:25 +0000805 for (const auto &I : Fns) {
John McCall6c9f1fdb2016-11-19 08:17:24 +0000806 auto ctor = ctors.beginStruct(CtorStructTy);
807 ctor.addInt(Int32Ty, I.Priority);
808 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
809 if (I.AssociatedData)
810 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
811 else
812 ctor.addNullPointer(VoidPtrTy);
John McCallf1788632016-11-28 22:18:30 +0000813 ctor.finishAndAddTo(ctors);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000814 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000815
John McCall18081af2016-11-19 20:12:25 +0000816 auto list =
817 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
818 /*constant*/ false,
819 llvm::GlobalValue::AppendingLinkage);
820
821 // The LTO linker doesn't seem to like it when we set an alignment
822 // on appending variables. Take it off as a workaround.
823 list->setAlignment(0);
824
Vassil Vassilev188ad3a2016-10-27 09:12:20 +0000825 Fns.clear();
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000826}
827
John McCalld4324142010-02-19 01:32:20 +0000828llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000829CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000830 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +0000831
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000832 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000833
Hans Wennborg275efb92014-05-28 01:52:23 +0000834 if (isa<CXXDestructorDecl>(D) &&
Reid Klecknera12cd282013-12-11 19:21:27 +0000835 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
Hans Wennborg275efb92014-05-28 01:52:23 +0000836 GD.getDtorType())) {
837 // Destructor variants in the Microsoft C++ ABI are always internal or
838 // linkonce_odr thunks emitted on an as-needed basis.
839 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
840 : llvm::GlobalValue::LinkOnceODRLinkage;
841 }
Reid Klecknera12cd282013-12-11 19:21:27 +0000842
Richard Smith5179eb72016-06-28 19:03:57 +0000843 if (isa<CXXConstructorDecl>(D) &&
844 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
845 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
846 // Our approach to inheriting constructors is fundamentally different from
847 // that used by the MS ABI, so keep our inheriting constructor thunks
848 // internal rather than trying to pick an unambiguous mangling for them.
849 return llvm::GlobalValue::InternalLinkage;
850 }
851
Hans Wennborg275efb92014-05-28 01:52:23 +0000852 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +0000853}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000854
Hans Wennborgbb4f9622015-05-28 17:44:56 +0000855void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
856 const auto *FD = cast<FunctionDecl>(GD.getDecl());
857
858 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
859 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
860 // Don't dllexport/import destructor thunks.
861 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
862 return;
863 }
864 }
865
866 if (FD->hasAttr<DLLImportAttr>())
867 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
868 else if (FD->hasAttr<DLLExportAttr>())
869 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
870 else
871 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
872}
873
Peter Collingbourne8dd14da2016-06-24 21:21:46 +0000874llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000875 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
876 if (!MDS) return nullptr;
877
Benjamin Kramer630cf8c2016-11-23 11:20:27 +0000878 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000879}
880
Rafael Espindolae033c8c2014-05-08 15:26:12 +0000881void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
882 llvm::Function *F) {
883 setNonAliasAttributes(D, F);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000884}
885
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000886void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000887 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000888 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000889 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +0000890 llvm::AttributeList PAL;
891 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
892 F->setAttributes(PAL);
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000893 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000894}
895
John McCall9b0a7ce2011-10-02 01:16:38 +0000896/// Determines whether the language options require us to model
897/// unwind exceptions. We treat -fexceptions as mandating this
898/// except under the fragile ObjC ABI with only ObjC exceptions
899/// enabled. This means, for example, that C with -fexceptions
900/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000901static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +0000902 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000903 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +0000904
905 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000906 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +0000907
908 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000909 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +0000910 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +0000911 }
912
913 return true;
914}
915
Daniel Dunbar38932572009-04-14 08:05:55 +0000916void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
917 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000918 llvm::AttrBuilder B;
919
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000920 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000921 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000922
David Blaikiebbafb8a2012-03-11 07:00:24 +0000923 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000924 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000925
Akira Hatanaka200500d2015-10-08 19:30:57 +0000926 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
927 B.addAttribute(llvm::Attribute::StackProtect);
928 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
929 B.addAttribute(llvm::Attribute::StackProtectStrong);
930 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
931 B.addAttribute(llvm::Attribute::StackProtectReq);
932
933 if (!D) {
Chandler Carruthfcd33142016-12-23 01:24:49 +0000934 // If we don't have a declaration to control inlining, the function isn't
935 // explicitly marked as alwaysinline for semantic reasons, and inlining is
936 // disabled, mark the function as noinline.
937 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
938 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
939 B.addAttribute(llvm::Attribute::NoInline);
940
Reid Kleckneree4930b2017-05-02 22:07:37 +0000941 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Akira Hatanaka200500d2015-10-08 19:30:57 +0000942 return;
943 }
944
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +0000945 // Track whether we need to add the optnone LLVM attribute,
946 // starting with the default for this optimization level.
947 bool ShouldAddOptNone =
948 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
949 // We can't add optnone in the following cases, it won't pass the verifier.
950 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
951 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
952 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
953
954 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
Chandler Carruthfcd33142016-12-23 01:24:49 +0000955 B.addAttribute(llvm::Attribute::OptimizeNone);
956
957 // OptimizeNone implies noinline; we should not be inlining such functions.
958 B.addAttribute(llvm::Attribute::NoInline);
959 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
960 "OptimizeNone and AlwaysInline on same function!");
961
962 // We still need to handle naked functions even though optnone subsumes
963 // much of their semantics.
964 if (D->hasAttr<NakedAttr>())
965 B.addAttribute(llvm::Attribute::Naked);
966
967 // OptimizeNone wins over OptimizeForSize and MinSize.
968 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
969 F->removeFnAttr(llvm::Attribute::MinSize);
970 } else if (D->hasAttr<NakedAttr>()) {
Eli Friedmanc55efe42011-08-22 23:55:33 +0000971 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000972 B.addAttribute(llvm::Attribute::Naked);
973 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +0000974 } else if (D->hasAttr<NoDuplicateAttr>()) {
975 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000976 } else if (D->hasAttr<NoInlineAttr>()) {
977 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +0000978 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Chandler Carruthfcd33142016-12-23 01:24:49 +0000979 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000980 // (noinline wins over always_inline, and we can't specify both in IR)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +0000981 B.addAttribute(llvm::Attribute::AlwaysInline);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000982 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
983 // If we're not inlining, then force everything that isn't always_inline to
984 // carry an explicit noinline attribute.
985 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
986 B.addAttribute(llvm::Attribute::NoInline);
987 } else {
988 // Otherwise, propagate the inline hint attribute and potentially use its
989 // absence to mark things as noinline.
990 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
991 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
992 return Redecl->isInlineSpecified();
993 })) {
994 B.addAttribute(llvm::Attribute::InlineHint);
995 } else if (CodeGenOpts.getInlining() ==
996 CodeGenOptions::OnlyHintInlining &&
997 !FD->isInlined() &&
998 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
999 B.addAttribute(llvm::Attribute::NoInline);
1000 }
1001 }
Eli Friedmanc55efe42011-08-22 23:55:33 +00001002 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +00001003
Chandler Carruthfcd33142016-12-23 01:24:49 +00001004 // Add other optimization related attributes if we are optimizing this
1005 // function.
1006 if (!D->hasAttr<OptimizeNoneAttr>()) {
1007 if (D->hasAttr<ColdAttr>()) {
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001008 if (!ShouldAddOptNone)
1009 B.addAttribute(llvm::Attribute::OptimizeForSize);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001010 B.addAttribute(llvm::Attribute::Cold);
1011 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001012
Chandler Carruthfcd33142016-12-23 01:24:49 +00001013 if (D->hasAttr<MinSizeAttr>())
1014 B.addAttribute(llvm::Attribute::MinSize);
1015 }
Richard Smithb555a762012-09-28 22:46:07 +00001016
Reid Kleckneree4930b2017-05-02 22:07:37 +00001017 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001018
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001019 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1020 if (alignment)
1021 F->setAlignment(alignment);
1022
Dan Gohmanc2853072015-09-03 22:51:53 +00001023 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1024 // reserve a bit for differentiating between virtual and non-virtual member
1025 // functions. If the current target's C++ ABI requires this and this is a
1026 // member function, set its alignment accordingly.
1027 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1028 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1029 F->setAlignment(2);
1030 }
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001031
1032 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1033 if (CodeGenOpts.SanitizeCfiCrossDso)
1034 if (auto *FD = dyn_cast<FunctionDecl>(D))
1035 CreateFunctionTypeMetadata(FD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001036}
1037
Mike Stump11289f42009-09-09 15:08:12 +00001038void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +00001039 llvm::GlobalValue *GV) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001040 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
Anders Carlsson072ef742011-01-29 19:41:00 +00001041 setGlobalVisibility(GV, ND);
John McCall457a04e2010-10-22 21:05:15 +00001042 else
1043 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +00001044
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001045 if (D && D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +00001046 addUsedGlobal(GV);
Rafael Espindola502f65a2014-05-05 20:21:03 +00001047}
1048
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00001049void CodeGenModule::setAliasAttributes(const Decl *D,
1050 llvm::GlobalValue *GV) {
1051 SetCommonAttributes(D, GV);
1052
1053 // Process the dllexport attribute based on whether the original definition
1054 // (not necessarily the aliasee) was exported.
1055 if (D->hasAttr<DLLExportAttr>())
1056 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1057}
1058
Rafael Espindola502f65a2014-05-05 20:21:03 +00001059void CodeGenModule::setNonAliasAttributes(const Decl *D,
Rafael Espindolaee076a22014-05-13 18:45:53 +00001060 llvm::GlobalObject *GO) {
1061 SetCommonAttributes(D, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +00001062
Javed Absar2a67c9e2017-06-05 10:11:57 +00001063 if (D) {
1064 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1065 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1066 GV->addAttribute("bss-section", SA->getName());
1067 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1068 GV->addAttribute("data-section", SA->getName());
1069 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1070 GV->addAttribute("rodata-section", SA->getName());
1071 }
1072
1073 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1074 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1075 if (!D->getAttr<SectionAttr>())
1076 F->addFnAttr("implicit-section-name", SA->getName());
1077 }
1078
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001079 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1080 GO->setSection(SA->getName());
Javed Absar2a67c9e2017-06-05 10:11:57 +00001081 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001082
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001083 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this, ForDefinition);
Daniel Dunbar38932572009-04-14 08:05:55 +00001084}
1085
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001086void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1087 llvm::Function *F,
1088 const CGFunctionInfo &FI) {
1089 SetLLVMFunctionAttributes(D, FI, F);
1090 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +00001091
1092 F->setLinkage(llvm::Function::InternalLinkage);
1093
Rafael Espindola502f65a2014-05-05 20:21:03 +00001094 setNonAliasAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001095}
1096
David Majnemerf6acb762014-04-25 17:07:16 +00001097static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
1098 const NamedDecl *ND) {
1099 // Set linkage and visibility in case we never see a definition.
1100 LinkageInfo LV = ND->getLinkageAndVisibility();
Richard Smith1283e982017-07-07 20:04:28 +00001101 if (!isExternallyVisible(LV.getLinkage())) {
David Majnemerf6acb762014-04-25 17:07:16 +00001102 // Don't set internal linkage on declarations.
1103 } else {
1104 if (ND->hasAttr<DLLImportAttr>()) {
1105 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1106 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1107 } else if (ND->hasAttr<DLLExportAttr>()) {
1108 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Majnemerf6acb762014-04-25 17:07:16 +00001109 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
1110 // "extern_weak" is overloaded in LLVM; we probably should have
1111 // separate linkage types for this.
1112 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1113 }
1114
1115 // Set visibility on a declaration only if it's explicit.
1116 if (LV.isVisibilityExplicit())
1117 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
1118 }
1119}
1120
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001121void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1122 llvm::Function *F) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001123 // Only if we are checking indirect calls.
1124 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1125 return;
1126
1127 // Non-static class methods are handled via vtable pointer checks elsewhere.
1128 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1129 return;
1130
1131 // Additionally, if building with cross-DSO support...
1132 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001133 // Skip available_externally functions. They won't be codegen'ed in the
1134 // current module anyway.
1135 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1136 return;
1137 }
1138
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001139 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001140 F->addTypeMetadata(0, MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001141
1142 // Emit a hash-based bit set entry for cross-DSO calls.
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001143 if (CodeGenOpts.SanitizeCfiCrossDso)
1144 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1145 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001146}
1147
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001148void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1149 bool IsIncompleteFunction,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001150 bool IsThunk,
1151 ForDefinition_t IsForDefinition) {
1152
Pete Cooper2f1637a2015-05-20 17:17:45 +00001153 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001154 // If this is an intrinsic function, set the function's attributes
1155 // to the intrinsic's attributes.
Pete Cooper2f1637a2015-05-20 17:17:45 +00001156 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001157 return;
1158 }
1159
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001160 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +00001161
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001162 if (!IsIncompleteFunction) {
John McCalla729c622012-02-17 03:33:10 +00001163 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001164 // Setup target-specific attributes.
1165 if (!IsForDefinition)
1166 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this,
1167 NotForDefinition);
1168 }
Mike Stump11289f42009-09-09 15:08:12 +00001169
Bob Wilsonfc6297f2014-04-01 01:38:16 +00001170 // Add the Returned attribute for "this", except for iOS 5 and earlier
1171 // where substantial code, including the libstdc++ dylib, was compiled with
1172 // GCC and does not actually return "this".
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001173 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00001174 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001175 assert(!F->arg_empty() &&
1176 F->arg_begin()->getType()
1177 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1178 "unexpected this return");
1179 F->addAttribute(1, llvm::Attribute::Returned);
1180 }
1181
Daniel Dunbar38932572009-04-14 08:05:55 +00001182 // Only a few attributes are set on declarations; these may later be
1183 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +00001184
David Majnemerf6acb762014-04-25 17:07:16 +00001185 setLinkageAndVisibilityForGV(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +00001186
Javed Absar2a67c9e2017-06-05 10:11:57 +00001187 if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1188 F->addFnAttr("implicit-section-name");
1189 }
1190
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001191 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +00001192 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +00001193
Richard Smith351241c2016-04-07 21:46:12 +00001194 if (FD->isReplaceableGlobalAllocationFunction()) {
1195 // A replaceable global allocation function does not act like a builtin by
1196 // default, only if it is invoked by a new-expression or delete-expression.
Reid Klecknerde864822017-03-21 16:57:30 +00001197 F->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001198 llvm::Attribute::NoBuiltin);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001199
Richard Smith351241c2016-04-07 21:46:12 +00001200 // A sane operator new returns a non-aliasing pointer.
1201 // FIXME: Also add NonNull attribute to the return value
1202 // for the non-nothrow forms?
1203 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1204 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1205 (Kind == OO_New || Kind == OO_Array_New))
Reid Klecknerde864822017-03-21 16:57:30 +00001206 F->addAttribute(llvm::AttributeList::ReturnIndex,
Richard Smith351241c2016-04-07 21:46:12 +00001207 llvm::Attribute::NoAlias);
1208 }
1209
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001210 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001211 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001212 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1213 if (MD->isVirtual())
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001214 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001215
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001216 // Don't emit entries for function declarations in the cross-DSO mode. This
1217 // is handled with better precision by the receiving DSO.
1218 if (!CodeGenOpts.SanitizeCfiCrossDso)
1219 CreateFunctionTypeMetadata(FD, F);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001220}
1221
Rafael Espindola060062a2014-03-06 22:15:10 +00001222void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +00001223 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001224 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001225 LLVMUsed.emplace_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001226}
1227
Rafael Espindola060062a2014-03-06 22:15:10 +00001228void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1229 assert(!GV->isDeclaration() &&
1230 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001231 LLVMCompilerUsed.emplace_back(GV);
Rafael Espindola060062a2014-03-06 22:15:10 +00001232}
1233
1234static void emitUsed(CodeGenModule &CGM, StringRef Name,
Sanjoy Dase369bd92017-05-01 17:08:00 +00001235 std::vector<llvm::WeakTrackingVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001236 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +00001237 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001238 return;
1239
Rafael Espindola060062a2014-03-06 22:15:10 +00001240 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +00001241 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +00001242 UsedArray.resize(List.size());
1243 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001244 UsedArray[i] =
Justin Holewinskif37f3d32015-02-02 21:05:49 +00001245 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1246 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +00001247 }
Mike Stump11289f42009-09-09 15:08:12 +00001248
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001249 if (UsedArray.empty())
1250 return;
Rafael Espindola060062a2014-03-06 22:15:10 +00001251 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +00001252
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001253 auto *GV = new llvm::GlobalVariable(
1254 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1255 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001256
1257 GV->setSection("llvm.metadata");
1258}
1259
Rafael Espindola060062a2014-03-06 22:15:10 +00001260void CodeGenModule::emitLLVMUsed() {
1261 emitUsed(*this, "llvm.used", LLVMUsed);
1262 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1263}
1264
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001265void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001266 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001267 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1268}
1269
Aaron Ballman5d041be2013-06-04 02:07:14 +00001270void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1271 llvm::SmallString<32> Opt;
1272 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001273 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballman5d041be2013-06-04 02:07:14 +00001274 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1275}
1276
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001277void CodeGenModule::AddDependentLib(StringRef Lib) {
1278 llvm::SmallString<24> Opt;
1279 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001280 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001281 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1282}
1283
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001284/// \brief Add link options implied by the given module, including modules
1285/// it depends on, using a postorder walk.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001286static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
Peter Collingbourne89061b22017-06-12 20:10:48 +00001287 SmallVectorImpl<llvm::MDNode *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001288 llvm::SmallPtrSet<Module *, 16> &Visited) {
1289 // Import this module's parent.
David Blaikie82e95a32014-11-19 07:49:47 +00001290 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001291 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001292 }
1293
1294 // Import this module's dependencies.
1295 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001296 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001297 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001298 }
1299
1300 // Add linker options to link against the libraries/frameworks
1301 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001302 llvm::LLVMContext &Context = CGM.getLLVMContext();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001303 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001304 // Link against a framework. Frameworks are currently Darwin only, so we
1305 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001306 if (Mod->LinkLibraries[I-1].IsFramework) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001307 llvm::Metadata *Args[2] = {
1308 llvm::MDString::get(Context, "-framework"),
1309 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001310
1311 Metadata.push_back(llvm::MDNode::get(Context, Args));
1312 continue;
1313 }
1314
1315 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001316 llvm::SmallString<24> Opt;
1317 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1318 Mod->LinkLibraries[I-1].Library, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001319 auto *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001320 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1321 }
1322}
1323
1324void CodeGenModule::EmitModuleLinkOptions() {
1325 // Collect the set of all of the modules we want to visit to emit link
1326 // options, which is essentially the imported modules and all of their
1327 // non-explicit child modules.
1328 llvm::SetVector<clang::Module *> LinkModules;
1329 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1330 SmallVector<clang::Module *, 16> Stack;
1331
1332 // Seed the stack with imported modules.
Manman Ren9803ee82017-01-11 18:47:38 +00001333 for (Module *M : ImportedModules) {
1334 // Do not add any link flags when an implementation TU of a module imports
1335 // a header of that same module.
1336 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1337 !getLangOpts().isCompilingModule())
1338 continue;
Yaron Kerenb54db522015-06-11 12:33:25 +00001339 if (Visited.insert(M).second)
1340 Stack.push_back(M);
Manman Ren9803ee82017-01-11 18:47:38 +00001341 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001342
1343 // Find all of the modules to import, making a little effort to prune
1344 // non-leaf modules.
1345 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001346 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001347
1348 bool AnyChildren = false;
1349
1350 // Visit the submodules of this module.
1351 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1352 SubEnd = Mod->submodule_end();
1353 Sub != SubEnd; ++Sub) {
1354 // Skip explicit children; they need to be explicitly imported to be
1355 // linked against.
1356 if ((*Sub)->IsExplicit)
1357 continue;
1358
David Blaikie82e95a32014-11-19 07:49:47 +00001359 if (Visited.insert(*Sub).second) {
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001360 Stack.push_back(*Sub);
1361 AnyChildren = true;
1362 }
1363 }
1364
1365 // We didn't find any children, so add this module to the list of
1366 // modules to link against.
1367 if (!AnyChildren) {
1368 LinkModules.insert(Mod);
1369 }
1370 }
1371
1372 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001373 // order. We don't do anything to try to order import link flags with respect
1374 // to linker options inserted by things like #pragma comment().
Peter Collingbourne89061b22017-06-12 20:10:48 +00001375 SmallVector<llvm::MDNode *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001376 Visited.clear();
Yaron Kerenb54db522015-06-11 12:33:25 +00001377 for (Module *M : LinkModules)
1378 if (Visited.insert(M).second)
1379 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
Daniel Dunbar69e47462013-01-17 01:35:06 +00001380 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001381 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001382
Daniel Dunbar69e47462013-01-17 01:35:06 +00001383 // Add the linker options metadata flag.
Peter Collingbourne89061b22017-06-12 20:10:48 +00001384 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1385 for (auto *MD : LinkerOptionsMetadata)
1386 NMD->addOperand(MD);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001387}
1388
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001389void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +00001390 // Emit code for any potentially referenced deferred decls. Since a
1391 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001392 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001393
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001394 if (!DeferredVTables.empty()) {
1395 EmitDeferredVTables();
John McCall6bd2a892013-01-25 22:31:03 +00001396
Eric Christopherd160c502016-01-29 01:35:53 +00001397 // Emitting a vtable doesn't directly cause more vtables to
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001398 // become deferred, although it can cause functions to be
Eric Christopherd160c502016-01-29 01:35:53 +00001399 // emitted that then need those vtables.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001400 assert(DeferredVTables.empty());
1401 }
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001402
Eric Christopherd160c502016-01-29 01:35:53 +00001403 // Stop if we're out of both deferred vtables and deferred declarations.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001404 if (DeferredDeclsToEmit.empty())
1405 return;
John McCall6bd2a892013-01-25 22:31:03 +00001406
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001407 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1408 // work, it will not interfere with this.
Sanjoy Das70a60512017-05-01 06:12:13 +00001409 std::vector<GlobalDecl> CurDeclsToEmit;
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001410 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1411
Sanjoy Das70a60512017-05-01 06:12:13 +00001412 for (GlobalDecl &D : CurDeclsToEmit) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00001413 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1414 // to get GlobalValue with exactly the type we need, not something that
1415 // might had been created for another decl with the same mangled name but
1416 // different type.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001417 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
John McCalld195d4c2016-11-30 23:25:13 +00001418 GetAddrOfGlobal(D, ForDefinition));
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001419
1420 // In case of different address spaces, we may still get a cast, even with
1421 // IsForDefinition equal to true. Query mangled names table to get
1422 // GlobalValue.
1423 if (!GV)
1424 GV = GetGlobalValue(getMangledName(D));
1425
1426 // Make sure GetGlobalValue returned non-null.
1427 assert(GV);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001428
John McCallc2af9392010-05-27 01:45:30 +00001429 // Check to see if we've already emitted this. This is necessary
1430 // for a couple of reasons: first, decls can end up in the
1431 // deferred-decls queue multiple times, and second, decls can end
1432 // up with definitions in unusual ways (e.g. by an extern inline
1433 // function acquiring a strong function redefinition). Just
1434 // ignore these cases.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001435 if (!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001436 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001437
Chris Lattner45470942009-03-21 09:44:56 +00001438 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001439 EmitGlobalDefinition(D, GV);
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001440
1441 // If we found out that we need to emit more decls, do that recursively.
1442 // This has the advantage that the decls are emitted in a DFS and related
1443 // ones are close together, which is convenient for testing.
1444 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1445 EmitDeferred();
1446 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1447 }
Chris Lattner45470942009-03-21 09:44:56 +00001448 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001449}
Chris Lattner09153c02007-06-22 18:48:09 +00001450
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001451void CodeGenModule::EmitVTablesOpportunistically() {
1452 // Try to emit external vtables as available_externally if they have emitted
1453 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1454 // is not allowed to create new references to things that need to be emitted
1455 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1456
Piotr Padlewski05547742017-06-01 09:24:36 +00001457 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1458 && "Only emit opportunistic vtables with optimizations");
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001459
1460 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1461 assert(getVTables().isVTableExternal(RD) &&
1462 "This queue should only contain external vtables");
1463 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1464 VTables.GenerateClassData(RD);
1465 }
1466 OpportunisticVTables.clear();
1467}
1468
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001469void CodeGenModule::EmitGlobalAnnotations() {
1470 if (Annotations.empty())
1471 return;
1472
1473 // Create a new global variable for the ConstantStruct in the Module.
1474 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1475 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001476 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1477 llvm::GlobalValue::AppendingLinkage,
1478 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001479 gv->setSection(AnnotationSection);
1480}
1481
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001482llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001483 llvm::Constant *&AStr = AnnotationStrings[Str];
1484 if (AStr)
1485 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001486
1487 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001488 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001489 auto *gv =
1490 new llvm::GlobalVariable(getModule(), s->getType(), true,
1491 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001492 gv->setSection(AnnotationSection);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001493 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Benjamin Kramereed80612013-11-10 16:55:11 +00001494 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001495 return gv;
1496}
1497
1498llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1499 SourceManager &SM = getContext().getSourceManager();
1500 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1501 if (PLoc.isValid())
1502 return EmitAnnotationString(PLoc.getFilename());
1503 return EmitAnnotationString(SM.getBufferName(Loc));
1504}
1505
1506llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1507 SourceManager &SM = getContext().getSourceManager();
1508 PresumedLoc PLoc = SM.getPresumedLoc(L);
1509 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1510 SM.getExpansionLineNumber(L);
1511 return llvm::ConstantInt::get(Int32Ty, LineNo);
1512}
1513
Mike Stump11289f42009-09-09 15:08:12 +00001514llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001515 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001516 SourceLocation L) {
1517 // Get the globals for file name, annotation, and the line number.
1518 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1519 *UnitGV = EmitAnnotationUnit(L),
1520 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001521
Daniel Dunbar346892a2009-04-14 22:41:13 +00001522 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001523 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001524 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1525 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1526 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1527 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001528 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001529 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001530}
1531
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001532void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1533 llvm::GlobalValue *GV) {
1534 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1535 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001536 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1537 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001538}
1539
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001540bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1541 llvm::Function *Fn,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001542 SourceLocation Loc) const {
1543 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1544 // Blacklist by function name.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001545 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001546 return true;
1547 // Blacklist by location.
Yaron Kerened1fe5d2015-10-03 05:15:57 +00001548 if (Loc.isValid())
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001549 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001550 // If location is unknown, this may be a compiler-generated function. Assume
1551 // it's located in the main file.
1552 auto &SM = Context.getSourceManager();
1553 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001554 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001555 }
1556 return false;
1557}
1558
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001559bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1560 SourceLocation Loc, QualType Ty,
1561 StringRef Category) const {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001562 // For now globals can be blacklisted only in ASan and KASan.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001563 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
1564 (SanitizerKind::Address | SanitizerKind::KernelAddress);
1565 if (!EnabledAsanMask)
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001566 return false;
1567 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001568 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001569 return true;
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001570 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001571 return true;
1572 // Check global type.
1573 if (!Ty.isNull()) {
1574 // Drill down the array types: if global variable of a fixed type is
1575 // blacklisted, we also don't instrument arrays of them.
1576 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1577 Ty = AT->getElementType();
1578 Ty = Ty.getCanonicalType().getUnqualifiedType();
1579 // We allow to blacklist only record types (classes, structs etc.)
1580 if (Ty->isRecordType()) {
1581 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001582 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001583 return true;
1584 }
1585 }
1586 return false;
1587}
1588
Dean Michael Berris835832d2017-03-30 00:29:36 +00001589bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1590 StringRef Category) const {
1591 if (!LangOpts.XRayInstrument)
1592 return false;
1593 const auto &XRayFilter = getContext().getXRayFilter();
1594 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1595 auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
1596 if (Loc.isValid())
1597 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1598 if (Attr == ImbueAttr::NONE)
1599 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1600 switch (Attr) {
1601 case ImbueAttr::NONE:
1602 return false;
1603 case ImbueAttr::ALWAYS:
1604 Fn->addFnAttr("function-instrument", "xray-always");
1605 break;
Dean Michael Berris170429e2017-05-24 05:46:36 +00001606 case ImbueAttr::ALWAYS_ARG1:
1607 Fn->addFnAttr("function-instrument", "xray-always");
1608 Fn->addFnAttr("xray-log-args", "1");
1609 break;
Dean Michael Berris835832d2017-03-30 00:29:36 +00001610 case ImbueAttr::NEVER:
1611 Fn->addFnAttr("function-instrument", "xray-never");
1612 break;
1613 }
1614 return true;
1615}
1616
Hans Wennborg43a0f992015-01-10 01:19:48 +00001617bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001618 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001619 if (LangOpts.EmitAllDecls)
Hans Wennborg43a0f992015-01-10 01:19:48 +00001620 return true;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001621
Hans Wennborg43a0f992015-01-10 01:19:48 +00001622 return getContext().DeclMustBeEmitted(Global);
1623}
1624
1625bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1626 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1627 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1628 // Implicit template instantiations may change linkage if they are later
1629 // explicitly instantiated, so they should not be emitted eagerly.
1630 return false;
Richard Smithd9b90092016-07-02 01:32:16 +00001631 if (const auto *VD = dyn_cast<VarDecl>(Global))
1632 if (Context.getInlineVariableDefinitionKind(VD) ==
1633 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1634 // A definition of an inline constexpr static data member may change
1635 // linkage later if it's redeclared outside the class.
1636 return false;
Samuel Antaof8b50122015-07-13 22:54:53 +00001637 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1638 // codegen for global variables, because they may be marked as threadprivate.
1639 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1640 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1641 return false;
Hans Wennborg43a0f992015-01-10 01:19:48 +00001642
1643 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001644}
1645
John McCall7f416cc2015-09-08 08:05:57 +00001646ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
Nico Webercf4ff5862012-10-11 10:13:44 +00001647 const CXXUuidofExpr* E) {
1648 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1649 // well-formed.
David Majnemer2041b462016-03-28 03:19:50 +00001650 StringRef Uuid = E->getUuidStr();
David Majnemercf963ce2013-08-09 08:35:59 +00001651 std::string Name = "_GUID_" + Uuid.lower();
1652 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00001653
David Majnemer65687602016-03-27 04:46:14 +00001654 // The UUID descriptor should be pointer aligned.
1655 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
John McCall7f416cc2015-09-08 08:05:57 +00001656
Nico Webercf4ff5862012-10-11 10:13:44 +00001657 // Look for an existing global.
1658 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
John McCall7f416cc2015-09-08 08:05:57 +00001659 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00001660
Nico Weber17d3a2c2014-09-08 16:26:36 +00001661 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Webercf4ff5862012-10-11 10:13:44 +00001662 assert(Init && "failed to initialize as constant");
1663
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001664 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00001665 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00001666 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001667 if (supportsCOMDAT())
1668 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
John McCall7f416cc2015-09-08 08:05:57 +00001669 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00001670}
1671
John McCall7f416cc2015-09-08 08:05:57 +00001672ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001673 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1674 assert(AA && "No alias?");
1675
John McCall7f416cc2015-09-08 08:05:57 +00001676 CharUnits Alignment = getContext().getDeclAlign(VD);
Chris Lattner2192fe52011-07-18 04:24:23 +00001677 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001678
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001679 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00001680 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001681 if (Entry) {
1682 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
John McCall7f416cc2015-09-08 08:05:57 +00001683 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1684 return ConstantAddress(Ptr, Alignment);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001685 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001686
1687 llvm::Constant *Aliasee;
1688 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00001689 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1690 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00001691 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001692 else
John McCall7ec50432010-03-19 23:29:14 +00001693 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00001694 llvm::PointerType::getUnqual(DeclTy),
1695 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001696
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001697 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001698 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1699 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001700
John McCall7f416cc2015-09-08 08:05:57 +00001701 return ConstantAddress(Aliasee, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001702}
1703
Chris Lattnere0be0df2009-05-12 21:21:08 +00001704void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001705 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001706
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001707 // Weak references don't produce any output by themselves.
1708 if (Global->hasAttr<WeakRefAttr>())
1709 return;
1710
Chris Lattner54041692009-03-22 21:47:11 +00001711 // If this is an alias definition (which otherwise looks like a declaration)
1712 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001713 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00001714 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001715
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001716 // IFunc like an alias whose value is resolved at runtime by calling resolver.
1717 if (Global->hasAttr<IFuncAttr>())
1718 return emitIFuncDefinition(GD);
1719
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001720 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001721 if (LangOpts.CUDA) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00001722 if (LangOpts.CUDAIsDevice) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001723 if (!Global->hasAttr<CUDADeviceAttr>() &&
1724 !Global->hasAttr<CUDAGlobalAttr>() &&
1725 !Global->hasAttr<CUDAConstantAttr>() &&
1726 !Global->hasAttr<CUDASharedAttr>())
1727 return;
1728 } else {
Artem Belevich42e19492016-03-02 18:28:50 +00001729 // We need to emit host-side 'shadows' for all global
1730 // device-side variables because the CUDA runtime needs their
1731 // size and host-side address in order to provide access to
1732 // their device-side incarnations.
1733
1734 // So device-only functions are the only things we skip.
1735 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1736 Global->hasAttr<CUDADeviceAttr>())
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001737 return;
Artem Belevich42e19492016-03-02 18:28:50 +00001738
1739 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1740 "Expected Variable or Function");
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001741 }
1742 }
1743
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001744 if (LangOpts.OpenMP) {
1745 // If this is OpenMP device, check if it is legal to emit this global
1746 // normally.
1747 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1748 return;
1749 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1750 if (MustBeEmitted(Global))
1751 EmitOMPDeclareReduction(DRD);
1752 return;
1753 }
1754 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001755
Chris Lattner45470942009-03-21 09:44:56 +00001756 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001757 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001758 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001759 if (!FD->doesThisDeclarationHaveABody()) {
1760 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1761 return;
1762
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001763 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00001764
1765 // Compute the function info and LLVM type.
1766 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1767 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1768
1769 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1770 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001771 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001772 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001773 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001774 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001775 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
Artem Belevich42e19492016-03-02 18:28:50 +00001776 // We need to emit device-side global CUDA variables even if a
1777 // variable does not have a definition -- we still need to define
1778 // host-side shadow for it.
1779 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1780 !VD->hasDefinition() &&
1781 (VD->hasAttr<CUDAConstantAttr>() ||
1782 VD->hasAttr<CUDADeviceAttr>());
1783 if (!MustEmitForCuda &&
1784 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
Richard Smithd9b90092016-07-02 01:32:16 +00001785 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1786 // If this declaration may have caused an inline variable definition to
1787 // change linkage, make sure that it's emitted.
1788 if (Context.getInlineVariableDefinitionKind(VD) ==
1789 ASTContext::InlineVariableDefinitionKind::Strong)
1790 GetAddrOfGlobalVar(VD);
Douglas Gregorbeecd582009-04-21 17:11:58 +00001791 return;
Richard Smithd9b90092016-07-02 01:32:16 +00001792 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00001793 }
1794
Hans Wennborg43a0f992015-01-10 01:19:48 +00001795 // Defer code generation to first use when possible, e.g. if this is an inline
1796 // function. If the global must always be emitted, do it eagerly if possible
1797 // to benefit from cache locality.
1798 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001799 // Emit the definition if it can't be deferred.
1800 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001801 return;
1802 }
John McCall70013b62010-07-15 23:40:35 +00001803
1804 // If we're deferring emission of a C++ variable with an
1805 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001806 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00001807 cast<VarDecl>(Global)->hasInit()) {
1808 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00001809 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00001810 }
Hans Wennborg43a0f992015-01-10 01:19:48 +00001811
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001812 StringRef MangledName = getMangledName(GD);
Sanjoy Das70a60512017-05-01 06:12:13 +00001813 if (GetGlobalValue(MangledName) != nullptr) {
Hans Wennborg43a0f992015-01-10 01:19:48 +00001814 // The value has already been used and should therefore be emitted.
Sanjoy Das70a60512017-05-01 06:12:13 +00001815 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001816 } else if (MustBeEmitted(Global)) {
1817 // The value must be emitted, but cannot be emitted eagerly.
1818 assert(!MayBeEmittedEagerly(Global));
Sanjoy Das70a60512017-05-01 06:12:13 +00001819 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001820 } else {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001821 // Otherwise, remember that we saw a deferred decl with this name. The
1822 // first use of the mangled name will cause it to move into
1823 // DeferredDeclsToEmit.
1824 DeferredDecls[MangledName] = GD;
1825 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00001826}
1827
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001828// Check if T is a class type with a destructor that's not dllimport.
1829static bool HasNonDllImportDtor(QualType T) {
1830 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
1831 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1832 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1833 return true;
1834
1835 return false;
1836}
1837
Rafael Espindolac5941352011-10-26 20:41:06 +00001838namespace {
1839 struct FunctionIsDirectlyRecursive :
1840 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1841 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001842 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00001843 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001844 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1845 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001846 }
1847 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1848
1849 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001850 const FunctionDecl *FD = E->getDirectCallee();
1851 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00001852 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001853 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1854 if (Attr && Name == Attr->getLabel()) {
1855 Result = true;
1856 return false;
1857 }
1858 unsigned BuiltinID = FD->getBuiltinID();
David Majnemer41011f62015-06-25 23:50:40 +00001859 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
Rafael Espindolac5941352011-10-26 20:41:06 +00001860 return true;
Eric Christopher02d5d862015-08-06 01:01:12 +00001861 StringRef BuiltinName = BI.getName(BuiltinID);
Nick Lewycky9ed5b152012-01-18 03:41:19 +00001862 if (BuiltinName.startswith("__builtin_") &&
1863 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001864 Result = true;
1865 return false;
1866 }
1867 return true;
1868 }
1869 };
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001870
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001871 // Make sure we're not referencing non-imported vars or functions.
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001872 struct DLLImportFunctionVisitor
1873 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1874 bool SafeToInline = true;
1875
Hans Wennborg1b3aee72016-09-13 22:51:42 +00001876 bool shouldVisitImplicitCode() const { return true; }
1877
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001878 bool VisitVarDecl(VarDecl *VD) {
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001879 if (VD->getTLSKind()) {
1880 // A thread-local variable cannot be imported.
1881 SafeToInline = false;
1882 return SafeToInline;
1883 }
1884
1885 // A variable definition might imply a destructor call.
1886 if (VD->isThisDeclarationADefinition())
1887 SafeToInline = !HasNonDllImportDtor(VD->getType());
1888
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001889 return SafeToInline;
1890 }
1891
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001892 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1893 if (const auto *D = E->getTemporary()->getDestructor())
1894 SafeToInline = D->hasAttr<DLLImportAttr>();
1895 return SafeToInline;
1896 }
1897
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001898 bool VisitDeclRefExpr(DeclRefExpr *E) {
1899 ValueDecl *VD = E->getDecl();
1900 if (isa<FunctionDecl>(VD))
1901 SafeToInline = VD->hasAttr<DLLImportAttr>();
1902 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1903 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1904 return SafeToInline;
1905 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001906
Hans Wennborg1b3aee72016-09-13 22:51:42 +00001907 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
1908 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
1909 return SafeToInline;
1910 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001911
Hans Wennborg251c2042017-01-23 23:57:50 +00001912 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1913 CXXMethodDecl *M = E->getMethodDecl();
1914 if (!M) {
1915 // Call through a pointer to member function. This is safe to inline.
1916 SafeToInline = true;
1917 } else {
1918 SafeToInline = M->hasAttr<DLLImportAttr>();
1919 }
1920 return SafeToInline;
1921 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001922
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001923 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1924 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1925 return SafeToInline;
1926 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001927
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001928 bool VisitCXXNewExpr(CXXNewExpr *E) {
1929 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1930 return SafeToInline;
1931 }
1932 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001933}
Rafael Espindolac5941352011-10-26 20:41:06 +00001934
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001935// isTriviallyRecursive - Check if this function calls another
1936// decl that, because of the asm attribute or the other decl being a builtin,
1937// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00001938bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001939CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1940 StringRef Name;
1941 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00001942 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001943 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1944 if (!Attr)
1945 return false;
1946 Name = Attr->getLabel();
1947 } else {
1948 Name = FD->getName();
1949 }
Rafael Espindolac5941352011-10-26 20:41:06 +00001950
David Majnemer64b0bdf2015-06-30 04:41:18 +00001951 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001952 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00001953 return Walker.Result;
1954}
1955
Hans Wennborg93f75472016-09-13 21:08:20 +00001956bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001957 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00001958 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001959 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00001960 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00001961 return false;
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001962
1963 if (F->hasAttr<DLLImportAttr>()) {
1964 // Check whether it would be safe to inline this dllimport function.
1965 DLLImportFunctionVisitor Visitor;
1966 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1967 if (!Visitor.SafeToInline)
1968 return false;
Hans Wennborg93f75472016-09-13 21:08:20 +00001969
1970 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
1971 // Implicit destructor invocations aren't captured in the AST, so the
1972 // check above can't see them. Check for them manually here.
1973 for (const Decl *Member : Dtor->getParent()->decls())
1974 if (isa<FieldDecl>(Member))
1975 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
1976 return false;
1977 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
1978 if (HasNonDllImportDtor(B.getType()))
1979 return false;
1980 }
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001981 }
1982
Rafael Espindolac5941352011-10-26 20:41:06 +00001983 // PR9614. Avoid cases where the source code is lying to us. An available
1984 // externally function should have an equivalent function somewhere else,
1985 // but a function that calls itself is clearly not equivalent to the real
1986 // implementation.
1987 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001988 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00001989}
1990
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001991bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
1992 return CodeGenOpts.OptimizationLevel > 0;
1993}
1994
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001995void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001996 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001997
Dan Gohman145f3f12010-04-19 16:39:44 +00001998 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00001999 Context.getSourceManager(),
2000 "Generating code for declaration");
2001
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002002 if (isa<FunctionDecl>(D)) {
Douglas Gregora700f682010-07-13 06:02:28 +00002003 // At -O0, don't generate IR for functions with available_externally
2004 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002005 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00002006 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00002007
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002008 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +00002009 // Make sure to emit the definition(s) before we emit the thunks.
2010 // This is necessary for the generation of certain thunks.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002011 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002012 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002013 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002014 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Eli Friedman49a94b12011-05-06 17:27:27 +00002015 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002016 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002017
Douglas Gregora700f682010-07-13 06:02:28 +00002018 if (Method->isVirtual())
2019 getVTables().EmitThunks(GD);
2020
Eli Friedman49a94b12011-05-06 17:27:27 +00002021 return;
Douglas Gregora700f682010-07-13 06:02:28 +00002022 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00002023
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002024 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00002025 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002026
2027 if (const auto *VD = dyn_cast<VarDecl>(D))
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002028 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002029
David Blaikie83d382b2011-09-23 05:06:16 +00002030 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00002031}
2032
Andrey Bokhankocab58582015-08-31 13:20:44 +00002033static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2034 llvm::Function *NewFn);
2035
Chris Lattnerd4808922009-03-22 21:03:39 +00002036/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2037/// module, create and return an llvm Function with the specified type. If there
2038/// is something in the module with the specified name, return it potentially
2039/// bitcasted to the right type.
2040///
2041/// If D is non-null, it specifies a decl that correspond to this. This is used
2042/// to set the attributes on the function when it is first created.
Reid Klecknerde864822017-03-21 16:57:30 +00002043llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2044 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2045 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2046 ForDefinition_t IsForDefinition) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002047 const Decl *D = GD.getDecl();
2048
Chris Lattnera85d68e2009-03-21 09:25:43 +00002049 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002050 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002051 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002052 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002053 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002054 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002055 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002056 }
2057
Hans Wennborg0a20f542014-08-29 00:16:06 +00002058 // Handle dropped DLL attributes.
2059 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2060 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2061
Andrey Bokhankocab58582015-08-31 13:20:44 +00002062 // If there are two attempts to define the same mangled name, issue an
2063 // error.
2064 if (IsForDefinition && !Entry->isDeclaration()) {
2065 GlobalDecl OtherGD;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002066 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2067 // to make sure that we issue an error only once.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002068 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2069 (GD.getCanonicalDecl().getDecl() !=
2070 OtherGD.getCanonicalDecl().getDecl()) &&
2071 DiagnosedConflictingDefinitions.insert(GD).second) {
2072 getDiags().Report(D->getLocation(),
2073 diag::err_duplicate_mangled_name);
2074 getDiags().Report(OtherGD.getDecl()->getLocation(),
2075 diag::note_previous_definition);
2076 }
2077 }
2078
2079 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2080 (Entry->getType()->getElementType() == Ty)) {
Chris Lattnera85d68e2009-03-21 09:25:43 +00002081 return Entry;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002082 }
Mike Stump11289f42009-09-09 15:08:12 +00002083
Chris Lattnera85d68e2009-03-21 09:25:43 +00002084 // Make sure the result is of the correct type.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002085 // (If function is requested for a definition, we always need to create a new
2086 // function, not just return a bitcast.)
2087 if (!IsForDefinition)
2088 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00002089 }
Mike Stump11289f42009-09-09 15:08:12 +00002090
Eli Friedmancc522d92009-11-09 05:07:37 +00002091 // This function doesn't have a complete type (for example, the return
2092 // type is an incomplete struct). Use a fake type instead, and make
2093 // sure not to try to set attributes.
2094 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00002095
Chris Lattner2192fe52011-07-18 04:24:23 +00002096 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00002097 if (isa<llvm::FunctionType>(Ty)) {
2098 FTy = cast<llvm::FunctionType>(Ty);
2099 } else {
John McCall9dc0db22011-05-15 01:53:33 +00002100 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00002101 IsIncompleteFunction = true;
2102 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002103
2104 llvm::Function *F =
2105 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2106 Entry ? StringRef() : MangledName, &getModule());
2107
2108 // If we already created a function with the same mangled name (but different
2109 // type) before, take its name and add it to the list of functions to be
2110 // replaced with F at the end of CodeGen.
2111 //
2112 // This happens if there is a prototype for a function (e.g. "int f()") and
2113 // then a definition of a different type (e.g. "int f(int x)").
2114 if (Entry) {
2115 F->takeName(Entry);
2116
2117 // This might be an implementation of a function without a prototype, in
2118 // which case, try to do special replacement of calls which match the new
2119 // prototype. The really key thing here is that we also potentially drop
2120 // arguments from the call site so as to make a direct call, which makes the
2121 // inliner happier and suppresses a number of optimizer warnings (!) about
2122 // dropping arguments.
2123 if (!Entry->use_empty()) {
2124 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2125 Entry->removeDeadConstantUsers();
2126 }
2127
2128 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2129 F, Entry->getType()->getElementType()->getPointerTo());
2130 addGlobalValReplacement(Entry, BC);
2131 }
2132
John McCall7ec50432010-03-19 23:29:14 +00002133 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002134 if (D)
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002135 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk,
2136 IsForDefinition);
Reid Klecknerde864822017-03-21 16:57:30 +00002137 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2138 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
Reid Kleckneree4930b2017-05-02 22:07:37 +00002139 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Bill Wendling9a677922013-01-23 00:21:06 +00002140 }
Eli Friedmancc522d92009-11-09 05:07:37 +00002141
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002142 if (!DontDefer) {
2143 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2144 // each other bottoming out with the base dtor. Therefore we emit non-base
2145 // dtors on usage, even if there is no dtor definition in the TU.
2146 if (D && isa<CXXDestructorDecl>(D) &&
2147 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2148 GD.getDtorType()))
Sanjoy Das70a60512017-05-01 06:12:13 +00002149 addDeferredDeclToEmit(GD);
John McCall357d0f32010-12-15 04:00:32 +00002150
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002151 // This is the first use or definition of a mangled name. If there is a
2152 // deferred decl with this name, remember that we need to emit it at the end
2153 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002154 auto DDI = DeferredDecls.find(MangledName);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002155 if (DDI != DeferredDecls.end()) {
2156 // Move the potentially referenced deferred decl to the
2157 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2158 // don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002159 addDeferredDeclToEmit(DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002160 DeferredDecls.erase(DDI);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002161
2162 // Otherwise, there are cases we have to worry about where we're
2163 // using a declaration for which we must emit a definition but where
2164 // we might not find a top-level definition:
2165 // - member functions defined inline in their classes
2166 // - friend functions defined inline in some class
2167 // - special member functions with implicit definitions
2168 // If we ever change our AST traversal to walk into class methods,
2169 // this will be unnecessary.
2170 //
2171 // We also don't emit a definition for a function if it's going to be an
Richard Smith46bb5812014-08-01 01:56:39 +00002172 // entry in a vtable, unless it's already marked as used.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002173 } else if (getLangOpts().CPlusPlus && D) {
2174 // Look for a declaration that's lexically in a record.
Richard Smith46bb5812014-08-01 01:56:39 +00002175 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2176 FD = FD->getPreviousDecl()) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002177 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Richard Smith46bb5812014-08-01 01:56:39 +00002178 if (FD->doesThisDeclarationHaveABody()) {
Sanjoy Das70a60512017-05-01 06:12:13 +00002179 addDeferredDeclToEmit(GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002180 break;
2181 }
John McCall357d0f32010-12-15 04:00:32 +00002182 }
Richard Smith46bb5812014-08-01 01:56:39 +00002183 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002184 }
Chris Lattner45470942009-03-21 09:44:56 +00002185 }
Mike Stump11289f42009-09-09 15:08:12 +00002186
John McCalld06fb862010-04-28 00:00:30 +00002187 // Make sure the result is of the requested type.
2188 if (!IsIncompleteFunction) {
2189 assert(F->getType()->getElementType() == Ty);
2190 return F;
2191 }
2192
Chris Lattnera5f58b02011-07-09 17:41:47 +00002193 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00002194 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002195}
2196
Chris Lattnerd4808922009-03-22 21:03:39 +00002197/// GetAddrOfFunction - Return the address of the given function. If Ty is
2198/// non-null, then this function will use the specified type if it has to
2199/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00002200llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00002201 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002202 bool ForVTable,
Andrey Bokhankocab58582015-08-31 13:20:44 +00002203 bool DontDefer,
John McCalld195d4c2016-11-30 23:25:13 +00002204 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002205 // If there was no specific requested type, just convert it now.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002206 if (!Ty) {
2207 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2208 auto CanonTy = Context.getCanonicalType(FD->getType());
2209 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2210 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002211
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002212 StringRef MangledName = getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002213 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +00002214 /*IsThunk=*/false, llvm::AttributeList(),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002215 IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002216}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002217
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002218static const FunctionDecl *
2219GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2220 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2221 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2222
2223 IdentifierInfo &CII = C.Idents.get(Name);
2224 for (const auto &Result : DC->lookup(&CII))
2225 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2226 return FD;
2227
2228 if (!C.getLangOpts().CPlusPlus)
2229 return nullptr;
2230
2231 // Demangle the premangled name from getTerminateFn()
2232 IdentifierInfo &CXXII =
2233 (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2234 ? C.Idents.get("terminate")
2235 : C.Idents.get(Name);
2236
2237 for (const auto &N : {"__cxxabiv1", "std"}) {
2238 IdentifierInfo &NS = C.Idents.get(N);
2239 for (const auto &Result : DC->lookup(&NS)) {
2240 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2241 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2242 for (const auto &Result : LSD->lookup(&NS))
2243 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2244 break;
2245
2246 if (ND)
2247 for (const auto &Result : ND->lookup(&CXXII))
2248 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2249 return FD;
2250 }
2251 }
2252
2253 return nullptr;
2254}
2255
Chris Lattnerd4808922009-03-22 21:03:39 +00002256/// CreateRuntimeFunction - Create a new runtime function with the specified
2257/// type and name.
2258llvm::Constant *
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002259CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
Reid Klecknerde864822017-03-21 16:57:30 +00002260 llvm::AttributeList ExtraAttrs,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002261 bool Local) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002262 llvm::Constant *C =
2263 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002264 /*DontDefer=*/false, /*IsThunk=*/false,
2265 ExtraAttrs);
2266
2267 if (auto *F = dyn_cast<llvm::Function>(C)) {
2268 if (F->empty()) {
John McCall882987f2013-02-28 19:01:20 +00002269 F->setCallingConv(getRuntimeCC());
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002270
2271 if (!Local && getTriple().isOSBinFormatCOFF() &&
2272 !getCodeGenOpts().LTOVisibilityPublicStd) {
2273 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2274 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2275 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2276 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2277 }
2278 }
2279 }
2280 }
2281
John McCall882987f2013-02-28 19:01:20 +00002282 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00002283}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002284
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002285/// CreateBuiltinFunction - Create a new builtin function with the specified
2286/// type and name.
2287llvm::Constant *
Reid Klecknerde864822017-03-21 16:57:30 +00002288CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2289 llvm::AttributeList ExtraAttrs) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002290 llvm::Constant *C =
2291 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2292 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2293 if (auto *F = dyn_cast<llvm::Function>(C))
2294 if (F->empty())
2295 F->setCallingConv(getBuiltinCC());
2296 return C;
2297}
2298
Richard Smithe070fd22012-02-17 06:48:11 +00002299/// isTypeConstant - Determine whether an object of this type can be emitted
2300/// as a constant.
2301///
2302/// If ExcludeCtor is true, the duration when the object's constructor runs
2303/// will not be considered. The caller will need to verify that the object is
2304/// not written to during its construction.
2305bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2306 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00002307 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00002308
David Blaikiebbafb8a2012-03-11 07:00:24 +00002309 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00002310 if (const CXXRecordDecl *Record
2311 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2312 return ExcludeCtor && !Record->hasMutableFields() &&
2313 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00002314 }
Richard Smithe070fd22012-02-17 06:48:11 +00002315
Eli Friedmanb095e152009-12-11 21:23:03 +00002316 return true;
2317}
2318
Chris Lattnerd4808922009-03-22 21:03:39 +00002319/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2320/// create and return an llvm GlobalVariable with the specified type. If there
2321/// is something in the module with the specified name, return it potentially
2322/// bitcasted to the right type.
2323///
2324/// If D is non-null, it specifies a decl that correspond to this. This is used
2325/// to set the attributes on the global when it is first created.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002326///
2327/// If IsForDefinition is true, it is guranteed that an actual global with
2328/// type Ty will be returned, not conversion of a variable with the same
2329/// mangled name but some other type.
John McCall7ec50432010-03-19 23:29:14 +00002330llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002331CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00002332 llvm::PointerType *Ty,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002333 const VarDecl *D,
John McCalld195d4c2016-11-30 23:25:13 +00002334 ForDefinition_t IsForDefinition) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00002335 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002336 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00002337 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002338 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002339 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002340 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002341 }
2342
Hans Wennborg0a20f542014-08-29 00:16:06 +00002343 // Handle dropped DLL attributes.
2344 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2345 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2346
Chris Lattnerd4808922009-03-22 21:03:39 +00002347 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00002348 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00002349
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002350 // If there are two attempts to define the same mangled name, issue an
2351 // error.
2352 if (IsForDefinition && !Entry->isDeclaration()) {
2353 GlobalDecl OtherGD;
2354 const VarDecl *OtherD;
2355
2356 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2357 // to make sure that we issue an error only once.
Artem Belevich2c323a02016-05-19 18:00:18 +00002358 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002359 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2360 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2361 OtherD->hasInit() &&
2362 DiagnosedConflictingDefinitions.insert(D).second) {
2363 getDiags().Report(D->getLocation(),
2364 diag::err_duplicate_mangled_name);
2365 getDiags().Report(OtherGD.getDecl()->getLocation(),
2366 diag::note_previous_definition);
2367 }
2368 }
2369
Chris Lattner3bfce182009-03-21 08:03:33 +00002370 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00002371 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2372 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2373
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002374 // (If global is requested for a definition, we always need to create a new
2375 // global, not just return a bitcast.)
2376 if (!IsForDefinition)
2377 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00002378 }
Mike Stump11289f42009-09-09 15:08:12 +00002379
Yaxun Liucbf647c2017-07-08 13:24:52 +00002380 auto AddrSpace = GetGlobalVarAddressSpace(D);
2381 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2382
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002383 auto *GV = new llvm::GlobalVariable(
2384 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002385 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Yaxun Liucbf647c2017-07-08 13:24:52 +00002386 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00002387
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002388 // If we already created a global with the same mangled name (but different
2389 // type) before, take its name and remove it from its parent.
2390 if (Entry) {
2391 GV->takeName(Entry);
2392
2393 if (!Entry->use_empty()) {
2394 llvm::Constant *NewPtrForOldDecl =
2395 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2396 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2397 }
2398
2399 Entry->eraseFromParent();
2400 }
2401
Chris Lattner45470942009-03-21 09:44:56 +00002402 // This is the first use or definition of a mangled name. If there is a
2403 // deferred decl with this name, remember that we need to emit it at the end
2404 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002405 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00002406 if (DDI != DeferredDecls.end()) {
2407 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2408 // list, and remove it from DeferredDecls (since we don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002409 addDeferredDeclToEmit(DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00002410 DeferredDecls.erase(DDI);
2411 }
Mike Stump11289f42009-09-09 15:08:12 +00002412
Chris Lattner3bfce182009-03-21 08:03:33 +00002413 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00002414 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00002415 // FIXME: This code is overly simple and should be merged with other global
2416 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00002417 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00002418
Ulrich Weigand46084382015-04-21 17:27:59 +00002419 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2420
David Majnemerf6acb762014-04-25 17:07:16 +00002421 setLinkageAndVisibilityForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00002422
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002423 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00002424 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00002425 CXXThreadLocals.push_back(D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +00002426 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002427 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00002428
2429 // If required by the ABI, treat declarations of static data members with
2430 // inline initializers as definitions.
Hans Wennborg56fc62b2014-07-17 20:25:23 +00002431 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Hans Wennborgfeedf852013-11-21 00:15:56 +00002432 EmitGlobalVarDefinition(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +00002433 }
Robert Lyttonf80d6882014-05-02 09:33:30 +00002434
Erich Keane99fdfb62017-09-26 23:42:34 +00002435 // Emit section information for extern variables.
2436 if (D->hasExternalStorage()) {
2437 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
2438 GV->setSection(SA->getName());
2439 }
2440
Robert Lyttonf80d6882014-05-02 09:33:30 +00002441 // Handle XCore specific ABI requirements.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00002442 if (getTriple().getArch() == llvm::Triple::xcore &&
Robert Lyttonf80d6882014-05-02 09:33:30 +00002443 D->getLanguageLinkage() == CLanguageLinkage &&
2444 D->getType().isConstant(Context) &&
2445 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2446 GV->setSection(".cp.rodata");
Mehdi Amini7cb1b302017-09-05 03:58:35 +00002447
2448 // Check if we a have a const declaration with an initializer, we may be
2449 // able to emit it as available_externally to expose it's value to the
2450 // optimizer.
2451 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
2452 D->getType().isConstQualified() && !GV->hasInitializer() &&
2453 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
2454 const auto *Record =
2455 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
2456 bool HasMutableFields = Record && Record->hasMutableFields();
2457 if (!HasMutableFields) {
2458 const VarDecl *InitDecl;
2459 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2460 if (InitExpr) {
2461 ConstantEmitter emitter(*this);
2462 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
2463 if (Init) {
2464 auto *InitType = Init->getType();
2465 if (GV->getType()->getElementType() != InitType) {
2466 // The type of the initializer does not match the definition.
2467 // This happens when an initializer has a different type from
2468 // the type of the global (because of padding at the end of a
2469 // structure for instance).
2470 GV->setName(StringRef());
2471 // Make a new global with the correct type, this is now guaranteed
2472 // to work.
2473 auto *NewGV = cast<llvm::GlobalVariable>(
2474 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
2475
2476 // Erase the old global, since it is no longer used.
2477 cast<llvm::GlobalValue>(GV)->eraseFromParent();
2478 GV = NewGV;
2479 } else {
2480 GV->setInitializer(Init);
2481 GV->setConstant(true);
2482 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
2483 }
2484 emitter.finalize(GV);
2485 }
2486 }
2487 }
2488 }
Chris Lattnerd4808922009-03-22 21:03:39 +00002489 }
Mike Stump11289f42009-09-09 15:08:12 +00002490
Yaxun Liucbf647c2017-07-08 13:24:52 +00002491 auto ExpectedAS =
2492 D ? D->getType().getAddressSpace()
Yaxun Liu7bce6422017-07-08 19:13:41 +00002493 : static_cast<unsigned>(LangOpts.OpenCL ? LangAS::opencl_global
2494 : LangAS::Default);
Benjamin Kramer6fbfdec2017-07-08 14:14:57 +00002495 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
2496 Ty->getPointerAddressSpace());
Yaxun Liucbf647c2017-07-08 13:24:52 +00002497 if (AddrSpace != ExpectedAS)
2498 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
2499 ExpectedAS, Ty);
Matt Arsenault00e65b22013-11-15 02:19:52 +00002500
2501 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002502}
2503
Andrey Bokhankocab58582015-08-31 13:20:44 +00002504llvm::Constant *
2505CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
John McCalld195d4c2016-11-30 23:25:13 +00002506 ForDefinition_t IsForDefinition) {
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002507 const Decl *D = GD.getDecl();
2508 if (isa<CXXConstructorDecl>(D))
2509 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002510 getFromCtorType(GD.getCtorType()),
2511 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2512 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002513 else if (isa<CXXDestructorDecl>(D))
2514 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002515 getFromDtorType(GD.getDtorType()),
2516 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2517 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002518 else if (isa<CXXMethodDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00002519 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002520 cast<CXXMethodDecl>(D));
Andrey Bokhankocab58582015-08-31 13:20:44 +00002521 auto Ty = getTypes().GetFunctionType(*FInfo);
2522 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2523 IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002524 } else if (isa<FunctionDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00002525 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2526 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2527 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2528 IsForDefinition);
2529 } else
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002530 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002531 IsForDefinition);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002532}
Chris Lattnerd4808922009-03-22 21:03:39 +00002533
Anders Carlssonda80af32011-01-29 18:20:20 +00002534llvm::GlobalVariable *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002535CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00002536 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00002537 llvm::GlobalValue::LinkageTypes Linkage) {
2538 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00002539 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00002540
Anders Carlssonda80af32011-01-29 18:20:20 +00002541 if (GV) {
2542 // Check if the variable has the right type.
2543 if (GV->getType()->getElementType() == Ty)
2544 return GV;
2545
2546 // Because C++ name mangling, the only way we can end up with an already
2547 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00002548 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00002549 OldGV = GV;
2550 }
2551
2552 // Create a new variable.
2553 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00002554 Linkage, nullptr, Name);
2555
Anders Carlssonda80af32011-01-29 18:20:20 +00002556 if (OldGV) {
2557 // Replace occurrences of the old variable if needed.
2558 GV->takeName(OldGV);
2559
2560 if (!OldGV->use_empty()) {
2561 llvm::Constant *NewPtrForOldDecl =
2562 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2563 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2564 }
2565
2566 OldGV->eraseFromParent();
2567 }
Rafael Espindolacb92c192015-01-15 23:18:01 +00002568
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002569 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2570 !GV->hasAvailableExternallyLinkage())
2571 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00002572
Anders Carlssonda80af32011-01-29 18:20:20 +00002573 return GV;
2574}
2575
Chris Lattnerd4808922009-03-22 21:03:39 +00002576/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2577/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00002578/// then it will be created with the specified type instead of whatever the
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002579/// normal requested type would be. If IsForDefinition is true, it is guranteed
2580/// that an actual global with type Ty will be returned, not conversion of a
2581/// variable with the same mangled name but some other type.
Chris Lattnerd4808922009-03-22 21:03:39 +00002582llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002583 llvm::Type *Ty,
John McCalld195d4c2016-11-30 23:25:13 +00002584 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002585 assert(D->hasGlobalStorage() && "Not a global variable");
2586 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00002587 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00002588 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00002589
Chris Lattner2192fe52011-07-18 04:24:23 +00002590 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00002591 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00002592
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002593 StringRef MangledName = getMangledName(D);
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002594 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002595}
2596
2597/// CreateRuntimeVariable - Create a new runtime global variable with the
2598/// specified type and name.
2599llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00002600CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002601 StringRef Name) {
Rafael Espindolab73c9732014-05-22 23:33:27 +00002602 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
Chris Lattnerd4808922009-03-22 21:03:39 +00002603}
2604
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002605void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2606 assert(!D->getInit() && "Cannot emit definite definitions here!");
2607
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002608 StringRef MangledName = getMangledName(D);
2609 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2610
2611 // We already have a definition, not declaration, with the same mangled name.
2612 // Emitting of declaration is not required (and actually overwrites emitted
2613 // definition).
2614 if (GV && !GV->isDeclaration())
2615 return;
2616
2617 // If we have not seen a reference to this variable yet, place it into the
2618 // deferred declarations table to be emitted if needed later.
2619 if (!MustBeEmitted(D) && !GV) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002620 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002621 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00002622 }
2623
2624 // The tentative definition is the only definition.
Reid Kleckner953fe032015-12-05 01:52:14 +00002625 EmitGlobalVarDefinition(D);
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002626}
2627
Chris Lattner2192fe52011-07-18 04:24:23 +00002628CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00002629 return Context.toCharUnitsFromBits(
2630 getDataLayout().getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00002631}
2632
Yaxun Liucbf647c2017-07-08 13:24:52 +00002633unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
2634 unsigned AddrSpace;
2635 if (LangOpts.OpenCL) {
Yaxun Liu7bce6422017-07-08 19:13:41 +00002636 AddrSpace = D ? D->getType().getAddressSpace()
2637 : static_cast<unsigned>(LangAS::opencl_global);
Yaxun Liucbf647c2017-07-08 13:24:52 +00002638 assert(AddrSpace == LangAS::opencl_global ||
2639 AddrSpace == LangAS::opencl_constant ||
2640 AddrSpace == LangAS::opencl_local ||
2641 AddrSpace >= LangAS::FirstTargetAddressSpace);
2642 return AddrSpace;
Peter Collingbournef44bdf92012-05-20 21:08:35 +00002643 }
2644
Yaxun Liucbf647c2017-07-08 13:24:52 +00002645 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2646 if (D && D->hasAttr<CUDAConstantAttr>())
2647 return LangAS::cuda_constant;
2648 else if (D && D->hasAttr<CUDASharedAttr>())
2649 return LangAS::cuda_shared;
2650 else
2651 return LangAS::cuda_device;
2652 }
2653
2654 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
Peter Collingbournef44bdf92012-05-20 21:08:35 +00002655}
2656
Richard Smithdf931ce2013-04-06 05:00:46 +00002657template<typename SomeDecl>
2658void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2659 llvm::GlobalValue *GV) {
2660 if (!getLangOpts().CPlusPlus)
2661 return;
2662
2663 // Must have 'used' attribute, or else inline assembly can't rely on
2664 // the name existing.
2665 if (!D->template hasAttr<UsedAttr>())
2666 return;
2667
2668 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00002669 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00002670 return;
2671
2672 // Must be in an extern "C" context. Entities declared directly within
2673 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00002674 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00002675 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00002676 return;
2677
2678 // OK, this is an internal linkage entity inside an extern "C" linkage
2679 // specification. Make a note of that so we can give it the "expected"
2680 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00002681 std::pair<StaticExternCMap::iterator, bool> R =
2682 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00002683
2684 // If we have multiple internal linkage entities with the same name
2685 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00002686 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00002687 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00002688}
2689
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002690static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2691 if (!CGM.supportsCOMDAT())
2692 return false;
2693
2694 if (D.hasAttr<SelectAnyAttr>())
2695 return true;
2696
2697 GVALinkage Linkage;
2698 if (auto *VD = dyn_cast<VarDecl>(&D))
2699 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2700 else
2701 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2702
2703 switch (Linkage) {
2704 case GVA_Internal:
2705 case GVA_AvailableExternally:
2706 case GVA_StrongExternal:
2707 return false;
2708 case GVA_DiscardableODR:
2709 case GVA_StrongODR:
2710 return true;
2711 }
2712 llvm_unreachable("No such linkage");
2713}
2714
Rafael Espindoladbee8a72015-01-15 21:36:08 +00002715void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2716 llvm::GlobalObject &GO) {
2717 if (!shouldBeInCOMDAT(*this, D))
2718 return;
2719 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2720}
2721
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002722/// Pass IsTentative as true if you want to create a tentative definition.
2723void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2724 bool IsTentative) {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002725 // OpenCL global variables of sampler type are translated to function calls,
2726 // therefore no need to be translated.
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002727 QualType ASTTy = D->getType();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002728 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
2729 return;
2730
2731 llvm::Constant *Init = nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00002732 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2733 bool NeedsGlobalCtor = false;
2734 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00002735
Richard Smithdafff942012-01-14 04:30:29 +00002736 const VarDecl *InitDecl;
2737 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00002738
John McCallde0fe072017-08-15 21:42:52 +00002739 Optional<ConstantEmitter> emitter;
2740
Artem Belevich97c01c32016-02-02 22:29:48 +00002741 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2742 // as part of their declaration." Sema has already checked for
2743 // error cases, so we just need to set Init to UndefValue.
2744 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2745 D->hasAttr<CUDASharedAttr>())
Jingyue Wu284ebe22015-08-22 05:49:28 +00002746 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
Artem Belevich97c01c32016-02-02 22:29:48 +00002747 else if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00002748 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002749 // implicitly initialized with { 0 }.
2750 //
2751 // Note that tentative definitions are only emitted at the end of
2752 // a translation unit, so they should never have incomplete
2753 // type. In addition, EmitTentativeDefinition makes sure that we
2754 // never attempt to emit a tentative definition if a real one
2755 // exists. A use may still exists, however, so we still may need
2756 // to do a RAUW.
2757 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00002758 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002759 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00002760 initializedGlobalDecl = GlobalDecl(D);
John McCallde0fe072017-08-15 21:42:52 +00002761 emitter.emplace(*this);
2762 Init = emitter->tryEmitForInitializer(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00002763
Fariborz Jahanian63628032012-06-26 16:06:38 +00002764 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00002765 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00002766 if (D->getType()->isReferenceType())
2767 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00002768
David Blaikiebbafb8a2012-03-11 07:00:24 +00002769 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00002770 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00002771 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00002772 } else {
2773 ErrorUnsupported(D, "static initializer");
2774 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2775 }
John McCall70013b62010-07-15 23:40:35 +00002776 } else {
2777 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00002778 // initializer position (just in case this entry was delayed) if we
2779 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002780 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00002781 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00002782 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002783 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002784
Chris Lattner2192fe52011-07-18 04:24:23 +00002785 llvm::Type* InitType = Init->getType();
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002786 llvm::Constant *Entry =
John McCalld195d4c2016-11-30 23:25:13 +00002787 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
Mike Stump11289f42009-09-09 15:08:12 +00002788
Chris Lattner149927c2009-03-21 09:16:30 +00002789 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002790 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00002791 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00002792 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2793 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00002794 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00002795 Entry = CE->getOperand(0);
2796 }
Mike Stump11289f42009-09-09 15:08:12 +00002797
Chris Lattner149927c2009-03-21 09:16:30 +00002798 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002799 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002800
Chris Lattner149927c2009-03-21 09:16:30 +00002801 // We have a definition after a declaration with the wrong type.
2802 // We must make a new GlobalVariable* and update everything that used OldGV
2803 // (a declaration or tentative definition) with the new GlobalVariable*
2804 // (which will be a definition).
2805 //
2806 // This happens if there is a prototype for a global (e.g.
2807 // "extern int x[];") and then a definition of a different type (e.g.
2808 // "int x[10];"). This also happens when an initializer has a different type
2809 // from the type of the global (this happens with unions).
Yaxun Liucbf647c2017-07-08 13:24:52 +00002810 if (!GV || GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00002811 GV->getType()->getAddressSpace() !=
Yaxun Liucbf647c2017-07-08 13:24:52 +00002812 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
Mike Stump11289f42009-09-09 15:08:12 +00002813
John McCall7ec50432010-03-19 23:29:14 +00002814 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002815 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00002816
Chris Lattner149927c2009-03-21 09:16:30 +00002817 // Make a new global with the correct type, this is now guaranteed to work.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002818 GV = cast<llvm::GlobalVariable>(
John McCalld195d4c2016-11-30 23:25:13 +00002819 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
Chris Lattnera85d68e2009-03-21 09:25:43 +00002820
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002821 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00002822 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00002823 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00002824 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002825
2826 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00002827 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00002828 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00002829
Richard Smithdf931ce2013-04-06 05:00:46 +00002830 MaybeHandleStaticInExternC(D, GV);
2831
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002832 if (D->hasAttr<AnnotateAttr>())
2833 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00002834
Artem Belevich42e19492016-03-02 18:28:50 +00002835 // Set the llvm linkage type as appropriate.
2836 llvm::GlobalValue::LinkageTypes Linkage =
2837 getLLVMLinkageVarDefinition(D, GV->isConstant());
2838
Jingyue Wu284ebe22015-08-22 05:49:28 +00002839 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2840 // the device. [...]"
2841 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2842 // __device__, declares a variable that: [...]
2843 // Is accessible from all the threads within the grid and from the host
2844 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2845 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
Artem Belevich42e19492016-03-02 18:28:50 +00002846 if (GV && LangOpts.CUDA) {
2847 if (LangOpts.CUDAIsDevice) {
2848 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2849 GV->setExternallyInitialized(true);
2850 } else {
2851 // Host-side shadows of external declarations of device-side
2852 // global variables become internal definitions. These have to
2853 // be internal in order to prevent name conflicts with global
2854 // host variables with the same name in a different TUs.
2855 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2856 Linkage = llvm::GlobalValue::InternalLinkage;
2857
2858 // Shadow variables and their properties must be registered
2859 // with CUDA runtime.
2860 unsigned Flags = 0;
2861 if (!D->hasDefinition())
2862 Flags |= CGCUDARuntime::ExternDeviceVar;
2863 if (D->hasAttr<CUDAConstantAttr>())
2864 Flags |= CGCUDARuntime::ConstantDeviceVar;
2865 getCUDARuntime().registerDeviceVar(*GV, Flags);
2866 } else if (D->hasAttr<CUDASharedAttr>())
2867 // __shared__ variables are odd. Shadows do get created, but
2868 // they are not registered with the CUDA runtime, so they
2869 // can't really be used to access their device-side
2870 // counterparts. It's not clear yet whether it's nvcc's bug or
2871 // a feature, but we've got to do the same for compatibility.
2872 Linkage = llvm::GlobalValue::InternalLinkage;
2873 }
Jingyue Wu284ebe22015-08-22 05:49:28 +00002874 }
John McCallde0fe072017-08-15 21:42:52 +00002875
Chris Lattnerd14bfa92007-07-13 05:13:43 +00002876 GV->setInitializer(Init);
John McCallde0fe072017-08-15 21:42:52 +00002877 if (emitter) emitter->finalize(GV);
Chris Lattnerf49573d2009-08-05 05:20:29 +00002878
2879 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00002880 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2881 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00002882
Hans Wennborg899ded92014-10-16 20:52:46 +00002883 // If it is in a read-only section, mark it 'constant'.
2884 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2885 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2886 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2887 GV->setConstant(true);
2888 }
2889
Ken Dyck160146e2010-01-27 17:10:57 +00002890 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00002891
David Majnemer35ab3282014-06-11 04:08:55 +00002892
Manman Ren68150262015-11-11 22:42:31 +00002893 // On Darwin, if the normal linkage of a C++ thread_local variable is
2894 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2895 // copies within a linkage unit; otherwise, the backing variable has
2896 // internal linkage and all accesses should just be calls to the
David Majnemer35ab3282014-06-11 04:08:55 +00002897 // Itanium-specified entry point, which has the normal linkage of the
Manman Ren68150262015-11-11 22:42:31 +00002898 // variable. This is to preserve the ability to change the implementation
2899 // behind the scenes.
David Majnemerbb525f7c2014-10-15 22:38:23 +00002900 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002901 Context.getTargetInfo().getTriple().isOSDarwin() &&
Manman Ren68150262015-11-11 22:42:31 +00002902 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2903 !llvm::GlobalVariable::isWeakLinkage(Linkage))
David Majnemerbb525f7c2014-10-15 22:38:23 +00002904 Linkage = llvm::GlobalValue::InternalLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002905
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002906 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00002907 if (D->hasAttr<DLLImportAttr>())
2908 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2909 else if (D->hasAttr<DLLExportAttr>())
2910 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00002911 else
2912 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00002913
Yaxun Liu402804b2016-12-15 08:09:08 +00002914 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
Chris Lattnerf49573d2009-08-05 05:20:29 +00002915 // common vars aren't constant even if declared const.
2916 GV->setConstant(false);
Yaxun Liu402804b2016-12-15 08:09:08 +00002917 // Tentative definition of global variables may be initialized with
2918 // non-zero null pointers. In this case they should have weak linkage
2919 // since common linkage must have zero initializer and must not have
2920 // explicit section therefore cannot have non-zero initial value.
2921 if (!GV->getInitializer()->isNullValue())
2922 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2923 }
Daniel Dunbard272cca2009-04-10 20:26:50 +00002924
Rafael Espindola502f65a2014-05-05 20:21:03 +00002925 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00002926
David Majnemerbb525f7c2014-10-15 22:38:23 +00002927 if (D->getTLSKind() && !GV->isThreadLocal()) {
2928 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00002929 CXXThreadLocals.push_back(D);
David Majnemerbb525f7c2014-10-15 22:38:23 +00002930 setTLSMode(GV, *D);
2931 }
2932
Rafael Espindoladbee8a72015-01-15 21:36:08 +00002933 maybeSetTrivialComdat(*D, *GV);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002934
John McCallcdf7ef52010-11-06 09:44:32 +00002935 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00002936 if (NeedsGlobalCtor || NeedsGlobalDtor)
2937 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00002938
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002939 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany28a26c82012-08-21 06:53:28 +00002940
Sanjiv Gupta158143a2008-06-05 08:59:10 +00002941 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00002942 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00002943 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00002944 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00002945}
Chris Lattner09153c02007-06-22 18:48:09 +00002946
David Majnemerc017d362014-08-05 00:01:13 +00002947static bool isVarDeclStrongDefinition(const ASTContext &Context,
Nico Weber608e7682015-04-15 23:04:24 +00002948 CodeGenModule &CGM, const VarDecl *D,
2949 bool NoCommon) {
David Majnemer9832a3d2014-04-10 16:53:16 +00002950 // Don't give variables common linkage if -fno-common was specified unless it
2951 // was overridden by a NoCommon attribute.
2952 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2953 return true;
2954
2955 // C11 6.9.2/2:
2956 // A declaration of an identifier for an object that has file scope without
2957 // an initializer, and without a storage-class specifier or with the
2958 // storage-class specifier static, constitutes a tentative definition.
2959 if (D->getInit() || D->hasExternalStorage())
2960 return true;
2961
2962 // A variable cannot be both common and exist in a section.
2963 if (D->hasAttr<SectionAttr>())
2964 return true;
2965
Javed Absar2a67c9e2017-06-05 10:11:57 +00002966 // A variable cannot be both common and exist in a section.
2967 // We dont try to determine which is the right section in the front-end.
2968 // If no specialized section name is applicable, it will resort to default.
2969 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
2970 D->hasAttr<PragmaClangDataSectionAttr>() ||
2971 D->hasAttr<PragmaClangRodataSectionAttr>())
2972 return true;
2973
David Majnemer9832a3d2014-04-10 16:53:16 +00002974 // Thread local vars aren't considered common linkage.
2975 if (D->getTLSKind())
2976 return true;
2977
2978 // Tentative definitions marked with WeakImportAttr are true definitions.
2979 if (D->hasAttr<WeakImportAttr>())
2980 return true;
2981
Nico Weber608e7682015-04-15 23:04:24 +00002982 // A variable cannot be both common and exist in a comdat.
2983 if (shouldBeInCOMDAT(CGM, *D))
2984 return true;
2985
Sanjay Patel2f9303a2016-06-30 21:02:40 +00002986 // Declarations with a required alignment do not have common linkage in MSVC
David Majnemerc017d362014-08-05 00:01:13 +00002987 // mode.
David Majnemer3f021502015-10-08 04:53:31 +00002988 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemere1a0b2e2015-02-03 08:49:32 +00002989 if (D->hasAttr<AlignedAttr>())
2990 return true;
2991 QualType VarType = D->getType();
2992 if (Context.isAlignmentRequired(VarType))
2993 return true;
2994
2995 if (const auto *RT = VarType->getAs<RecordType>()) {
2996 const RecordDecl *RD = RT->getDecl();
2997 for (const FieldDecl *FD : RD->fields()) {
2998 if (FD->isBitField())
2999 continue;
3000 if (FD->hasAttr<AlignedAttr>())
3001 return true;
3002 if (Context.isAlignmentRequired(FD->getType()))
3003 return true;
3004 }
3005 }
3006 }
David Majnemerc017d362014-08-05 00:01:13 +00003007
David Majnemer9832a3d2014-04-10 16:53:16 +00003008 return false;
3009}
3010
Hans Wennborg1a3a0742014-05-14 19:54:53 +00003011llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00003012 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003013 if (Linkage == GVA_Internal)
3014 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003015
3016 if (D->hasAttr<WeakAttr>()) {
3017 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003018 return llvm::GlobalVariable::WeakODRLinkage;
3019 else
3020 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003021 }
3022
3023 // We are guaranteed to have a strong definition somewhere else,
3024 // so we can use available_externally linkage.
3025 if (Linkage == GVA_AvailableExternally)
David Blaikie9ffe5a32017-01-30 05:00:26 +00003026 return llvm::GlobalValue::AvailableExternallyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003027
David Majnemer27d69db2014-04-28 22:17:59 +00003028 // Note that Apple's kernel linker doesn't support symbol
3029 // coalescing, so we need to avoid linkonce and weak linkages there.
3030 // Normally, this means we just map to internal, but for explicit
3031 // instantiations we'll map to external.
3032
3033 // In C++, the compiler has to emit a definition in every translation unit
3034 // that references the function. We should use linkonce_odr because
3035 // a) if all references in this translation unit are optimized away, we
3036 // don't need to codegen it. b) if the function persists, it needs to be
3037 // merged with other definitions. c) C++ has the ODR, so we know the
3038 // definition is dependable.
3039 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00003040 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00003041 : llvm::Function::InternalLinkage;
3042
3043 // An explicit instantiation of a template has weak linkage, since
3044 // explicit instantiations can occur in multiple translation units
3045 // and must all be equivalent. However, we are not allowed to
3046 // throw away these explicit instantiations.
Justin Lebar27ee1302016-06-30 18:41:33 +00003047 //
3048 // We don't currently support CUDA device code spread out across multiple TUs,
3049 // so say that CUDA templates are either external (for kernels) or internal.
3050 // This lets llvm perform aggressive inter-procedural optimizations.
3051 if (Linkage == GVA_StrongODR) {
3052 if (Context.getLangOpts().AppleKext)
3053 return llvm::Function::ExternalLinkage;
3054 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3055 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3056 : llvm::Function::InternalLinkage;
3057 return llvm::Function::WeakODRLinkage;
3058 }
David Majnemer27d69db2014-04-28 22:17:59 +00003059
David Majnemer27d69db2014-04-28 22:17:59 +00003060 // C++ doesn't have tentative definitions and thus cannot have common
3061 // linkage.
3062 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Nico Weber608e7682015-04-15 23:04:24 +00003063 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
David Majnemerc017d362014-08-05 00:01:13 +00003064 CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00003065 return llvm::GlobalVariable::CommonLinkage;
3066
David Majnemer27d69db2014-04-28 22:17:59 +00003067 // selectany symbols are externally visible, so use weak instead of
3068 // linkonce. MSVC optimizes away references to const selectany globals, so
3069 // all definitions should be the same and ODR linkage should be used.
3070 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3071 if (D->hasAttr<SelectAnyAttr>())
3072 return llvm::GlobalVariable::WeakODRLinkage;
3073
3074 // Otherwise, we have strong external linkage.
3075 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003076 return llvm::GlobalVariable::ExternalLinkage;
3077}
3078
David Majnemer27d69db2014-04-28 22:17:59 +00003079llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3080 const VarDecl *VD, bool IsConstant) {
3081 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00003082 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00003083}
3084
John McCall49954ca2012-12-12 22:21:47 +00003085/// Replace the uses of a function that was declared with a non-proto type.
3086/// We want to silently drop extra arguments from call sites
3087static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3088 llvm::Function *newFn) {
3089 // Fast path.
3090 if (old->use_empty()) return;
3091
3092 llvm::Type *newRetTy = newFn->getReturnType();
3093 SmallVector<llvm::Value*, 4> newArgs;
David Majnemer0b17d442015-12-15 21:27:59 +00003094 SmallVector<llvm::OperandBundleDef, 1> newBundles;
John McCall49954ca2012-12-12 22:21:47 +00003095
3096 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3097 ui != ue; ) {
3098 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003099 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00003100
3101 // Recognize and replace uses of bitcasts. Most calls to
3102 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003103 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00003104 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3105 replaceUsesOfNonProtoConstant(bitcast, newFn);
3106 continue;
3107 }
3108
3109 // Recognize calls to the function.
3110 llvm::CallSite callSite(user);
3111 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003112 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00003113
3114 // If the return types don't match exactly, then we can't
3115 // transform this call unless it's dead.
3116 if (callSite->getType() != newRetTy && !callSite->use_empty())
3117 continue;
3118
3119 // Get the call site's attribute list.
Reid Kleckner7f720332017-04-13 00:58:09 +00003120 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
Reid Klecknerde864822017-03-21 16:57:30 +00003121 llvm::AttributeList oldAttrs = callSite.getAttributes();
John McCall49954ca2012-12-12 22:21:47 +00003122
John McCall49954ca2012-12-12 22:21:47 +00003123 // If the function was passed too few arguments, don't transform.
3124 unsigned newNumArgs = newFn->arg_size();
3125 if (callSite.arg_size() < newNumArgs) continue;
3126
3127 // If extra arguments were passed, we silently drop them.
3128 // If any of the types mismatch, we don't transform.
3129 unsigned argNo = 0;
3130 bool dontTransform = false;
Reid Kleckner7f720332017-04-13 00:58:09 +00003131 for (llvm::Argument &A : newFn->args()) {
3132 if (callSite.getArgument(argNo)->getType() != A.getType()) {
John McCall49954ca2012-12-12 22:21:47 +00003133 dontTransform = true;
3134 break;
3135 }
3136
3137 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00003138 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
Reid Kleckner7f720332017-04-13 00:58:09 +00003139 argNo++;
John McCall49954ca2012-12-12 22:21:47 +00003140 }
3141 if (dontTransform)
3142 continue;
3143
John McCall49954ca2012-12-12 22:21:47 +00003144 // Okay, we can transform this. Create the new call instruction and copy
3145 // over the required information.
3146 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3147
David Majnemer0b17d442015-12-15 21:27:59 +00003148 // Copy over any operand bundles.
3149 callSite.getOperandBundlesAsDefs(newBundles);
3150
John McCall49954ca2012-12-12 22:21:47 +00003151 llvm::CallSite newCall;
3152 if (callSite.isCall()) {
David Majnemer0b17d442015-12-15 21:27:59 +00003153 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003154 callSite.getInstruction());
3155 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003156 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCall49954ca2012-12-12 22:21:47 +00003157 newCall = llvm::InvokeInst::Create(newFn,
3158 oldInvoke->getNormalDest(),
3159 oldInvoke->getUnwindDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003160 newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003161 callSite.getInstruction());
3162 }
3163 newArgs.clear(); // for the next iteration
3164
3165 if (!newCall->getType()->isVoidTy())
3166 newCall->takeName(callSite.getInstruction());
Reid Kleckner7f720332017-04-13 00:58:09 +00003167 newCall.setAttributes(llvm::AttributeList::get(
3168 newFn->getContext(), oldAttrs.getFnAttributes(),
3169 oldAttrs.getRetAttributes(), newArgAttrs));
John McCall49954ca2012-12-12 22:21:47 +00003170 newCall.setCallingConv(callSite.getCallingConv());
3171
3172 // Finally, remove the old call, replacing any uses with the new one.
3173 if (!callSite->use_empty())
3174 callSite->replaceAllUsesWith(newCall.getInstruction());
3175
3176 // Copy debug location attached to CI.
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00003177 if (callSite->getDebugLoc())
John McCall49954ca2012-12-12 22:21:47 +00003178 newCall->setDebugLoc(callSite->getDebugLoc());
David Majnemer0b17d442015-12-15 21:27:59 +00003179
John McCall49954ca2012-12-12 22:21:47 +00003180 callSite->eraseFromParent();
3181 }
3182}
3183
Chris Lattner36797ab2009-05-05 06:16:31 +00003184/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3185/// implement a function with no prototype, e.g. "int foo() {}". If there are
3186/// existing call uses of the old function in the module, this adjusts them to
3187/// call the new function directly.
3188///
3189/// This is not just a cleanup: the always_inline pass requires direct calls to
3190/// functions to be able to inline them. If there is a bitcast in the way, it
3191/// won't inline them. Instcombine normally deletes these calls, but it isn't
3192/// run at -O0.
3193static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3194 llvm::Function *NewFn) {
3195 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00003196 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00003197
John McCall49954ca2012-12-12 22:21:47 +00003198 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00003199}
3200
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003201void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
David Majnemer60e5bdc2016-07-11 04:28:21 +00003202 auto DK = VD->isThisDeclarationADefinition();
3203 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3204 return;
3205
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003206 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3207 // If we have a definition, this might be a deferred decl. If the
3208 // instantiation is explicit, make sure we emit it at the end.
3209 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3210 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003211
3212 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00003213}
Daniel Dunbar9c426522008-07-29 23:18:29 +00003214
Rafael Espindolacd7743b2013-12-09 16:01:03 +00003215void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3216 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003217 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00003218
John McCall46288ef2011-03-09 08:12:35 +00003219 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00003220 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3221 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00003222
Chris Lattnereb7466d2009-05-12 20:58:15 +00003223 // Get or create the prototype for the function.
Andrey Bokhankocab58582015-08-31 13:20:44 +00003224 if (!GV || (GV->getType()->getElementType() != Ty))
3225 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3226 /*DontDefer=*/true,
John McCalld195d4c2016-11-30 23:25:13 +00003227 ForDefinition));
Mike Stump11289f42009-09-09 15:08:12 +00003228
Andrey Bokhankocab58582015-08-31 13:20:44 +00003229 // Already emitted.
3230 if (!GV->isDeclaration())
Renato Golinc640ff62015-04-15 08:44:40 +00003231 return;
Mike Stump11289f42009-09-09 15:08:12 +00003232
John McCall8e7cb6d2010-11-02 21:04:24 +00003233 // We need to set linkage and visibility on the function before
3234 // generating code for it because various parts of IR generation
3235 // want to propagate this information down (e.g. to local static
3236 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003237 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00003238 setFunctionLinkage(GD, Fn);
Hans Wennborgbb4f9622015-05-28 17:44:56 +00003239 setFunctionDLLStorageClass(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003240
Rafael Espindolae033c8c2014-05-08 15:26:12 +00003241 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00003242 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00003243
Richard Smithdf931ce2013-04-06 05:00:46 +00003244 MaybeHandleStaticInExternC(D, Fn);
3245
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003246 maybeSetTrivialComdat(*D, *Fn);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003247
John McCalla738c252011-03-09 04:27:21 +00003248 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00003249
Rafael Espindolae033c8c2014-05-08 15:26:12 +00003250 setFunctionDefinitionAttributes(D, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00003251 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00003252
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003253 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003254 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003255 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003256 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003257 if (D->hasAttr<AnnotateAttr>())
3258 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003259}
3260
John McCall7ec50432010-03-19 23:29:14 +00003261void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003262 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003263 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00003264 assert(AA && "Not an alias?");
3265
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003266 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00003267
Hal Finkel0e2b9752015-09-04 21:49:21 +00003268 if (AA->getAliasee() == MangledName) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003269 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Hal Finkel0e2b9752015-09-04 21:49:21 +00003270 return;
3271 }
3272
John McCall7ec50432010-03-19 23:29:14 +00003273 // If there is a definition in the module, then it wins over the alias.
3274 // This is dubious, but allow it to be safe. Just ignore the alias.
3275 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3276 if (Entry && !Entry->isDeclaration())
3277 return;
3278
Rafael Espindola208b5c02013-10-22 19:26:13 +00003279 Aliases.push_back(GD);
3280
Chris Lattner2192fe52011-07-18 04:24:23 +00003281 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00003282
3283 // Create a reference to the named value. This ensures that it is emitted
3284 // if a deferred decl.
3285 llvm::Constant *Aliasee;
3286 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00003287 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00003288 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00003289 else
John McCall7ec50432010-03-19 23:29:14 +00003290 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00003291 llvm::PointerType::getUnqual(DeclTy),
David Majnemerbb525f7c2014-10-15 22:38:23 +00003292 /*D=*/nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00003293
3294 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00003295 auto *GA = llvm::GlobalAlias::create(
David Blaikie2a791d72015-09-14 18:38:22 +00003296 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00003297
Chris Lattner54041692009-03-22 21:47:11 +00003298 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00003299 if (GA->getAliasee() == Entry) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003300 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Rafael Espindolab2633b92014-05-16 19:35:48 +00003301 return;
3302 }
3303
John McCall7ec50432010-03-19 23:29:14 +00003304 assert(Entry->isDeclaration());
3305
Chris Lattner54041692009-03-22 21:47:11 +00003306 // If there is a declaration in the module, then we had an extern followed
3307 // by the alias, as in:
3308 // extern int test6();
3309 // ...
3310 // int test6() __attribute__((alias("test7")));
3311 //
3312 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00003313 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003314
Owen Andersonade90fd2009-07-29 18:54:39 +00003315 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00003316 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00003317 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00003318 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00003319 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00003320 }
Mike Stump11289f42009-09-09 15:08:12 +00003321
Daniel Dunbar38932572009-04-14 08:05:55 +00003322 // Set attributes which are particular to an alias; this is a
3323 // specialization of the attributes which may be set on a global
3324 // variable/function.
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00003325 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3326 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00003327 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3328 }
3329
David Majnemerbb525f7c2014-10-15 22:38:23 +00003330 if (const auto *VD = dyn_cast<VarDecl>(D))
3331 if (VD->getTLSKind())
3332 setTLSMode(GA, *VD);
3333
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00003334 setAliasAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00003335}
3336
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003337void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3338 const auto *D = cast<ValueDecl>(GD.getDecl());
3339 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3340 assert(IFA && "Not an ifunc?");
3341
3342 StringRef MangledName = getMangledName(GD);
3343
3344 if (IFA->getResolver() == MangledName) {
3345 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3346 return;
3347 }
3348
3349 // Report an error if some definition overrides ifunc.
3350 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3351 if (Entry && !Entry->isDeclaration()) {
3352 GlobalDecl OtherGD;
3353 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3354 DiagnosedConflictingDefinitions.insert(GD).second) {
3355 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3356 Diags.Report(OtherGD.getDecl()->getLocation(),
3357 diag::note_previous_definition);
3358 }
3359 return;
3360 }
3361
3362 Aliases.push_back(GD);
3363
3364 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3365 llvm::Constant *Resolver =
3366 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3367 /*ForVTable=*/false);
3368 llvm::GlobalIFunc *GIF =
3369 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3370 "", Resolver, &getModule());
3371 if (Entry) {
3372 if (GIF->getResolver() == Entry) {
3373 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3374 return;
3375 }
3376 assert(Entry->isDeclaration());
3377
3378 // If there is a declaration in the module, then we had an extern followed
3379 // by the ifunc, as in:
3380 // extern int test();
3381 // ...
3382 // int test() __attribute__((ifunc("resolver")));
3383 //
3384 // Remove it and replace uses of it with the ifunc.
3385 GIF->takeName(Entry);
3386
3387 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3388 Entry->getType()));
3389 Entry->eraseFromParent();
3390 } else
3391 GIF->setName(MangledName);
3392
3393 SetCommonAttributes(D, GIF);
3394}
3395
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003396llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00003397 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00003398 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003399 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00003400}
Chris Lattner1eec6602007-08-31 04:31:45 +00003401
David Blaikie2e804282015-04-05 22:47:07 +00003402static llvm::StringMapEntry<llvm::GlobalVariable *> &
3403GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3404 const StringLiteral *Literal, bool TargetIsLSB,
3405 bool &IsUTF16, unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003406 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003407 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00003408
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00003409 // Check for simple case.
3410 if (!Literal->containsNonAsciiOrNull()) {
3411 StringLength = NumBytes;
David Blaikie13156b62014-11-19 03:06:06 +00003412 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00003413 }
3414
Bill Wendling82b87f12012-03-30 00:26:17 +00003415 // Otherwise, convert the UTF8 literals into a string of shorts.
3416 IsUTF16 = true;
3417
Justin Lebar90910552016-09-30 00:38:45 +00003418 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3419 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3420 llvm::UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00003421
Justin Lebar90910552016-09-30 00:38:45 +00003422 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3423 ToPtr + NumBytes, llvm::strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00003424
Daniel Dunbar91ade142009-07-23 23:41:22 +00003425 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00003426 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00003427
Bill Wendling82b87f12012-03-30 00:26:17 +00003428 // Add an explicit null.
3429 *ToPtr = 0;
David Blaikie13156b62014-11-19 03:06:06 +00003430 return *Map.insert(std::make_pair(
3431 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3432 (StringLength + 1) * 2),
3433 nullptr)).first;
Daniel Dunbar64509b22009-07-23 22:52:48 +00003434}
3435
John McCall7f416cc2015-09-08 08:05:57 +00003436ConstantAddress
Daniel Dunbar64509b22009-07-23 22:52:48 +00003437CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3438 unsigned StringLength = 0;
3439 bool isUTF16 = false;
David Blaikie2e804282015-04-05 22:47:07 +00003440 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3441 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3442 getDataLayout().isLittleEndian(), isUTF16,
3443 StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00003444
David Blaikie13156b62014-11-19 03:06:06 +00003445 if (auto *C = Entry.second)
John McCall7f416cc2015-09-08 08:05:57 +00003446 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Mike Stump11289f42009-09-09 15:08:12 +00003447
Chris Lattnerece04092012-02-07 00:39:47 +00003448 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00003449 llvm::Constant *Zeros[] = { Zero, Zero };
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003450
Chris Lattneraa64ca22009-07-16 16:48:25 +00003451 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00003452 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003453 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00003454 Ty = llvm::ArrayType::get(Ty, 0);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003455 llvm::Constant *GV =
3456 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003457
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003458 if (getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003459 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3460 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3461 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3462 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3463
3464 const VarDecl *VD = nullptr;
3465 for (const auto &Result : DC->lookup(&II))
3466 if ((VD = dyn_cast<VarDecl>(Result)))
3467 break;
3468
3469 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3470 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3471 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3472 } else {
3473 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3474 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3475 }
3476 }
3477
Daniel Dunbard644ad62008-08-23 18:37:06 +00003478 // Decay array -> ptr
Saleem Abdulrasool4fab7452016-09-11 01:25:15 +00003479 CFConstantStringClassRef =
3480 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003481 }
Mike Stump11289f42009-09-09 15:08:12 +00003482
Anders Carlssonc2480a52008-11-15 18:54:24 +00003483 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00003484
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003485 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00003486
John McCall23c9dc62016-11-28 22:18:27 +00003487 ConstantInitBuilder Builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003488 auto Fields = Builder.beginStruct(STy);
Douglas Gregor91f84212008-12-11 16:49:14 +00003489
Anders Carlssonb04ea612007-08-21 00:21:21 +00003490 // Class pointer.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003491 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
Mike Stump11289f42009-09-09 15:08:12 +00003492
Anders Carlssonb04ea612007-08-21 00:21:21 +00003493 // Flags.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003494 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
Anders Carlsson157c3212009-08-16 05:55:31 +00003495
Anders Carlssonb04ea612007-08-21 00:21:21 +00003496 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00003497 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00003498 if (isUTF16) {
Craig Topperc005cc02015-09-27 03:44:08 +00003499 auto Arr = llvm::makeArrayRef(
David Blaikie13156b62014-11-19 03:06:06 +00003500 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3501 Entry.first().size() / 2);
Bill Wendling82b87f12012-03-30 00:26:17 +00003502 C = llvm::ConstantDataArray::get(VMContext, Arr);
3503 } else {
David Blaikie13156b62014-11-19 03:06:06 +00003504 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling82b87f12012-03-30 00:26:17 +00003505 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00003506
Bill Wendling86131f22012-01-10 08:46:39 +00003507 // Note: -fwritable-strings doesn't make the backing store strings of
3508 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003509 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00003510 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3511 llvm::GlobalValue::PrivateLinkage, C, ".str");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003512 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigandfa806422013-05-06 16:23:57 +00003513 // Don't enforce the target's minimum global alignment, since the only use
3514 // of the string is via this class initializer.
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003515 CharUnits Align = isUTF16
3516 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3517 : getContext().getTypeAlignInChars(getContext().CharTy);
3518 GV->setAlignment(Align.getQuantity());
3519
3520 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3521 // Without it LLVM can merge the string with a non unnamed_addr one during
3522 // LTO. Doing that changes the section it ends in, which surprises ld64.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003523 if (getTriple().isOSBinFormatMachO())
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003524 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3525 : "__TEXT,__cstring,cstring_literals");
Bill Wendling82b87f12012-03-30 00:26:17 +00003526
3527 // String.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003528 llvm::Constant *Str =
David Blaikied3c127e2015-05-07 17:27:56 +00003529 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00003530
Bill Wendling82b87f12012-03-30 00:26:17 +00003531 if (isUTF16)
3532 // Cast the UTF16 string to the correct type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003533 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3534 Fields.add(Str);
Bill Wendling82b87f12012-03-30 00:26:17 +00003535
Anders Carlssonb04ea612007-08-21 00:21:21 +00003536 // String length.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003537 auto Ty = getTypes().ConvertType(getContext().LongTy);
3538 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00003539
John McCall7f416cc2015-09-08 08:05:57 +00003540 CharUnits Alignment = getPointerAlign();
3541
Anders Carlssonb04ea612007-08-21 00:21:21 +00003542 // The struct.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003543 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3544 /*isConstant=*/false,
3545 llvm::GlobalVariable::PrivateLinkage);
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003546 switch (getTriple().getObjectFormat()) {
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003547 case llvm::Triple::UnknownObjectFormat:
3548 llvm_unreachable("unknown file format");
3549 case llvm::Triple::COFF:
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003550 case llvm::Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00003551 case llvm::Triple::Wasm:
Saleem Abdulrasool0295f8c2016-07-09 01:59:51 +00003552 GV->setSection("cfstring");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003553 break;
3554 case llvm::Triple::MachO:
3555 GV->setSection("__DATA,__cfstring");
3556 break;
3557 }
David Blaikie13156b62014-11-19 03:06:06 +00003558 Entry.second = GV;
Mike Stump11289f42009-09-09 15:08:12 +00003559
John McCall7f416cc2015-09-08 08:05:57 +00003560 return ConstantAddress(GV, Alignment);
Anders Carlssonb04ea612007-08-21 00:21:21 +00003561}
Chris Lattnerfb300092007-11-28 05:34:05 +00003562
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +00003563bool CodeGenModule::getExpressionLocationsEnabled() const {
3564 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
3565}
3566
Douglas Gregor636e2002011-08-09 17:23:49 +00003567QualType CodeGenModule::getObjCFastEnumerationStateType() {
3568 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00003569 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00003570 D->startDefinition();
3571
3572 QualType FieldTypes[] = {
3573 Context.UnsignedLongTy,
3574 Context.getPointerType(Context.getObjCIdType()),
3575 Context.getPointerType(Context.UnsignedLongTy),
3576 Context.getConstantArrayType(Context.UnsignedLongTy,
3577 llvm::APInt(32, 5), ArrayType::Normal, 0)
3578 };
3579
3580 for (size_t i = 0; i < 4; ++i) {
3581 FieldDecl *Field = FieldDecl::Create(Context,
3582 D,
3583 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00003584 SourceLocation(), nullptr,
3585 FieldTypes[i], /*TInfo=*/nullptr,
3586 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00003587 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003588 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00003589 Field->setAccess(AS_public);
3590 D->addDecl(Field);
3591 }
3592
3593 D->completeDefinition();
3594 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3595 }
3596
3597 return ObjCFastEnumerationStateType;
3598}
3599
Eli Friedmanfcec6302011-11-01 02:23:42 +00003600llvm::Constant *
3601CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3602 assert(!E->getType()->isPointerType() && "Strings are always arrays");
3603
3604 // Don't emit it as the address of the string, emit the string data itself
3605 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00003606 if (E->getCharByteWidth() == 1) {
3607 SmallString<64> Str(E->getString());
3608
3609 // Resize the string to the right size, which is indicated by its type.
3610 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3611 Str.resize(CAT->getSize().getZExtValue());
3612 return llvm::ConstantDataArray::getString(VMContext, Str, false);
3613 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003614
3615 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00003616 llvm::Type *ElemTy = AType->getElementType();
3617 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00003618
3619 // Wide strings have either 2-byte or 4-byte elements.
3620 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3621 SmallVector<uint16_t, 32> Elements;
3622 Elements.reserve(NumElements);
3623
3624 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3625 Elements.push_back(E->getCodeUnit(i));
3626 Elements.resize(NumElements);
3627 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00003628 }
3629
Chris Lattner02cb1712012-02-06 22:52:04 +00003630 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3631 SmallVector<uint32_t, 32> Elements;
3632 Elements.reserve(NumElements);
3633
3634 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3635 Elements.push_back(E->getCodeUnit(i));
3636 Elements.resize(NumElements);
3637 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00003638}
3639
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003640static llvm::GlobalVariable *
3641GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3642 CodeGenModule &CGM, StringRef GlobalName,
John McCall7f416cc2015-09-08 08:05:57 +00003643 CharUnits Alignment) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003644 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3645 unsigned AddrSpace = 0;
3646 if (CGM.getLangOpts().OpenCL)
3647 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3648
Rafael Espindolad9b26d52015-01-16 20:32:35 +00003649 llvm::Module &M = CGM.getModule();
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003650 // Create a global variable for this string
3651 auto *GV = new llvm::GlobalVariable(
Rafael Espindolad9b26d52015-01-16 20:32:35 +00003652 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3653 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +00003654 GV->setAlignment(Alignment.getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003655 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003656 if (GV->isWeakForLinker()) {
3657 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3658 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3659 }
Rafael Espindolad9b26d52015-01-16 20:32:35 +00003660
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003661 return GV;
3662}
3663
Daniel Dunbarc4baa062008-08-13 23:20:05 +00003664/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3665/// constant array for the given string literal.
John McCall7f416cc2015-09-08 08:05:57 +00003666ConstantAddress
Alexey Bataevec474782014-10-09 08:45:04 +00003667CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3668 StringRef Name) {
John McCall7f416cc2015-09-08 08:05:57 +00003669 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
James Molloye735b2b2014-05-09 16:28:56 +00003670
Richard Smith00db2f12014-07-29 21:20:12 +00003671 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3672 llvm::GlobalVariable **Entry = nullptr;
David Majnemer58e5bee2014-03-24 21:43:36 +00003673 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00003674 Entry = &ConstantStringMap[C];
3675 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00003676 if (Alignment.getQuantity() > GV->getAlignment())
3677 GV->setAlignment(Alignment.getQuantity());
3678 return ConstantAddress(GV, Alignment);
David Majnemer58e5bee2014-03-24 21:43:36 +00003679 }
Eli Friedman49ddc5f2009-11-16 05:55:46 +00003680 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00003681
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003682 SmallString<256> MangledNameBuffer;
3683 StringRef GlobalVariableName;
3684 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00003685
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003686 // Mangle the string literal if the ABI allows for it. However, we cannot
3687 // do this if we are compiling with ASan or -fwritable-strings because they
3688 // rely on strings having normal linkage.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003689 if (!LangOpts.WritableStrings &&
3690 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003691 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3692 llvm::raw_svector_ostream Out(MangledNameBuffer);
3693 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
David Majnemer58e5bee2014-03-24 21:43:36 +00003694
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003695 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3696 GlobalVariableName = MangledNameBuffer;
3697 } else {
3698 LT = llvm::GlobalValue::PrivateLinkage;
Alexey Bataevec474782014-10-09 08:45:04 +00003699 GlobalVariableName = Name;
David Majnemer58e5bee2014-03-24 21:43:36 +00003700 }
3701
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003702 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3703 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00003704 *Entry = GV;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00003705
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00003706 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3707 QualType());
John McCall7f416cc2015-09-08 08:05:57 +00003708 return ConstantAddress(GV, Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00003709}
3710
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00003711/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3712/// array for the given ObjCEncodeExpr node.
John McCall7f416cc2015-09-08 08:05:57 +00003713ConstantAddress
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00003714CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3715 std::string Str;
3716 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00003717
3718 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00003719}
3720
Alexey Samsonovadc90372014-06-04 20:25:57 +00003721/// GetAddrOfConstantCString - Returns a pointer to a character array containing
3722/// the literal and a terminating '\0' character.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00003723/// The result has pointer to array type.
John McCall7f416cc2015-09-08 08:05:57 +00003724ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3725 const std::string &Str, const char *GlobalName) {
Alexey Samsonovadc90372014-06-04 20:25:57 +00003726 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall7f416cc2015-09-08 08:05:57 +00003727 CharUnits Alignment =
3728 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003729
Richard Smith00db2f12014-07-29 21:20:12 +00003730 llvm::Constant *C =
3731 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3732
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003733 // Don't share any string literals if strings aren't constant.
Richard Smith00db2f12014-07-29 21:20:12 +00003734 llvm::GlobalVariable **Entry = nullptr;
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003735 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00003736 Entry = &ConstantStringMap[C];
3737 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00003738 if (Alignment.getQuantity() > GV->getAlignment())
3739 GV->setAlignment(Alignment.getQuantity());
3740 return ConstantAddress(GV, Alignment);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003741 }
3742 }
3743
Daniel Dunbar08b216a2009-03-31 23:42:16 +00003744 // Get the default prefix if a name wasn't specified.
3745 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00003746 GlobalName = ".str";
Chris Lattnerfb300092007-11-28 05:34:05 +00003747 // Create a global variable for this.
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003748 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3749 GlobalName, Alignment);
3750 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00003751 *Entry = GV;
John McCall7f416cc2015-09-08 08:05:57 +00003752 return ConstantAddress(GV, Alignment);
Chris Lattnerfb300092007-11-28 05:34:05 +00003753}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00003754
John McCall7f416cc2015-09-08 08:05:57 +00003755ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00003756 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00003757 assert((E->getStorageDuration() == SD_Static ||
3758 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003759 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00003760
3761 // If we're not materializing a subobject of the temporary, keep the
3762 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00003763 QualType MaterializedType = Init->getType();
3764 if (Init == E->GetTemporaryExpr())
3765 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00003766
John McCall7f416cc2015-09-08 08:05:57 +00003767 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3768
David Majnemer2dcef9e2015-08-13 23:50:15 +00003769 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
John McCall7f416cc2015-09-08 08:05:57 +00003770 return ConstantAddress(Slot, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00003771
3772 // FIXME: If an externally-visible declaration extends multiple temporaries,
3773 // we need to give each temporary the same name in every translation unit (and
3774 // we also need to make the temporaries externally-visible).
3775 SmallString<256> Name;
3776 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00003777 getCXXABI().getMangleContext().mangleReferenceTemporary(
3778 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00003779
Craig Topper8a13c412014-05-21 05:09:00 +00003780 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00003781 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00003782 // We might have a cached constant initializer for this temporary. Note
3783 // that this might have a different value from the value computed by
3784 // evaluating the initializer if the surrounding constant expression
3785 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00003786 Value = getContext().getMaterializedTemporaryValue(E, false);
3787 if (Value && Value->isUninit())
Craig Topper8a13c412014-05-21 05:09:00 +00003788 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00003789 }
3790
Richard Smitha509f2f2013-06-14 03:07:01 +00003791 // Try evaluating it now, it might have a constant initializer.
3792 Expr::EvalResult EvalResult;
3793 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3794 !EvalResult.hasSideEffects())
3795 Value = &EvalResult.Val;
3796
John McCallde0fe072017-08-15 21:42:52 +00003797 unsigned AddrSpace =
3798 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
3799
3800 Optional<ConstantEmitter> emitter;
Craig Topper8a13c412014-05-21 05:09:00 +00003801 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00003802 bool Constant = false;
3803 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00003804 if (Value) {
3805 // The temporary has a constant initializer, use it.
John McCallde0fe072017-08-15 21:42:52 +00003806 emitter.emplace(*this);
3807 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
3808 MaterializedType);
Richard Smitha509f2f2013-06-14 03:07:01 +00003809 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3810 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00003811 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00003812 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00003813 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00003814 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00003815 }
3816
3817 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00003818 llvm::GlobalValue::LinkageTypes Linkage =
3819 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemerc9a9c7a2015-02-19 19:25:17 +00003820 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3821 const VarDecl *InitVD;
3822 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3823 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3824 // Temporaries defined inside a class get linkonce_odr linkage because the
3825 // class can be defined in multipe translation units.
3826 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3827 } else {
3828 // There is no need for this temporary to have external linkage if the
3829 // VarDecl has external linkage.
3830 Linkage = llvm::GlobalVariable::InternalLinkage;
3831 }
3832 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00003833 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003834 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00003835 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
Yaxun Liucbf647c2017-07-08 13:24:52 +00003836 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
John McCallde0fe072017-08-15 21:42:52 +00003837 if (emitter) emitter->finalize(GV);
David Majnemer846c2832014-04-29 06:18:53 +00003838 setGlobalVisibility(GV, VD);
John McCall7f416cc2015-09-08 08:05:57 +00003839 GV->setAlignment(Align.getQuantity());
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003840 if (supportsCOMDAT() && GV->isWeakForLinker())
3841 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smithe6c01442013-06-05 00:46:14 +00003842 if (VD->getTLSKind())
3843 setTLSMode(GV, *VD);
Yaxun Liucbf647c2017-07-08 13:24:52 +00003844 llvm::Constant *CV = GV;
3845 if (AddrSpace != LangAS::Default)
3846 CV = getTargetCodeGenInfo().performAddrSpaceCast(
3847 *this, GV, AddrSpace, LangAS::Default,
3848 Type->getPointerTo(
3849 getContext().getTargetAddressSpace(LangAS::Default)));
3850 MaterializedGlobalTemporaryMap[E] = CV;
3851 return ConstantAddress(CV, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00003852}
3853
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003854/// EmitObjCPropertyImplementations - Emit information for synthesized
3855/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00003856void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003857 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00003858 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003859 // Dynamic is just for type-checking.
3860 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3861 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3862
3863 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00003864 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003865 // we want, that just indicates if the decl came from a
3866 // property. What we want to know is if the method is defined in
3867 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003868 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00003869 CodeGenFunction(*this).GenerateObjCGetter(
3870 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003871 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003872 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00003873 CodeGenFunction(*this).GenerateObjCSetter(
3874 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003875 }
3876 }
3877}
3878
John McCall6a4fa522011-03-22 07:05:39 +00003879static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00003880 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3881 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00003882 ivar; ivar = ivar->getNextIvar())
3883 if (ivar->getType().isDestructedType())
3884 return true;
3885
3886 return false;
3887}
3888
Fariborz Jahanian800821a2014-11-12 22:37:43 +00003889static bool AllTrivialInitializers(CodeGenModule &CGM,
3890 ObjCImplementationDecl *D) {
3891 CodeGenFunction CGF(CGM);
3892 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3893 E = D->init_end(); B != E; ++B) {
3894 CXXCtorInitializer *CtorInitExp = *B;
3895 Expr *Init = CtorInitExp->getInit();
3896 if (!CGF.isTrivialInitializer(Init))
3897 return false;
3898 }
3899 return true;
3900}
3901
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003902/// EmitObjCIvarInitializations - Emit information for ivar initialization
3903/// for an implementation.
3904void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00003905 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3906 if (needsDestructMethod(D)) {
3907 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3908 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3909 ObjCMethodDecl *DTORMethod =
3910 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00003911 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003912 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00003913 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003914 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00003915 D->addInstanceMethod(DTORMethod);
3916 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00003917 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00003918 }
3919
3920 // If the implementation doesn't have any ivar initializers, we don't need
3921 // a .cxx_construct.
Fariborz Jahanian800821a2014-11-12 22:37:43 +00003922 if (D->getNumIvarInitializers() == 0 ||
3923 AllTrivialInitializers(*this, D))
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003924 return;
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003925
John McCall6a4fa522011-03-22 07:05:39 +00003926 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3927 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003928 // The constructor returns 'self'.
3929 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3930 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00003931 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00003932 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003933 getContext().getObjCIdType(),
3934 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003935 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00003936 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003937 /*isImplicitlyDeclared=*/true,
3938 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003939 ObjCMethodDecl::Required);
3940 D->addInstanceMethod(CTORMethod);
3941 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00003942 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003943}
3944
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003945// EmitLinkageSpec - Emit all declarations in a linkage spec.
3946void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00003947 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3948 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003949 ErrorUnsupported(LSD, "linkage spec");
3950 return;
3951 }
3952
Richard Smith8df390f2016-09-08 23:14:54 +00003953 EmitDeclContext(LSD);
3954}
3955
3956void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
3957 for (auto *I : DC->decls()) {
3958 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
3959 // are themselves considered "top-level", so EmitTopLevelDecl on an
3960 // ObjCImplDecl does not recursively visit them. We need to do that in
3961 // case they're nested inside another construct (LinkageSpecDecl /
3962 // ExportDecl) that does stop them from being considered "top-level".
Aaron Ballman629afae2014-03-07 19:56:05 +00003963 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003964 for (auto *M : OID->methods())
3965 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00003966 }
Richard Smith8df390f2016-09-08 23:14:54 +00003967
Aaron Ballman629afae2014-03-07 19:56:05 +00003968 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00003969 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003970}
3971
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003972/// EmitTopLevelDecl - Emit code for a single top level declaration.
3973void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003974 // Ignore dependent declarations.
3975 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3976 return;
Mike Stump11289f42009-09-09 15:08:12 +00003977
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003978 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00003979 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00003980 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003981 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00003982 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00003983 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3984 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor70d83e22009-06-29 17:30:29 +00003985 return;
Mike Stump11289f42009-09-09 15:08:12 +00003986
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003987 EmitGlobal(cast<FunctionDecl>(D));
Alex Lorenzee024992014-08-04 18:41:51 +00003988 // Always provide some coverage mapping
3989 // even for the functions that aren't emitted.
3990 AddDeferredUnusedCoverageMapping(D);
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003991 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003992
Richard Smithada08882017-04-19 21:15:45 +00003993 case Decl::CXXDeductionGuide:
3994 // Function-like, but does not result in code emission.
3995 break;
3996
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003997 case Decl::Var:
Richard Smithbdb84f32016-07-22 23:36:59 +00003998 case Decl::Decomposition:
Larisse Voufo39a1e502013-08-06 01:03:05 +00003999 // Skip variable templates
4000 if (cast<VarDecl>(D)->getDescribedVarTemplate())
4001 return;
Galina Kistanova0872d6c2017-06-03 06:30:46 +00004002 LLVM_FALLTHROUGH;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004003 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004004 EmitGlobal(cast<VarDecl>(D));
Richard Smithda383632016-08-15 01:33:41 +00004005 if (auto *DD = dyn_cast<DecompositionDecl>(D))
4006 for (auto *B : DD->bindings())
4007 if (auto *HD = B->getHoldingVar())
4008 EmitGlobal(HD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004009 break;
4010
John McCall32f44bd2011-04-12 01:01:22 +00004011 // Indirect fields from global anonymous structs and unions can be
4012 // ignored; only the actual variable requires IR gen support.
4013 case Decl::IndirectField:
4014 break;
4015
Anders Carlssonf7475242009-04-15 15:55:24 +00004016 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004017 case Decl::Namespace:
Richard Smith8df390f2016-09-08 23:14:54 +00004018 EmitDeclContext(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004019 break;
Richard Smith62f19e72016-06-25 00:15:56 +00004020 case Decl::CXXRecord:
David Blaikie1ac9c982017-04-11 21:13:37 +00004021 if (DebugInfo) {
4022 if (auto *ES = D->getASTContext().getExternalSource())
4023 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4024 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4025 }
Richard Smith62f19e72016-06-25 00:15:56 +00004026 // Emit any static data members, they may be definitions.
4027 for (auto *I : cast<CXXRecordDecl>(D)->decls())
4028 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4029 EmitTopLevelDecl(I);
4030 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00004031 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00004032 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004033 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004034 case Decl::VarTemplate:
4035 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004036 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00004037 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00004038 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00004039 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00004040 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00004041 case Decl::Using: // using X; [C++]
4042 if (CGDebugInfo *DI = getModuleDebugInfo())
4043 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4044 return;
David Blaikief121b932013-05-20 22:50:41 +00004045 case Decl::NamespaceAlias:
4046 if (CGDebugInfo *DI = getModuleDebugInfo())
4047 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4048 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00004049 case Decl::UsingDirective: // using namespace X; [C++]
4050 if (CGDebugInfo *DI = getModuleDebugInfo())
4051 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4052 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00004053 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00004054 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00004055 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
4056 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson0ade9712009-11-24 05:16:24 +00004057 return;
4058
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00004059 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00004060 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004061 case Decl::CXXDestructor:
Francois Pichet1c229c02011-04-22 22:18:13 +00004062 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
4063 return;
Reid Klecknere7de47e2013-07-22 13:51:44 +00004064 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004065 break;
Anders Carlsson87835432009-06-11 21:22:55 +00004066
4067 case Decl::StaticAssert:
4068 // Nothing to do.
4069 break;
4070
Anders Carlssonf7475242009-04-15 15:55:24 +00004071 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00004072
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004073 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00004074 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00004075 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00004076 break;
4077
Douglas Gregorf6102672012-01-01 21:23:57 +00004078 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004079 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00004080 if (Proto->isThisDeclarationADefinition())
4081 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004082 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00004083 }
4084
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004085 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004086 // Categories have properties but don't support synthesize so we
4087 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00004088 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004089 break;
4090
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004091 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004092 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004093 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004094 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00004095 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00004096 // Emit global variable debug information.
4097 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00004098 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00004099 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4100 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004101 break;
Mike Stump11289f42009-09-09 15:08:12 +00004102 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004103 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004104 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004105 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004106 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004107 CodeGenFunction(*this).GenerateObjCMethod(OMD);
4108 break;
4109 }
Mike Stump11289f42009-09-09 15:08:12 +00004110 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00004111 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004112 break;
4113
Nico Weber66220292016-03-02 17:28:48 +00004114 case Decl::PragmaComment: {
4115 const auto *PCD = cast<PragmaCommentDecl>(D);
4116 switch (PCD->getCommentKind()) {
4117 case PCK_Unknown:
4118 llvm_unreachable("unexpected pragma comment kind");
4119 case PCK_Linker:
4120 AppendLinkerOptions(PCD->getArg());
4121 break;
4122 case PCK_Lib:
4123 AddDependentLib(PCD->getArg());
4124 break;
4125 case PCK_Compiler:
4126 case PCK_ExeStr:
4127 case PCK_User:
4128 break; // We ignore all of these.
4129 }
4130 break;
4131 }
4132
Nico Webercbbaeb12016-03-02 19:28:54 +00004133 case Decl::PragmaDetectMismatch: {
4134 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4135 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4136 break;
4137 }
4138
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004139 case Decl::LinkageSpec:
4140 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004141 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004142
4143 case Decl::FileScopeAsm: {
Artem Belevich0488d1e2015-04-27 18:52:00 +00004144 // File-scope asm is ignored during device-side CUDA compilation.
4145 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4146 break;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004147 // File-scope asm is ignored during device-side OpenMP compilation.
4148 if (LangOpts.OpenMPIsDevice)
4149 break;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004150 auto *AD = cast<FileScopeAsmDecl>(D);
Joerg Sonnenbergerdfd511e2015-03-13 00:54:30 +00004151 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004152 break;
4153 }
Mike Stump11289f42009-09-09 15:08:12 +00004154
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004155 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004156 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004157
Richard Smithdc1f0422016-07-20 19:10:16 +00004158 // If we've already imported this module, we're done.
4159 if (!ImportedModules.insert(Import->getImportedModule()))
Richard Smithc52efa72015-08-19 02:30:28 +00004160 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004161
Richard Smithdc1f0422016-07-20 19:10:16 +00004162 // Emit debug information for direct imports.
4163 if (!Import->getImportedOwningModule()) {
4164 if (CGDebugInfo *DI = getModuleDebugInfo())
4165 DI->EmitImportDecl(*Import);
4166 }
4167
Manman Ren3b5dbf22016-10-14 18:55:44 +00004168 // Find all of the submodules and emit the module initializers.
4169 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4170 SmallVector<clang::Module *, 16> Stack;
4171 Visited.insert(Import->getImportedModule());
4172 Stack.push_back(Import->getImportedModule());
4173
4174 while (!Stack.empty()) {
4175 clang::Module *Mod = Stack.pop_back_val();
4176 if (!EmittedModuleInitializers.insert(Mod).second)
4177 continue;
4178
4179 for (auto *D : Context.getModuleInitializers(Mod))
4180 EmitTopLevelDecl(D);
4181
4182 // Visit the submodules of this module.
4183 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4184 SubEnd = Mod->submodule_end();
4185 Sub != SubEnd; ++Sub) {
4186 // Skip explicit children; they need to be explicitly imported to emit
4187 // the initializers.
4188 if ((*Sub)->IsExplicit)
4189 continue;
4190
4191 if (Visited.insert(*Sub).second)
4192 Stack.push_back(*Sub);
4193 }
4194 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004195 break;
David Blaikie0e716b42014-03-03 23:48:23 +00004196 }
4197
Richard Smith8df390f2016-09-08 23:14:54 +00004198 case Decl::Export:
4199 EmitDeclContext(cast<ExportDecl>(D));
4200 break;
4201
Alexey Bataev97720002014-11-11 04:05:39 +00004202 case Decl::OMPThreadPrivate:
4203 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4204 break;
4205
David Blaikie0e716b42014-03-03 23:48:23 +00004206 case Decl::ClassTemplateSpecialization: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004207 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
David Blaikie0e716b42014-03-03 23:48:23 +00004208 if (DebugInfo &&
David Blaikie0317bc92014-12-16 23:49:18 +00004209 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4210 Spec->hasDefinition())
David Blaikie0e716b42014-03-03 23:48:23 +00004211 DebugInfo->completeTemplateDefinition(*Spec);
Richard Smitha634ff22014-12-01 18:59:10 +00004212 break;
David Blaikie0e716b42014-03-03 23:48:23 +00004213 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004214
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004215 case Decl::OMPDeclareReduction:
4216 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4217 break;
4218
Mike Stump11289f42009-09-09 15:08:12 +00004219 default:
Mike Stump18bb9282009-05-16 07:57:57 +00004220 // Make sure we handled everything we should, every other kind is a
4221 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4222 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004223 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Richard Smitha634ff22014-12-01 18:59:10 +00004224 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004225 }
4226}
John McCall09ae0322010-07-06 23:57:41 +00004227
Alex Lorenzee024992014-08-04 18:41:51 +00004228void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4229 // Do we need to generate coverage mapping?
4230 if (!CodeGenOpts.CoverageMapping)
4231 return;
4232 switch (D->getKind()) {
4233 case Decl::CXXConversion:
4234 case Decl::CXXMethod:
4235 case Decl::Function:
4236 case Decl::ObjCMethod:
4237 case Decl::CXXConstructor:
4238 case Decl::CXXDestructor: {
Justin Bogner203f0922015-07-28 00:41:51 +00004239 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
Alex Lorenzee024992014-08-04 18:41:51 +00004240 return;
Vedant Kumar0acf3432017-09-22 18:23:04 +00004241 SourceManager &SM = getContext().getSourceManager();
4242 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
4243 return;
Alex Lorenzee024992014-08-04 18:41:51 +00004244 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4245 if (I == DeferredEmptyCoverageMappingDecls.end())
4246 DeferredEmptyCoverageMappingDecls[D] = true;
4247 break;
4248 }
4249 default:
4250 break;
4251 };
4252}
4253
4254void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4255 // Do we need to generate coverage mapping?
4256 if (!CodeGenOpts.CoverageMapping)
4257 return;
4258 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4259 if (Fn->isTemplateInstantiation())
4260 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4261 }
4262 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4263 if (I == DeferredEmptyCoverageMappingDecls.end())
4264 DeferredEmptyCoverageMappingDecls[D] = false;
4265 else
4266 I->second = false;
4267}
4268
4269void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00004270 std::vector<const Decl *> DeferredDecls;
Richard Trieub5841332015-04-15 01:21:42 +00004271 for (const auto &I : DeferredEmptyCoverageMappingDecls) {
Alex Lorenzee024992014-08-04 18:41:51 +00004272 if (!I.second)
4273 continue;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00004274 DeferredDecls.push_back(I.first);
4275 }
4276 // Sort the declarations by their location to make sure that the tests get a
4277 // predictable order for the coverage mapping for the unused declarations.
4278 if (CodeGenOpts.DumpCoverageMapping)
4279 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4280 [] (const Decl *LHS, const Decl *RHS) {
4281 return LHS->getLocStart() < RHS->getLocStart();
4282 });
4283 for (const auto *D : DeferredDecls) {
Alex Lorenzee024992014-08-04 18:41:51 +00004284 switch (D->getKind()) {
4285 case Decl::CXXConversion:
4286 case Decl::CXXMethod:
4287 case Decl::Function:
4288 case Decl::ObjCMethod: {
4289 CodeGenPGO PGO(*this);
4290 GlobalDecl GD(cast<FunctionDecl>(D));
4291 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4292 getFunctionLinkage(GD));
4293 break;
4294 }
4295 case Decl::CXXConstructor: {
4296 CodeGenPGO PGO(*this);
4297 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4298 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4299 getFunctionLinkage(GD));
4300 break;
4301 }
4302 case Decl::CXXDestructor: {
4303 CodeGenPGO PGO(*this);
4304 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4305 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4306 getFunctionLinkage(GD));
4307 break;
4308 }
4309 default:
4310 break;
4311 };
4312 }
4313}
4314
John McCall09ae0322010-07-06 23:57:41 +00004315/// Turns the given pointer into a constant.
4316static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4317 const void *Ptr) {
4318 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00004319 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00004320 return llvm::ConstantInt::get(i64, PtrInt);
4321}
4322
4323static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4324 llvm::NamedMDNode *&GlobalMetadata,
4325 GlobalDecl D,
4326 llvm::GlobalValue *Addr) {
4327 if (!GlobalMetadata)
4328 GlobalMetadata =
4329 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4330
4331 // TODO: should we report variant information for ctors/dtors?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004332 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4333 llvm::ConstantAsMetadata::get(GetPointerConstant(
4334 CGM.getLLVMContext(), D.getDecl()))};
Jay Foadea324f12011-04-21 19:59:12 +00004335 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00004336}
4337
Richard Smithdf931ce2013-04-06 05:00:46 +00004338/// For each function which is declared within an extern "C" region and marked
4339/// as 'used', but has internal linkage, create an alias from the unmangled
4340/// name to the mangled name if possible. People expect to be able to refer
4341/// to such functions with an unmangled name from inline assembly within the
4342/// same translation unit.
4343void CodeGenModule::EmitStaticExternCAliases() {
Justin Lebarcd2f6bb2016-01-25 22:36:37 +00004344 // Don't do anything if we're generating CUDA device code -- the NVPTX
4345 // assembly target doesn't support aliases.
4346 if (Context.getTargetInfo().getTriple().isNVPTX())
4347 return;
Yaron Kerenb54db522015-06-11 12:33:25 +00004348 for (auto &I : StaticExternCValues) {
4349 IdentifierInfo *Name = I.first;
4350 llvm::GlobalValue *Val = I.second;
Richard Smith85465e62013-04-06 07:07:44 +00004351 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola27c60b52014-06-03 02:42:01 +00004352 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith85465e62013-04-06 07:07:44 +00004353 }
Richard Smithdf931ce2013-04-06 05:00:46 +00004354}
4355
Alp Tokerfb8d02b2014-06-05 22:10:59 +00004356bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4357 GlobalDecl &Result) const {
4358 auto Res = Manglings.find(MangledName);
4359 if (Res == Manglings.end())
4360 return false;
4361 Result = Res->getValue();
4362 return true;
4363}
4364
John McCall09ae0322010-07-06 23:57:41 +00004365/// Emits metadata nodes associating all the global values in the
4366/// current module with the Decls they came from. This is useful for
4367/// projects using IR gen as a subroutine.
4368///
4369/// Since there's currently no way to associate an MDNode directly
4370/// with an llvm::GlobalValue, we create a global named metadata
4371/// with the name 'clang.global.decl.ptrs'.
4372void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00004373 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00004374
Robert Lytton5b88f78f2014-07-03 09:30:29 +00004375 for (auto &I : MangledDeclNames) {
4376 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
Keno Fischer0e2d4222015-11-05 23:18:44 +00004377 // Some mangled names don't necessarily have an associated GlobalValue
4378 // in this module, e.g. if we mangled it for DebugInfo.
4379 if (Addr)
4380 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall09ae0322010-07-06 23:57:41 +00004381 }
4382}
4383
4384/// Emits metadata nodes for all the local variables in the current
4385/// function.
4386void CodeGenFunction::EmitDeclMetadata() {
4387 if (LocalDeclMap.empty()) return;
4388
4389 llvm::LLVMContext &Context = getLLVMContext();
4390
4391 // Find the unique metadata ID for this name.
4392 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4393
Craig Topper8a13c412014-05-21 05:09:00 +00004394 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00004395
Robert Lytton5b88f78f2014-07-03 09:30:29 +00004396 for (auto &I : LocalDeclMap) {
4397 const Decl *D = I.first;
John McCall7f416cc2015-09-08 08:05:57 +00004398 llvm::Value *Addr = I.second.getPointer();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004399 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00004400 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004401 Alloca->setMetadata(
4402 DeclPtrKind, llvm::MDNode::get(
4403 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004404 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00004405 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4406 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4407 }
4408 }
4409}
Daniel Dunbar900546d2010-07-16 00:00:15 +00004410
Rafael Espindola3bfa4682013-10-16 19:28:50 +00004411void CodeGenModule::EmitVersionIdentMetadata() {
4412 llvm::NamedMDNode *IdentMetadata =
4413 TheModule.getOrInsertNamedMetadata("llvm.ident");
4414 std::string Version = getClangFullVersion();
4415 llvm::LLVMContext &Ctx = TheModule.getContext();
4416
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004417 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola3bfa4682013-10-16 19:28:50 +00004418 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4419}
4420
Robert Lytton57765d52014-07-03 09:30:33 +00004421void CodeGenModule::EmitTargetMetadata() {
Richard Smith1ba0a072014-08-01 20:39:36 +00004422 // Warning, new MangledDeclNames may be appended within this loop.
4423 // We rely on MapVector insertions adding new elements to the end
4424 // of the container.
4425 // FIXME: Move this loop into the one target that needs it, and only
4426 // loop over those declarations for which we couldn't emit the target
4427 // metadata when we emitted the declaration.
4428 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
Richard Smith570706d2014-08-01 22:17:28 +00004429 auto Val = *(MangledDeclNames.begin() + I);
Richard Smith1ba0a072014-08-01 20:39:36 +00004430 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4431 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Robert Lytton57765d52014-07-03 09:30:33 +00004432 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4433 }
4434}
4435
Nick Lewycky85c011d2011-05-05 00:08:20 +00004436void CodeGenModule::EmitCoverageFile() {
Nick Lewycky97e49ac2016-08-31 23:04:32 +00004437 if (getCodeGenOpts().CoverageDataFile.empty() &&
4438 getCodeGenOpts().CoverageNotesFile.empty())
4439 return;
4440
4441 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4442 if (!CUNode)
4443 return;
4444
4445 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4446 llvm::LLVMContext &Ctx = TheModule.getContext();
4447 auto *CoverageDataFile =
4448 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4449 auto *CoverageNotesFile =
4450 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4451 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4452 llvm::MDNode *CU = CUNode->getOperand(i);
4453 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4454 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky480cb992011-05-04 20:46:58 +00004455 }
4456}
Nico Webercf4ff5862012-10-11 10:13:44 +00004457
Nico Weber17d3a2c2014-09-08 16:26:36 +00004458llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Webercf4ff5862012-10-11 10:13:44 +00004459 // Sema has checked that all uuid strings are of the form
4460 // "12345678-1234-1234-1234-1234567890ab".
4461 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00004462 for (unsigned i = 0; i < 36; ++i) {
4463 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4464 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00004465 }
Nico Webercf4ff5862012-10-11 10:13:44 +00004466
Nico Weberdfa274e2014-09-08 16:11:15 +00004467 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemerbbecd092013-08-15 19:59:14 +00004468 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00004469
David Majnemerbbecd092013-08-15 19:59:14 +00004470 llvm::Constant *Field3[8];
4471 for (unsigned Idx = 0; Idx < 8; ++Idx)
4472 Field3[Idx] = llvm::ConstantInt::get(
4473 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4474
4475 llvm::Constant *Fields[4] = {
4476 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4477 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4478 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4479 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4480 };
4481
4482 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00004483}
David Majnemere2cb8d12014-07-07 06:20:47 +00004484
4485llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4486 bool ForEH) {
4487 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4488 // FIXME: should we even be calling this method if RTTI is disabled
4489 // and it's not for EH?
4490 if (!ForEH && !getLangOpts().RTTI)
4491 return llvm::Constant::getNullValue(Int8PtrTy);
4492
4493 if (ForEH && Ty->isObjCObjectPointerType() &&
4494 LangOpts.ObjCRuntime.isGNUFamily())
4495 return ObjCRuntime->GetEHType(Ty);
4496
David Majnemer443250f2015-03-17 20:35:00 +00004497 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
David Majnemere2cb8d12014-07-07 06:20:47 +00004498}
4499
Alexey Bataev97720002014-11-11 04:05:39 +00004500void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4501 for (auto RefExpr : D->varlists()) {
4502 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4503 bool PerformInit =
4504 VD->getAnyInitializer() &&
4505 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4506 /*ForRef=*/false);
John McCall7f416cc2015-09-08 08:05:57 +00004507
4508 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
Alexey Bataev3eff5f42015-02-25 08:32:46 +00004509 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00004510 VD, Addr, RefExpr->getLocStart(), PerformInit))
Alexey Bataev97720002014-11-11 04:05:39 +00004511 CXXGlobalInits.push_back(InitFunction);
4512 }
4513}
Peter Collingbourne86d34a72015-06-17 19:08:05 +00004514
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00004515llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4516 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4517 if (InternalId)
4518 return InternalId;
4519
4520 if (isExternallyVisible(T->getLinkage())) {
4521 std::string OutName;
4522 llvm::raw_string_ostream Out(OutName);
4523 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4524
4525 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4526 } else {
4527 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4528 llvm::ArrayRef<llvm::Metadata *>());
4529 }
4530
4531 return InternalId;
4532}
4533
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004534/// Returns whether this module needs the "all-vtables" type identifier.
4535bool CodeGenModule::NeedAllVtablesTypeId() const {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004536 // Returns true if at least one of vtable-based CFI checkers is enabled and
4537 // is not in the trapping mode.
4538 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4539 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4540 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4541 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4542 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4543 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4544 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4545 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4546}
4547
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004548void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4549 CharUnits Offset,
4550 const CXXRecordDecl *RD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004551 llvm::Metadata *MD =
4552 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004553 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004554
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004555 if (CodeGenOpts.SanitizeCfiCrossDso)
4556 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4557 VTable->addTypeMetadata(Offset.getQuantity(),
4558 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004559
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004560 if (NeedAllVtablesTypeId()) {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004561 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004562 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004563 }
Peter Collingbourne86d34a72015-06-17 19:08:05 +00004564}
Eric Christopher2b90a642015-11-11 23:05:08 +00004565
4566// Fills in the supplied string map with the set of target features for the
4567// passed in function.
4568void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4569 const FunctionDecl *FD) {
4570 StringRef TargetCPU = Target.getTargetOpts().CPU;
4571 if (const auto *TD = FD->getAttr<TargetAttr>()) {
4572 // If we have a TargetAttr build up the feature map based on that.
4573 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4574
4575 // Make a copy of the features as passed on the command line into the
4576 // beginning of the additional features from the function to override.
Erich Keaneb0d44232017-07-18 20:41:02 +00004577 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
Eric Christopher2b90a642015-11-11 23:05:08 +00004578 Target.getTargetOpts().FeaturesAsWritten.begin(),
4579 Target.getTargetOpts().FeaturesAsWritten.end());
4580
Erich Keaneb0d44232017-07-18 20:41:02 +00004581 if (ParsedAttr.Architecture != "")
4582 TargetCPU = ParsedAttr.Architecture ;
Eric Christopher2b90a642015-11-11 23:05:08 +00004583
4584 // Now populate the feature map, first with the TargetCPU which is either
4585 // the default or a new one from the target attribute string. Then we'll use
4586 // the passed in features (FeaturesAsWritten) along with the new ones from
4587 // the attribute.
Erich Keaneb0d44232017-07-18 20:41:02 +00004588 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4589 ParsedAttr.Features);
Eric Christopher2b90a642015-11-11 23:05:08 +00004590 } else {
4591 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4592 Target.getTargetOpts().Features);
4593 }
4594}
Peter Collingbournedc134532016-01-16 00:31:22 +00004595
4596llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4597 if (!SanStats)
4598 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4599
4600 return *SanStats;
4601}
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00004602llvm::Value *
4603CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4604 CodeGenFunction &CGF) {
John McCallde0fe072017-08-15 21:42:52 +00004605 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00004606 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00004607 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4608 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4609 "__translate_sampler_initializer"),
4610 {C});
4611}