blob: 68868708888ae8b33fa3c21005b6917b79044538 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
John McCall7f416cc2015-09-08 08:05:57 +000015#include "CGBlocks.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000016#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGCall.h"
19#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000021#include "CGOpenCLRuntime.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022#include "CGOpenMPRuntime.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000023#include "CGOpenMPRuntimeNVPTX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "CodeGenFunction.h"
Justin Bogneref512b92014-01-06 22:27:43 +000025#include "CodeGenPGO.h"
John McCallde0fe072017-08-15 21:42:52 +000026#include "ConstantEmitter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000027#include "CoverageMappingGen.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000028#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000029#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000030#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000031#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000033#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000034#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000035#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000036#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000037#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000038#include "clang/Basic/CharInfo.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000039#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000040#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000041#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000042#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000043#include "clang/Basic/Version.h"
John McCall5ad74072017-03-02 20:04:19 +000044#include "clang/CodeGen/ConstantInitBuilder.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000045#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindola208b5c02013-10-22 19:26:13 +000046#include "clang/Sema/SemaDiagnostic.h"
John McCallbeec5a02010-03-06 00:35:14 +000047#include "llvm/ADT/Triple.h"
Matthias Brauna4519532017-05-20 01:29:55 +000048#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000049#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000050#include "llvm/IR/CallingConv.h"
51#include "llvm/IR/DataLayout.h"
52#include "llvm/IR/Intrinsics.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/Module.h"
Justin Bogner837a6f62014-04-18 21:52:00 +000055#include "llvm/ProfileData/InstrProfReader.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000056#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000057#include "llvm/Support/ErrorHandling.h"
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +000058#include "llvm/Support/MD5.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000059
Chris Lattnerbed31442007-05-28 01:07:47 +000060using namespace clang;
61using namespace CodeGen;
62
Vedant Kumar0acf3432017-09-22 18:23:04 +000063static llvm::cl::opt<bool> LimitedCoverage(
Zachary Turner8065f0b2017-12-01 00:53:10 +000064 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
Vedant Kumar0acf3432017-09-22 18:23:04 +000065 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
66 llvm::cl::init(false));
67
Julien Lerouge5a6b6982011-09-09 22:41:49 +000068static const char AnnotationSection[] = "llvm.metadata";
69
Alp Toker82862252013-12-28 21:58:40 +000070static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000071 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000072 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000073 case TargetCXXABI::GenericARM:
74 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000075 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +000076 case TargetCXXABI::WatchOS:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000077 case TargetCXXABI::GenericMIPS:
John McCall57625922013-01-25 23:36:14 +000078 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +000079 case TargetCXXABI::WebAssembly:
Alp Toker82862252013-12-28 21:58:40 +000080 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000081 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000082 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000083 }
84
85 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000086}
87
Adrian Prantle74f5252015-06-30 02:26:03 +000088CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
89 const PreprocessorOptions &PPO,
90 const CodeGenOptions &CGO, llvm::Module &M,
Alex Lorenzee024992014-08-04 18:41:51 +000091 DiagnosticsEngine &diags,
92 CoverageSourceInfo *CoverageInfo)
Adrian Prantle74f5252015-06-30 02:26:03 +000093 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
94 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
Mehdi Aminica3cf9e2015-07-24 16:04:29 +000095 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
Reid Kleckner9305fd12016-04-13 23:37:17 +000096 VMContext(M.getContext()), Types(*this), VTables(*this),
Peter Collingbourne3afb2662016-04-28 17:09:37 +000097 SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietzf54319c2013-01-18 11:30:38 +000098
Chris Lattnerece04092012-02-07 00:39:47 +000099 // Initialize the type cache.
100 llvm::LLVMContext &LLVMContext = M.getContext();
101 VoidTy = llvm::Type::getVoidTy(LLVMContext);
102 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
103 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
104 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
105 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
Abderrazek Zaafranif58a1322017-12-21 19:20:01 +0000106 HalfTy = llvm::Type::getHalfTy(LLVMContext);
Chris Lattnerece04092012-02-07 00:39:47 +0000107 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();
126
David Blaikiebbafb8a2012-03-11 07:00:24 +0000127 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000128 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000129 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000130 createOpenCLRuntime();
Alexey Bataev9959db52014-05-06 10:08:46 +0000131 if (LangOpts.OpenMP)
132 createOpenMPRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000133 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000134 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000135
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000136 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000137 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000138 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000139 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
Reid Kleckner9305fd12016-04-13 23:37:17 +0000140 getCXXABI().getMangleContext()));
Dan Gohman947c9af2010-10-14 23:06:10 +0000141
Nick Lewycky207bce32011-04-21 23:44:07 +0000142 // If debug info or coverage generation is enabled, create the CGDebugInfo
143 // object.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000144 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
145 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000146 DebugInfo.reset(new CGDebugInfo(*this));
John McCallad7c5c12011-02-08 08:22:06 +0000147
148 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000149
John McCallb04ecb72015-10-21 18:06:43 +0000150 if (C.getLangOpts().ObjC1)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000151 ObjCData.reset(new ObjCEntrypoints());
Justin Bogneref512b92014-01-06 22:27:43 +0000152
Rong Xu9c6f1532016-03-02 20:59:36 +0000153 if (CodeGenOpts.hasProfileClangUse()) {
154 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
155 CodeGenOpts.ProfileInstrumentUsePath);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000156 if (auto E = ReaderOrErr.takeError()) {
Justin Bogner837a6f62014-04-18 21:52:00 +0000157 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
Diego Novillo5aecacb2015-06-25 22:56:00 +0000158 "Could not read profile %0: %1");
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000159 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
160 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
161 << EI.message();
162 });
Nico Weber176efac2015-04-06 04:16:48 +0000163 } else
164 PGOReader = std::move(ReaderOrErr.get());
Justin Bogner837a6f62014-04-18 21:52:00 +0000165 }
Alex Lorenzee024992014-08-04 18:41:51 +0000166
167 // If coverage mapping generation is enabled, create the
168 // CoverageMappingModuleGen object.
169 if (CodeGenOpts.CoverageMapping)
170 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattnera087ff92008-03-01 08:45:05 +0000171}
172
Reid Kleckner9305fd12016-04-13 23:37:17 +0000173CodeGenModule::~CodeGenModule() {}
Ted Kremenek2c674f62008-08-05 18:50:11 +0000174
David Chisnall481e3a82010-01-23 02:40:42 +0000175void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000176 // This is just isGNUFamily(), but we want to force implementors of
177 // new ABIs to decide how best to do this.
178 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000179 case ObjCRuntime::GNUstep:
180 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000181 case ObjCRuntime::ObjFW:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000182 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000183 return;
184
185 case ObjCRuntime::FragileMacOSX:
186 case ObjCRuntime::MacOSX:
187 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000188 case ObjCRuntime::WatchOS:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000189 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000190 return;
191 }
192 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000193}
194
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000195void CodeGenModule::createOpenCLRuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000196 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000197}
198
Alexey Bataev9959db52014-05-06 10:08:46 +0000199void CodeGenModule::createOpenMPRuntime() {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000200 // Select a specialized code generation class based on the target, if any.
201 // If it does not exist use the default implementation.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000202 switch (getTriple().getArch()) {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000203 case llvm::Triple::nvptx:
204 case llvm::Triple::nvptx64:
205 assert(getLangOpts().OpenMPIsDevice &&
206 "OpenMP NVPTX is only prepared to deal with device code.");
Reid Kleckner9305fd12016-04-13 23:37:17 +0000207 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000208 break;
209 default:
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000210 if (LangOpts.OpenMPSimd)
211 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
212 else
213 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000214 break;
215 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000216}
217
Peter Collingbournefe883422011-10-06 18:29:37 +0000218void CodeGenModule::createCUDARuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000219 CUDARuntime.reset(CreateNVCUDARuntime(*this));
Peter Collingbournefe883422011-10-06 18:29:37 +0000220}
221
Rafael Espindola1e4df922014-09-16 15:18:21 +0000222void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
223 Replacements[Name] = C;
224}
225
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000226void CodeGenModule::applyReplacements() {
Yaron Kerenb54db522015-06-11 12:33:25 +0000227 for (auto &I : Replacements) {
228 StringRef MangledName = I.first();
229 llvm::Constant *Replacement = I.second;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000230 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
231 if (!Entry)
232 continue;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000233 auto *OldF = cast<llvm::Function>(Entry);
234 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000235 if (!NewF) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000236 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
Rafael Espindola0fcad882014-05-16 22:20:18 +0000237 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Reid Klecknerb78257d2014-02-03 18:54:51 +0000238 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000239 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Reid Klecknerb78257d2014-02-03 18:54:51 +0000240 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
241 CE->getOpcode() == llvm::Instruction::GetElementPtr);
242 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
243 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000244 }
245
246 // Replace old with new, but keep the old order.
247 OldF->replaceAllUsesWith(Replacement);
248 if (NewF) {
249 NewF->removeFromParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000250 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
251 NewF);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000252 }
253 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000254 }
255}
256
Andrey Bokhankocab58582015-08-31 13:20:44 +0000257void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
258 GlobalValReplacements.push_back(std::make_pair(GV, C));
259}
260
261void CodeGenModule::applyGlobalValReplacements() {
262 for (auto &I : GlobalValReplacements) {
263 llvm::GlobalValue *GV = I.first;
264 llvm::Constant *C = I.second;
265
266 GV->replaceAllUsesWith(C);
267 GV->eraseFromParent();
268 }
269}
270
Rafael Espindola27c60b52014-06-03 02:42:01 +0000271// This is only used in aliases that we created and we know they have a
272// linear structure.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000273static const llvm::GlobalObject *getAliasedGlobal(
274 const llvm::GlobalIndirectSymbol &GIS) {
275 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
276 const llvm::Constant *C = &GIS;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000277 for (;;) {
Rafael Espindolae11f40a2014-06-04 19:03:20 +0000278 C = C->stripPointerCasts();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000279 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
280 return GO;
281 // stripPointerCasts will not walk over weak aliases.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000282 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
283 if (!GIS2)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000284 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000285 if (!Visited.insert(GIS2).second)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000286 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000287 C = GIS2->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000288 }
289}
290
Rafael Espindola208b5c02013-10-22 19:26:13 +0000291void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000292 // Check if the constructed aliases are well formed. It is really unfortunate
293 // that we have to do this in CodeGen, but we only construct mangled names
294 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000295 bool Error = false;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000296 DiagnosticsEngine &Diags = getDiags();
Yaron Kerenb54db522015-06-11 12:33:25 +0000297 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000298 const auto *D = cast<ValueDecl>(GD.getDecl());
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000299 SourceLocation Location;
300 bool IsIFunc = D->hasAttr<IFuncAttr>();
301 if (const Attr *A = D->getDefiningAttr())
302 Location = A->getLocation();
303 else
304 llvm_unreachable("Not an alias or ifunc?");
Rafael Espindola208b5c02013-10-22 19:26:13 +0000305 StringRef MangledName = getMangledName(GD);
306 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000307 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000308 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
309 if (!GV) {
310 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000311 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000312 } else if (GV->isDeclaration()) {
Rafael Espindola93c7a652014-03-13 15:47:50 +0000313 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000314 Diags.Report(Location, diag::err_alias_to_undefined)
315 << IsIFunc << IsIFunc;
316 } else if (IsIFunc) {
317 // Check resolver function type.
318 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
319 GV->getType()->getPointerElementType());
320 assert(FTy);
321 if (!FTy->getReturnType()->isPointerTy())
322 Diags.Report(Location, diag::err_ifunc_resolver_return);
323 if (FTy->getNumParams())
324 Diags.Report(Location, diag::err_ifunc_resolver_params);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000325 }
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000326
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000327 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000328 llvm::GlobalValue *AliaseeGV;
329 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
330 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
331 else
332 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
333
Rafael Espindola502f65a2014-05-05 20:21:03 +0000334 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
335 StringRef AliasSection = SA->getName();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000336 if (AliasSection != AliaseeGV->getSection())
Rafael Espindola502f65a2014-05-05 20:21:03 +0000337 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000338 << AliasSection << IsIFunc << IsIFunc;
Rafael Espindola502f65a2014-05-05 20:21:03 +0000339 }
Rafael Espindola27c60b52014-06-03 02:42:01 +0000340
341 // We have to handle alias to weak aliases in here. LLVM itself disallows
342 // this since the object semantics would not match the IL one. For
343 // compatibility with gcc we implement it by just pointing the alias
344 // to its aliasee's aliasee. We also warn, since the user is probably
345 // expecting the link to be weak.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000346 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
Sanjoy Dasf60a0d72016-04-08 01:31:02 +0000347 if (GA->isInterposable()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000348 Diags.Report(Location, diag::warn_alias_to_weak_alias)
349 << GV->getName() << GA->getName() << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000350 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000351 GA->getIndirectSymbol(), Alias->getType());
352 Alias->setIndirectSymbol(Aliasee);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000353 }
354 }
Rafael Espindola208b5c02013-10-22 19:26:13 +0000355 }
356 if (!Error)
357 return;
358
Yaron Kerenb54db522015-06-11 12:33:25 +0000359 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola208b5c02013-10-22 19:26:13 +0000360 StringRef MangledName = getMangledName(GD);
361 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000362 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000363 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
364 Alias->eraseFromParent();
365 }
366}
367
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000368void CodeGenModule::clear() {
369 DeferredDeclsToEmit.clear();
Alexey Bataev91797552015-03-18 04:13:55 +0000370 if (OpenMPRuntime)
371 OpenMPRuntime->clear();
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000372}
373
Justin Bogner40b8ba12014-06-26 01:45:07 +0000374void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
375 StringRef MainFile) {
376 if (!hasDiagnostics())
377 return;
378 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
379 if (MainFile.empty())
380 MainFile = "<stdin>";
381 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
Vedant Kumar96d6ca72017-04-27 17:30:58 +0000382 } else {
383 if (Mismatched > 0)
384 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
385
386 if (Missing > 0)
387 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
388 }
Justin Bogner40b8ba12014-06-26 01:45:07 +0000389}
390
Ted Kremenek2c674f62008-08-05 18:50:11 +0000391void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000392 EmitDeferred();
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000393 EmitVTablesOpportunistically();
Andrey Bokhankocab58582015-08-31 13:20:44 +0000394 applyGlobalValReplacements();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000395 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000396 checkAliases();
Erich Keane281d20b2018-01-08 21:34:17 +0000397 emitMultiVersionFunctions();
Eli Friedman5866fe32010-01-08 00:50:11 +0000398 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000399 EmitCXXGlobalDtorFunc();
Akira Hatanaka617e2612018-04-17 18:41:52 +0000400 registerGlobalDtorsWithAtExit();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000401 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000402 if (ObjCRuntime)
403 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000404 AddGlobalCtor(ObjCInitFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000405 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
406 CUDARuntime) {
Artem Belevichc66d2542018-06-27 18:32:51 +0000407 if (llvm::Function *CudaCtorFunction =
408 CUDARuntime->makeModuleCtorFunction())
Artem Belevich52cc4872015-05-07 19:34:16 +0000409 AddGlobalCtor(CudaCtorFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000410 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000411 if (OpenMPRuntime) {
Samuel Antaoee8fb302016-01-06 13:42:12 +0000412 if (llvm::Function *OpenMPRegistrationFunction =
George Rokos29d0f002017-05-27 03:03:13 +0000413 OpenMPRuntime->emitRegistrationFunction()) {
414 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415 OpenMPRegistrationFunction : nullptr;
416 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
417 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000418 OpenMPRuntime->clear();
419 }
Easwaran Raman695890c2015-12-17 19:14:27 +0000420 if (PGOReader) {
Easwaran Raman81608122016-03-24 21:32:25 +0000421 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
Easwaran Raman695890c2015-12-17 19:14:27 +0000422 if (PGOStats.hasDiagnostics())
423 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
424 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000425 EmitCtorList(GlobalCtors, "llvm.global_ctors");
426 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000427 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000428 EmitStaticExternCAliases();
Alex Lorenzee024992014-08-04 18:41:51 +0000429 EmitDeferredUnusedCoverageMappings();
430 if (CoverageMapping)
431 CoverageMapping->emit();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000432 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000433 CodeGenFunction(*this).EmitCfiCheckFail();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000434 CodeGenFunction(*this).EmitCfiCheckStub();
435 }
Alex Lorenza8fbef42017-03-23 11:14:27 +0000436 emitAtAvailableLinkGuard();
Rafael Espindola060062a2014-03-06 22:15:10 +0000437 emitLLVMUsed();
Peter Collingbournedc134532016-01-16 00:31:22 +0000438 if (SanStats)
439 SanStats->finish();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000440
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000441 if (CodeGenOpts.Autolink &&
442 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000443 EmitModuleLinkOptions();
444 }
Nirav Dave8497ef42017-03-18 00:43:39 +0000445
Nirav Dave741dea02017-03-30 13:41:44 +0000446 // Record mregparm value now so it is visible through rest of codegen.
447 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
448 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
449 CodeGenOpts.NumRegisterParameters);
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000450
Reid Kleckner124955a2015-08-05 18:51:13 +0000451 if (CodeGenOpts.DwarfVersion) {
Manman Ren9691f7f2013-06-19 01:46:49 +0000452 // We actually want the latest version when there are conflicts.
453 // We can change from Warning to Latest if such mode is supported.
454 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
455 CodeGenOpts.DwarfVersion);
Reid Kleckner124955a2015-08-05 18:51:13 +0000456 }
457 if (CodeGenOpts.EmitCodeView) {
458 // Indicate that we want CodeView in the metadata.
459 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
460 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000461 if (CodeGenOpts.ControlFlowGuard) {
462 // We want function ID tables for Control Flow Guard.
463 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
464 }
Piotr Padlewski9d0ecf22015-09-15 21:46:50 +0000465 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
466 // We don't support LTO with 2 with different StrictVTablePointers
467 // FIXME: we could support it by stripping all the information introduced
468 // by StrictVTablePointers.
469
470 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
471
472 llvm::Metadata *Ops[2] = {
473 llvm::MDString::get(VMContext, "StrictVTablePointers"),
474 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
475 llvm::Type::getInt32Ty(VMContext), 1))};
476
477 getModule().addModuleFlag(llvm::Module::Require,
478 "StrictVTablePointersRequirement",
479 llvm::MDNode::get(VMContext, Ops));
480 }
Manman Ren4b7f23d2013-11-22 19:42:45 +0000481 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000482 // We support a single version in the linked module. The LLVM
483 // parser will drop debug info with a different version number
484 // (and warn about it, too).
485 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000486 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000487
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000488 // We need to record the widths of enums and wchar_t, so that we can generate
Matthias Brauna4519532017-05-20 01:29:55 +0000489 // the correct build attributes in the ARM backend. wchar_size is also used by
490 // TargetLibraryInfo.
Matthias Braunbffc1bb2017-09-26 02:37:23 +0000491 uint64_t WCharWidth =
492 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
Matthias Brauna4519532017-05-20 01:29:55 +0000493 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
494
Justin Bogner9bb7f152014-06-23 20:03:28 +0000495 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000496 if ( Arch == llvm::Triple::arm
497 || Arch == llvm::Triple::armeb
498 || Arch == llvm::Triple::thumb
499 || Arch == llvm::Triple::thumbeb) {
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000500 // The minimum width of an enum in bytes
501 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
502 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
503 }
504
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000505 if (CodeGenOpts.SanitizeCfiCrossDso) {
506 // Indicate that we want cross-DSO control flow integrity checks.
507 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
508 }
509
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +0000510 if (CodeGenOpts.CFProtectionReturn &&
511 Target.checkCFProtectionReturnSupported(getDiags())) {
512 // Indicate that we want to instrument return control flow protection.
513 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
514 1);
515 }
516
517 if (CodeGenOpts.CFProtectionBranch &&
518 Target.checkCFProtectionBranchSupported(getDiags())) {
519 // Indicate that we want to instrument branch control flow protection.
520 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
521 1);
522 }
523
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000524 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
Justin Lebard3a44f62016-04-05 18:26:20 +0000525 // Indicate whether __nvvm_reflect should be configured to flush denormal
526 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
527 // property.)
528 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
529 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
530 }
531
Alexey Bader364a1162017-06-20 14:30:18 +0000532 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
533 if (LangOpts.OpenCL) {
534 EmitOpenCLMetadata();
535 // Emit SPIR version.
536 if (getTriple().getArch() == llvm::Triple::spir ||
537 getTriple().getArch() == llvm::Triple::spir64) {
538 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
539 // opencl.spir.version named metadata.
540 llvm::Metadata *SPIRVerElts[] = {
541 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
542 Int32Ty, LangOpts.OpenCLVersion / 100)),
543 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
544 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
545 llvm::NamedMDNode *SPIRVerMD =
546 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
547 llvm::LLVMContext &Ctx = TheModule.getContext();
548 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
549 }
550 }
551
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000552 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
Sriraman Tallam70e70e62016-04-28 22:34:00 +0000553 assert(PLevel < 3 && "Invalid PIC Level");
554 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
Rafael Espindolac9d336e2016-06-23 15:07:32 +0000555 if (Context.getLangOpts().PIE)
556 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000557 }
558
Sriraman Tallam80af0052018-02-23 21:27:33 +0000559 if (CodeGenOpts.NoPLT)
560 getModule().setRtLibUseGOT();
561
John McCall0bdb1fd2010-09-16 06:16:50 +0000562 SimplifyPersonality();
563
John McCall09ae0322010-07-06 23:57:41 +0000564 if (getCodeGenOpts().EmitDeclMetadata)
565 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000566
567 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000568 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000569
570 if (DebugInfo)
571 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000572
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +0000573 if (getCodeGenOpts().EmitVersionIdentMetadata)
574 EmitVersionIdentMetadata();
Robert Lytton57765d52014-07-03 09:30:33 +0000575
576 EmitTargetMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000577}
578
Alexey Bader364a1162017-06-20 14:30:18 +0000579void CodeGenModule::EmitOpenCLMetadata() {
580 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
581 // opencl.ocl.version named metadata node.
582 llvm::Metadata *OCLVerElts[] = {
583 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
584 Int32Ty, LangOpts.OpenCLVersion / 100)),
585 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
586 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
587 llvm::NamedMDNode *OCLVerMD =
588 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
589 llvm::LLVMContext &Ctx = TheModule.getContext();
590 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
591}
592
Devang Patel945b8ae2011-03-23 16:29:39 +0000593void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
594 // Make sure that this type is translated.
595 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000596}
597
David Majnemer929025d2016-01-26 19:30:26 +0000598void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
599 // Make sure that this type is translated.
600 Types.RefreshTypeCacheForClass(RD);
601}
602
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000603llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
Dan Gohman947c9af2010-10-14 23:06:10 +0000604 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000605 return nullptr;
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000606 return TBAA->getTypeInfo(QTy);
Dan Gohman947c9af2010-10-14 23:06:10 +0000607}
608
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000609TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
Ivan A. Kosarev124a2182018-02-20 12:33:04 +0000610 if (!TBAA)
611 return TBAAAccessInfo();
612 return TBAA->getAccessInfo(AccessType);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000613}
614
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000615TBAAAccessInfo
616CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000617 if (!TBAA)
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000618 return TBAAAccessInfo();
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000619 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000620}
621
Dan Gohman22695fc2012-09-28 21:58:29 +0000622llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
623 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000624 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000625 return TBAA->getTBAAStructInfo(QTy);
626}
627
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000628llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
629 if (!TBAA)
630 return nullptr;
631 return TBAA->getBaseTypeInfo(QTy);
632}
633
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000634llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
Manman Renc451e572013-04-04 21:53:22 +0000635 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000636 return nullptr;
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000637 return TBAA->getAccessTagInfo(Info);
Manman Renc451e572013-04-04 21:53:22 +0000638}
639
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000640TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
641 TBAAAccessInfo TargetInfo) {
642 if (!TBAA)
643 return TBAAAccessInfo();
644 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
645}
646
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +0000647TBAAAccessInfo
648CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
649 TBAAAccessInfo InfoB) {
650 if (!TBAA)
651 return TBAAAccessInfo();
652 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
653}
654
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000655TBAAAccessInfo
656CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
657 TBAAAccessInfo SrcInfo) {
658 if (!TBAA)
659 return TBAAAccessInfo();
660 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
661}
662
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000663void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000664 TBAAAccessInfo TBAAInfo) {
665 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
666 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
Dan Gohman947c9af2010-10-14 23:06:10 +0000667}
668
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000669void CodeGenModule::DecorateInstructionWithInvariantGroup(
670 llvm::Instruction *I, const CXXRecordDecl *RD) {
Piotr Padlewski34046bd2017-04-24 12:58:43 +0000671 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
672 llvm::MDNode::get(getLLVMContext(), {}));
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000673}
674
Alp Toker29cb66b2014-01-26 06:17:37 +0000675void CodeGenModule::Error(SourceLocation loc, StringRef message) {
676 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
677 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000678}
679
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000680/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000681/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000682void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000683 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000684 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000685 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000686 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
687 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000688}
Chris Lattner41af8182007-12-02 06:27:33 +0000689
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000690/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000691/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000692void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000693 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000694 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000695 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000696 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000697}
698
John McCall23c29fe2011-06-24 21:55:10 +0000699llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
700 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
701}
702
Mike Stump11289f42009-09-09 15:08:12 +0000703void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000704 const NamedDecl *D) const {
Rafael Espindola123ce972018-01-24 18:58:32 +0000705 if (GV->hasDLLImportStorageClass())
706 return;
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000707 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000708 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000709 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000710 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000711 }
Rafael Espindola3f727a82018-03-14 18:14:46 +0000712 if (!D)
713 return;
John McCallc273f242010-10-30 11:50:40 +0000714 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000715 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000716 if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
Rafael Espindola4a5da442013-02-27 02:56:45 +0000717 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000718}
719
Rafael Espindola699f5d62018-02-07 22:15:33 +0000720static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
Rafael Espindola3dd49812018-02-23 00:22:15 +0000721 llvm::GlobalValue *GV) {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000722 if (GV->hasLocalLinkage())
723 return true;
724
725 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
726 return true;
727
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000728 // DLLImport explicitly marks the GV as external.
729 if (GV->hasDLLImportStorageClass())
730 return false;
731
Rafael Espindola699f5d62018-02-07 22:15:33 +0000732 const llvm::Triple &TT = CGM.getTriple();
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000733 // Every other GV is local on COFF.
734 // Make an exception for windows OS in the triple: Some firmware builds use
735 // *-win32-macho triples. This (accidentally?) produced windows relocations
736 // without GOT tables in older clang versions; Keep this behaviour.
737 // FIXME: even thread local variables?
738 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
739 return true;
740
741 // Only handle COFF and ELF for now.
Rafael Espindola699f5d62018-02-07 22:15:33 +0000742 if (!TT.isOSBinFormatELF())
743 return false;
744
745 // If this is not an executable, don't assume anything is local.
746 const auto &CGOpts = CGM.getCodeGenOpts();
747 llvm::Reloc::Model RM = CGOpts.RelocationModel;
748 const auto &LOpts = CGM.getLangOpts();
749 if (RM != llvm::Reloc::Static && !LOpts.PIE)
750 return false;
751
752 // A definition cannot be preempted from an executable.
753 if (!GV->isDeclarationForLinker())
754 return true;
755
756 // Most PIC code sequences that assume that a symbol is local cannot produce a
757 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
758 // depended, it seems worth it to handle it here.
759 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
760 return false;
761
762 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
763 llvm::Triple::ArchType Arch = TT.getArch();
764 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
765 Arch == llvm::Triple::ppc64le)
766 return false;
767
768 // If we can use copy relocations we can assume it is local.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000769 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
770 if (!Var->isThreadLocal() &&
Rafael Espindola75e57362018-02-07 23:04:06 +0000771 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
772 return true;
Rafael Espindola699f5d62018-02-07 22:15:33 +0000773
774 // If we can use a plt entry as the symbol address we can assume it
775 // is local.
776 // FIXME: This should work for PIE, but the gold linker doesn't support it.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000777 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
Rafael Espindola699f5d62018-02-07 22:15:33 +0000778 return true;
779
780 // Otherwise don't assue it is local.
781 return false;
782}
783
Rafael Espindola3dd49812018-02-23 00:22:15 +0000784void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000785 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
Rafael Espindola699f5d62018-02-07 22:15:33 +0000786}
787
Rafael Espindolab7350042018-03-01 00:35:47 +0000788void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
789 GlobalDecl GD) const {
790 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
Reid Klecknerae9b0702018-03-16 19:40:50 +0000791 // C++ destructors have a few C++ ABI specific special cases.
Rafael Espindolab7350042018-03-01 00:35:47 +0000792 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
Reid Klecknerae9b0702018-03-16 19:40:50 +0000793 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
794 return;
Rafael Espindolab7350042018-03-01 00:35:47 +0000795 }
796 setDLLImportDLLExport(GV, D);
797}
798
799void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
800 const NamedDecl *D) const {
Rafael Espindola3f727a82018-03-14 18:14:46 +0000801 if (D && D->isExternallyVisible()) {
Rafael Espindolab7350042018-03-01 00:35:47 +0000802 if (D->hasAttr<DLLImportAttr>())
803 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
804 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
805 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
806 }
807}
808
809void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
810 GlobalDecl GD) const {
811 setDLLImportDLLExport(GV, GD);
812 setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
813}
814
Rafael Espindola699f5d62018-02-07 22:15:33 +0000815void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
816 const NamedDecl *D) const {
Rafael Espindolab7350042018-03-01 00:35:47 +0000817 setDLLImportDLLExport(GV, D);
818 setGlobalVisibilityAndLocal(GV, D);
819}
820
821void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
822 const NamedDecl *D) const {
Rafael Espindola699f5d62018-02-07 22:15:33 +0000823 setGlobalVisibility(GV, D);
Rafael Espindola3dd49812018-02-23 00:22:15 +0000824 setDSOLocal(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +0000825}
826
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000827static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
828 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
829 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
830 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
831 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
832 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
833}
834
835static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
836 CodeGenOptions::TLSModel M) {
837 switch (M) {
838 case CodeGenOptions::GeneralDynamicTLSModel:
839 return llvm::GlobalVariable::GeneralDynamicTLSModel;
840 case CodeGenOptions::LocalDynamicTLSModel:
841 return llvm::GlobalVariable::LocalDynamicTLSModel;
842 case CodeGenOptions::InitialExecTLSModel:
843 return llvm::GlobalVariable::InitialExecTLSModel;
844 case CodeGenOptions::LocalExecTLSModel:
845 return llvm::GlobalVariable::LocalExecTLSModel;
846 }
847 llvm_unreachable("Invalid TLS model!");
848}
849
David Majnemerbb525f7c2014-10-15 22:38:23 +0000850void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000851 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000852
David Majnemerbb525f7c2014-10-15 22:38:23 +0000853 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000854 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000855
856 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000857 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000858 TLM = GetLLVMTLSModel(Attr->getModel());
859 }
860
861 GV->setThreadLocalMode(TLM);
862}
863
Erich Keane281d20b2018-01-08 21:34:17 +0000864static void AppendTargetMangling(const CodeGenModule &CGM,
865 const TargetAttr *Attr, raw_ostream &Out) {
866 if (Attr->isDefaultVersion())
867 return;
868
869 Out << '.';
870 const auto &Target = CGM.getTarget();
871 TargetAttr::ParsedTargetAttr Info =
872 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
George Burgess IV19131152018-01-17 04:46:04 +0000873 // Multiversioning doesn't allow "no-${feature}", so we can
874 // only have "+" prefixes here.
875 assert(LHS.startswith("+") && RHS.startswith("+") &&
876 "Features should always have a prefix.");
877 return Target.multiVersionSortPriority(LHS.substr(1)) >
878 Target.multiVersionSortPriority(RHS.substr(1));
Erich Keane281d20b2018-01-08 21:34:17 +0000879 });
880
881 bool IsFirst = true;
882
883 if (!Info.Architecture.empty()) {
884 IsFirst = false;
885 Out << "arch_" << Info.Architecture;
886 }
887
888 for (StringRef Feat : Info.Features) {
889 if (!IsFirst)
890 Out << '_';
891 IsFirst = false;
892 Out << Feat.substr(1);
893 }
894}
895
896static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
897 const NamedDecl *ND,
898 bool OmitTargetMangling = false) {
899 SmallString<256> Buffer;
900 llvm::raw_svector_ostream Out(Buffer);
901 MangleContext &MC = CGM.getCXXABI().getMangleContext();
902 if (MC.shouldMangleDeclName(ND)) {
903 llvm::raw_svector_ostream Out(Buffer);
904 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
905 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
906 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
907 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
908 else
909 MC.mangleName(ND, Out);
910 } else {
911 IdentifierInfo *II = ND->getIdentifier();
912 assert(II && "Attempt to mangle unnamed decl.");
913 const auto *FD = dyn_cast<FunctionDecl>(ND);
914
915 if (FD &&
916 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
917 llvm::raw_svector_ostream Out(Buffer);
918 Out << "__regcall3__" << II->getName();
919 } else {
920 Out << II->getName();
921 }
922 }
923
924 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
925 if (FD->isMultiVersion() && !OmitTargetMangling)
926 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
927 return Out.str();
928}
929
930void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
931 const FunctionDecl *FD) {
932 if (!FD->isMultiVersion())
933 return;
934
935 // Get the name of what this would be without the 'target' attribute. This
936 // allows us to lookup the version that was emitted when this wasn't a
937 // multiversion function.
938 std::string NonTargetName =
939 getMangledNameImpl(*this, GD, FD, /*OmitTargetMangling=*/true);
940 GlobalDecl OtherGD;
941 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
942 assert(OtherGD.getCanonicalDecl()
943 .getDecl()
944 ->getAsFunction()
945 ->isMultiVersion() &&
946 "Other GD should now be a multiversioned function");
947 // OtherFD is the version of this function that was mangled BEFORE
948 // becoming a MultiVersion function. It potentially needs to be updated.
949 const FunctionDecl *OtherFD =
950 OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
951 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
952 // This is so that if the initial version was already the 'default'
953 // version, we don't try to update it.
954 if (OtherName != NonTargetName) {
Erich Keanebc40c5c2018-01-09 01:09:12 +0000955 // Remove instead of erase, since others may have stored the StringRef
956 // to this.
957 const auto ExistingRecord = Manglings.find(NonTargetName);
958 if (ExistingRecord != std::end(Manglings))
959 Manglings.remove(&(*ExistingRecord));
Erich Keane281d20b2018-01-08 21:34:17 +0000960 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
961 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
962 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
963 Entry->setName(OtherName);
964 }
965 }
966}
967
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000968StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
David Majnemerd2385c02016-01-08 20:48:26 +0000969 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
970
971 // Some ABIs don't have constructor variants. Make sure that base and
972 // complete constructors get mangled the same.
973 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
974 if (!getTarget().getCXXABI().hasConstructorVariants()) {
975 CXXCtorType OrigCtorType = GD.getCtorType();
976 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
977 if (OrigCtorType == Ctor_Base)
978 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
979 }
980 }
981
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +0000982 auto FoundName = MangledDeclNames.find(CanonicalGD);
983 if (FoundName != MangledDeclNames.end())
984 return FoundName->second;
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000985
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000986
Richard Smith6d0e97a2014-08-02 00:50:16 +0000987 // Keep the first result in the case of a mangling collision.
Erich Keane281d20b2018-01-08 21:34:17 +0000988 const auto *ND = cast<NamedDecl>(GD.getDecl());
989 auto Result =
990 Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +0000991 return MangledDeclNames[CanonicalGD] = Result.first->first();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000992}
993
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000994StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
995 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000996 MangleContext &MangleCtx = getCXXABI().getMangleContext();
997 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +0000998
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000999 SmallString<256> Buffer;
1000 llvm::raw_svector_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +00001001 if (!D)
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001002 MangleCtx.mangleGlobalBlock(BD,
Fariborz Jahanian63628032012-06-26 16:06:38 +00001003 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001004 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001005 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001006 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001007 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001008 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001009 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001010
Richard Smith6d0e97a2014-08-02 00:50:16 +00001011 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1012 return Result.first->first();
Anders Carlsson635186a2010-06-09 02:36:32 +00001013}
1014
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001015llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +00001016 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +00001017}
1018
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001019/// AddGlobalCtor - Add a function to the list that will be called before
1020/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001021void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1022 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +00001023 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001024 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001025}
1026
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001027/// AddGlobalDtor - Add a function to the list that will be called
1028/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001029void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Akira Hatanaka617e2612018-04-17 18:41:52 +00001030 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1031 DtorsUsingAtExit[Priority].push_back(Dtor);
1032 return;
1033 }
1034
Daniel Dunbardec798b2009-01-13 02:25:00 +00001035 // FIXME: Type coercion of void()* types.
Craig Topper4b566922014-06-09 02:04:02 +00001036 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001037}
1038
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001039void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001040 if (Fns.empty()) return;
1041
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001042 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +00001043 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001044 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001045
Reid Kleckner563f0e82014-05-23 21:13:45 +00001046 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1047 llvm::StructType *CtorStructTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00001048 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001049
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001050 // Construct the constructor and destructor arrays.
John McCall23c9dc62016-11-28 22:18:27 +00001051 ConstantInitBuilder builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001052 auto ctors = builder.beginArray(CtorStructTy);
Yaron Kerenb54db522015-06-11 12:33:25 +00001053 for (const auto &I : Fns) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001054 auto ctor = ctors.beginStruct(CtorStructTy);
1055 ctor.addInt(Int32Ty, I.Priority);
1056 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1057 if (I.AssociatedData)
1058 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1059 else
1060 ctor.addNullPointer(VoidPtrTy);
John McCallf1788632016-11-28 22:18:30 +00001061 ctor.finishAndAddTo(ctors);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001062 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001063
John McCall18081af2016-11-19 20:12:25 +00001064 auto list =
1065 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1066 /*constant*/ false,
1067 llvm::GlobalValue::AppendingLinkage);
1068
1069 // The LTO linker doesn't seem to like it when we set an alignment
1070 // on appending variables. Take it off as a workaround.
1071 list->setAlignment(0);
1072
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001073 Fns.clear();
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001074}
1075
John McCalld4324142010-02-19 01:32:20 +00001076llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001077CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001078 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +00001079
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001080 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +00001081
Reid Klecknerae9b0702018-03-16 19:40:50 +00001082 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1083 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
Reid Klecknera283e482017-12-21 19:44:23 +00001084
Richard Smith5179eb72016-06-28 19:03:57 +00001085 if (isa<CXXConstructorDecl>(D) &&
1086 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1087 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1088 // Our approach to inheriting constructors is fundamentally different from
1089 // that used by the MS ABI, so keep our inheriting constructor thunks
1090 // internal rather than trying to pick an unambiguous mangling for them.
1091 return llvm::GlobalValue::InternalLinkage;
1092 }
1093
Hans Wennborg275efb92014-05-28 01:52:23 +00001094 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +00001095}
Nuno Lopesb6f79532008-06-08 15:45:52 +00001096
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001097llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001098 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1099 if (!MDS) return nullptr;
1100
Benjamin Kramer630cf8c2016-11-23 11:20:27 +00001101 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001102}
1103
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001104void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +00001105 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001106 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001107 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +00001108 llvm::AttributeList PAL;
1109 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
1110 F->setAttributes(PAL);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001111 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +00001112}
1113
John McCall9b0a7ce2011-10-02 01:16:38 +00001114/// Determines whether the language options require us to model
1115/// unwind exceptions. We treat -fexceptions as mandating this
1116/// except under the fragile ObjC ABI with only ObjC exceptions
1117/// enabled. This means, for example, that C with -fexceptions
1118/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001119static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +00001120 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001121 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +00001122
1123 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001124 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +00001125
1126 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001127 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +00001128 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +00001129 }
1130
1131 return true;
1132}
1133
Peter Collingbournee44acad2018-06-26 02:15:47 +00001134static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1135 const CXXMethodDecl *MD) {
1136 // Check that the type metadata can ever actually be used by a call.
1137 if (!CGM.getCodeGenOpts().LTOUnit ||
1138 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1139 return false;
1140
1141 // Only functions whose address can be taken with a member function pointer
1142 // need this sort of type metadata.
1143 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1144 !isa<CXXDestructorDecl>(MD);
1145}
1146
1147std::vector<const CXXRecordDecl *>
1148CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1149 llvm::SetVector<const CXXRecordDecl *> MostBases;
1150
1151 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1152 CollectMostBases = [&](const CXXRecordDecl *RD) {
1153 if (RD->getNumBases() == 0)
1154 MostBases.insert(RD);
1155 for (const CXXBaseSpecifier &B : RD->bases())
1156 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1157 };
1158 CollectMostBases(RD);
1159 return MostBases.takeVector();
1160}
1161
Daniel Dunbar38932572009-04-14 08:05:55 +00001162void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1163 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001164 llvm::AttrBuilder B;
1165
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001166 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001167 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001168
David Blaikiebbafb8a2012-03-11 07:00:24 +00001169 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001170 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +00001171
Manoj Gupta4fbf84c2018-05-09 21:41:18 +00001172 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1173 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1174 B.addAttribute(llvm::Attribute::StackProtect);
1175 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1176 B.addAttribute(llvm::Attribute::StackProtectStrong);
1177 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1178 B.addAttribute(llvm::Attribute::StackProtectReq);
1179 }
Akira Hatanaka200500d2015-10-08 19:30:57 +00001180
1181 if (!D) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001182 // If we don't have a declaration to control inlining, the function isn't
1183 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1184 // disabled, mark the function as noinline.
1185 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1186 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1187 B.addAttribute(llvm::Attribute::NoInline);
1188
Reid Kleckneree4930b2017-05-02 22:07:37 +00001189 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Akira Hatanaka200500d2015-10-08 19:30:57 +00001190 return;
1191 }
1192
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001193 // Track whether we need to add the optnone LLVM attribute,
1194 // starting with the default for this optimization level.
1195 bool ShouldAddOptNone =
1196 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1197 // We can't add optnone in the following cases, it won't pass the verifier.
1198 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1199 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1200 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1201
1202 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001203 B.addAttribute(llvm::Attribute::OptimizeNone);
1204
1205 // OptimizeNone implies noinline; we should not be inlining such functions.
1206 B.addAttribute(llvm::Attribute::NoInline);
1207 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1208 "OptimizeNone and AlwaysInline on same function!");
1209
1210 // We still need to handle naked functions even though optnone subsumes
1211 // much of their semantics.
1212 if (D->hasAttr<NakedAttr>())
1213 B.addAttribute(llvm::Attribute::Naked);
1214
1215 // OptimizeNone wins over OptimizeForSize and MinSize.
1216 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1217 F->removeFnAttr(llvm::Attribute::MinSize);
1218 } else if (D->hasAttr<NakedAttr>()) {
Eli Friedmanc55efe42011-08-22 23:55:33 +00001219 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001220 B.addAttribute(llvm::Attribute::Naked);
1221 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001222 } else if (D->hasAttr<NoDuplicateAttr>()) {
1223 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001224 } else if (D->hasAttr<NoInlineAttr>()) {
1225 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +00001226 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Chandler Carruthfcd33142016-12-23 01:24:49 +00001227 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001228 // (noinline wins over always_inline, and we can't specify both in IR)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001229 B.addAttribute(llvm::Attribute::AlwaysInline);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001230 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1231 // If we're not inlining, then force everything that isn't always_inline to
1232 // carry an explicit noinline attribute.
1233 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1234 B.addAttribute(llvm::Attribute::NoInline);
1235 } else {
1236 // Otherwise, propagate the inline hint attribute and potentially use its
1237 // absence to mark things as noinline.
1238 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1239 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
1240 return Redecl->isInlineSpecified();
1241 })) {
1242 B.addAttribute(llvm::Attribute::InlineHint);
1243 } else if (CodeGenOpts.getInlining() ==
1244 CodeGenOptions::OnlyHintInlining &&
1245 !FD->isInlined() &&
1246 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1247 B.addAttribute(llvm::Attribute::NoInline);
1248 }
1249 }
Eli Friedmanc55efe42011-08-22 23:55:33 +00001250 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +00001251
Chandler Carruthfcd33142016-12-23 01:24:49 +00001252 // Add other optimization related attributes if we are optimizing this
1253 // function.
1254 if (!D->hasAttr<OptimizeNoneAttr>()) {
1255 if (D->hasAttr<ColdAttr>()) {
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001256 if (!ShouldAddOptNone)
1257 B.addAttribute(llvm::Attribute::OptimizeForSize);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001258 B.addAttribute(llvm::Attribute::Cold);
1259 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001260
Chandler Carruthfcd33142016-12-23 01:24:49 +00001261 if (D->hasAttr<MinSizeAttr>())
1262 B.addAttribute(llvm::Attribute::MinSize);
1263 }
Richard Smithb555a762012-09-28 22:46:07 +00001264
Reid Kleckneree4930b2017-05-02 22:07:37 +00001265 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001266
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001267 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1268 if (alignment)
1269 F->setAlignment(alignment);
1270
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00001271 if (!D->hasAttr<AlignedAttr>())
1272 if (LangOpts.FunctionAlignment)
1273 F->setAlignment(1 << LangOpts.FunctionAlignment);
1274
Dan Gohmanc2853072015-09-03 22:51:53 +00001275 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1276 // reserve a bit for differentiating between virtual and non-virtual member
1277 // functions. If the current target's C++ ABI requires this and this is a
1278 // member function, set its alignment accordingly.
1279 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1280 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1281 F->setAlignment(2);
1282 }
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001283
1284 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1285 if (CodeGenOpts.SanitizeCfiCrossDso)
1286 if (auto *FD = dyn_cast<FunctionDecl>(D))
Peter Collingbournee44acad2018-06-26 02:15:47 +00001287 CreateFunctionTypeMetadataForIcall(FD, F);
1288
1289 // Emit type metadata on member functions for member function pointer checks.
1290 // These are only ever necessary on definitions; we're guaranteed that the
1291 // definition will be present in the LTO unit as a result of LTO visibility.
1292 auto *MD = dyn_cast<CXXMethodDecl>(D);
1293 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1294 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1295 llvm::Metadata *Id =
1296 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1297 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1298 F->addTypeMetadata(0, Id);
1299 }
1300 }
Daniel Dunbar449a3392008-09-04 23:41:35 +00001301}
1302
Rafael Espindola75c649c2018-03-01 00:06:55 +00001303void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1304 const Decl *D = GD.getDecl();
Rafael Espindolab7350042018-03-01 00:35:47 +00001305 if (dyn_cast_or_null<NamedDecl>(D))
1306 setGVProperties(GV, GD);
John McCall457a04e2010-10-22 21:05:15 +00001307 else
1308 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +00001309
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001310 if (D && D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +00001311 addUsedGlobal(GV);
Rafael Espindola502f65a2014-05-05 20:21:03 +00001312}
1313
Erich Keane93e58662018-02-12 17:01:41 +00001314bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
1315 llvm::AttrBuilder &Attrs) {
1316 // Add target-cpu and target-features attributes to functions. If
1317 // we have a decl for the function and it has a target attribute then
1318 // parse that and add it to the feature set.
1319 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1320 std::vector<std::string> Features;
1321 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
1322 FD = FD ? FD->getMostRecentDecl() : FD;
1323 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1324 bool AddedAttr = false;
1325 if (TD) {
1326 llvm::StringMap<bool> FeatureMap;
1327 getFunctionFeatureMap(FeatureMap, FD);
1328
1329 // Produce the canonical string for this set of features.
1330 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1331 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1332
1333 // Now add the target-cpu and target-features to the function.
1334 // While we populated the feature map above, we still need to
1335 // get and parse the target attribute so we can get the cpu for
1336 // the function.
1337 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1338 if (ParsedAttr.Architecture != "" &&
1339 getTarget().isValidCPUName(ParsedAttr.Architecture))
1340 TargetCPU = ParsedAttr.Architecture;
1341 } else {
1342 // Otherwise just add the existing target cpu and target features to the
1343 // function.
1344 Features = getTarget().getTargetOpts().Features;
1345 }
1346
1347 if (TargetCPU != "") {
1348 Attrs.addAttribute("target-cpu", TargetCPU);
1349 AddedAttr = true;
1350 }
1351 if (!Features.empty()) {
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001352 llvm::sort(Features.begin(), Features.end());
Erich Keane93e58662018-02-12 17:01:41 +00001353 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1354 AddedAttr = true;
1355 }
1356
1357 return AddedAttr;
1358}
1359
Rafael Espindola285271c2018-02-28 23:54:23 +00001360void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
Rafael Espindolaee076a22014-05-13 18:45:53 +00001361 llvm::GlobalObject *GO) {
Rafael Espindola285271c2018-02-28 23:54:23 +00001362 const Decl *D = GD.getDecl();
Rafael Espindola75c649c2018-03-01 00:06:55 +00001363 SetCommonAttributes(GD, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +00001364
Javed Absar2a67c9e2017-06-05 10:11:57 +00001365 if (D) {
1366 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1367 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1368 GV->addAttribute("bss-section", SA->getName());
1369 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1370 GV->addAttribute("data-section", SA->getName());
1371 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1372 GV->addAttribute("rodata-section", SA->getName());
1373 }
1374
1375 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1376 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
Erich Keane30994d22018-02-08 20:04:22 +00001377 if (!D->getAttr<SectionAttr>())
1378 F->addFnAttr("implicit-section-name", SA->getName());
Erich Keane93e58662018-02-12 17:01:41 +00001379
1380 llvm::AttrBuilder Attrs;
1381 if (GetCPUAndFeaturesAttributes(D, Attrs)) {
1382 // We know that GetCPUAndFeaturesAttributes will always have the
1383 // newest set, since it has the newest possible FunctionDecl, so the
1384 // new ones should replace the old.
1385 F->removeFnAttr("target-cpu");
1386 F->removeFnAttr("target-features");
1387 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1388 }
Javed Absar2a67c9e2017-06-05 10:11:57 +00001389 }
Erich Keane7963e8b2018-07-18 20:04:48 +00001390
1391 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1392 GO->setSection(CSA->getName());
1393 else if (const auto *SA = D->getAttr<SectionAttr>())
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001394 GO->setSection(SA->getName());
Javed Absar2a67c9e2017-06-05 10:11:57 +00001395 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001396
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001397 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +00001398}
1399
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001400void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001401 llvm::Function *F,
1402 const CGFunctionInfo &FI) {
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001403 const Decl *D = GD.getDecl();
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001404 SetLLVMFunctionAttributes(D, FI, F);
1405 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +00001406
1407 F->setLinkage(llvm::Function::InternalLinkage);
1408
Rafael Espindola285271c2018-02-28 23:54:23 +00001409 setNonAliasAttributes(GD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001410}
1411
Rafael Espindolab7350042018-03-01 00:35:47 +00001412static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
David Majnemerf6acb762014-04-25 17:07:16 +00001413 // Set linkage and visibility in case we never see a definition.
1414 LinkageInfo LV = ND->getLinkageAndVisibility();
Rafael Espindolab7350042018-03-01 00:35:47 +00001415 // Don't set internal linkage on declarations.
1416 // "extern_weak" is overloaded in LLVM; we probably should have
1417 // separate linkage types for this.
1418 if (isExternallyVisible(LV.getLinkage()) &&
1419 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1420 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
David Majnemerf6acb762014-04-25 17:07:16 +00001421}
1422
Peter Collingbournee44acad2018-06-26 02:15:47 +00001423void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1424 llvm::Function *F) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001425 // Only if we are checking indirect calls.
1426 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1427 return;
1428
Peter Collingbournee44acad2018-06-26 02:15:47 +00001429 // Non-static class methods are handled via vtable or member function pointer
1430 // checks elsewhere.
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001431 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1432 return;
1433
1434 // Additionally, if building with cross-DSO support...
1435 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001436 // Skip available_externally functions. They won't be codegen'ed in the
1437 // current module anyway.
1438 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1439 return;
1440 }
1441
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001442 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001443 F->addTypeMetadata(0, MD);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00001444 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001445
1446 // Emit a hash-based bit set entry for cross-DSO calls.
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001447 if (CodeGenOpts.SanitizeCfiCrossDso)
1448 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1449 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001450}
1451
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001452void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1453 bool IsIncompleteFunction,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001454 bool IsThunk) {
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001455
Pete Cooper2f1637a2015-05-20 17:17:45 +00001456 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001457 // If this is an intrinsic function, set the function's attributes
1458 // to the intrinsic's attributes.
Pete Cooper2f1637a2015-05-20 17:17:45 +00001459 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001460 return;
1461 }
1462
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001463 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +00001464
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001465 if (!IsIncompleteFunction) {
John McCalla729c622012-02-17 03:33:10 +00001466 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001467 // Setup target-specific attributes.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001468 if (F->isDeclaration())
1469 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001470 }
Mike Stump11289f42009-09-09 15:08:12 +00001471
Bob Wilsonfc6297f2014-04-01 01:38:16 +00001472 // Add the Returned attribute for "this", except for iOS 5 and earlier
1473 // where substantial code, including the libstdc++ dylib, was compiled with
1474 // GCC and does not actually return "this".
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001475 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00001476 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001477 assert(!F->arg_empty() &&
1478 F->arg_begin()->getType()
1479 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1480 "unexpected this return");
1481 F->addAttribute(1, llvm::Attribute::Returned);
1482 }
1483
Daniel Dunbar38932572009-04-14 08:05:55 +00001484 // Only a few attributes are set on declarations; these may later be
1485 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +00001486
Jake Ehrlichba874ad2017-11-29 00:54:20 +00001487 setLinkageForGV(F, FD);
Rafael Espindola699f5d62018-02-07 22:15:33 +00001488 setGVProperties(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +00001489
Erich Keane7963e8b2018-07-18 20:04:48 +00001490 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1491 F->setSection(CSA->getName());
1492 else if (const auto *SA = FD->getAttr<SectionAttr>())
1493 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +00001494
Richard Smith351241c2016-04-07 21:46:12 +00001495 if (FD->isReplaceableGlobalAllocationFunction()) {
1496 // A replaceable global allocation function does not act like a builtin by
1497 // default, only if it is invoked by a new-expression or delete-expression.
Reid Klecknerde864822017-03-21 16:57:30 +00001498 F->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001499 llvm::Attribute::NoBuiltin);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001500
Richard Smith351241c2016-04-07 21:46:12 +00001501 // A sane operator new returns a non-aliasing pointer.
1502 // FIXME: Also add NonNull attribute to the return value
1503 // for the non-nothrow forms?
1504 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1505 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1506 (Kind == OO_New || Kind == OO_Array_New))
Reid Klecknerde864822017-03-21 16:57:30 +00001507 F->addAttribute(llvm::AttributeList::ReturnIndex,
Richard Smith351241c2016-04-07 21:46:12 +00001508 llvm::Attribute::NoAlias);
1509 }
1510
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001511 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001512 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001513 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1514 if (MD->isVirtual())
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001515 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001516
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001517 // Don't emit entries for function declarations in the cross-DSO mode. This
1518 // is handled with better precision by the receiving DSO.
1519 if (!CodeGenOpts.SanitizeCfiCrossDso)
Peter Collingbournee44acad2018-06-26 02:15:47 +00001520 CreateFunctionTypeMetadataForIcall(FD, F);
Alexey Bataevb952e632017-12-15 16:28:31 +00001521
1522 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1523 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001524}
1525
Rafael Espindola060062a2014-03-06 22:15:10 +00001526void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +00001527 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001528 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001529 LLVMUsed.emplace_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001530}
1531
Rafael Espindola060062a2014-03-06 22:15:10 +00001532void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1533 assert(!GV->isDeclaration() &&
1534 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001535 LLVMCompilerUsed.emplace_back(GV);
Rafael Espindola060062a2014-03-06 22:15:10 +00001536}
1537
1538static void emitUsed(CodeGenModule &CGM, StringRef Name,
Sanjoy Dase369bd92017-05-01 17:08:00 +00001539 std::vector<llvm::WeakTrackingVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001540 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +00001541 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001542 return;
1543
Rafael Espindola060062a2014-03-06 22:15:10 +00001544 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +00001545 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +00001546 UsedArray.resize(List.size());
1547 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001548 UsedArray[i] =
Justin Holewinskif37f3d32015-02-02 21:05:49 +00001549 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1550 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +00001551 }
Mike Stump11289f42009-09-09 15:08:12 +00001552
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001553 if (UsedArray.empty())
1554 return;
Rafael Espindola060062a2014-03-06 22:15:10 +00001555 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +00001556
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001557 auto *GV = new llvm::GlobalVariable(
1558 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1559 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001560
1561 GV->setSection("llvm.metadata");
1562}
1563
Rafael Espindola060062a2014-03-06 22:15:10 +00001564void CodeGenModule::emitLLVMUsed() {
1565 emitUsed(*this, "llvm.used", LLVMUsed);
1566 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1567}
1568
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001569void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001570 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001571 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1572}
1573
Aaron Ballman5d041be2013-06-04 02:07:14 +00001574void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1575 llvm::SmallString<32> Opt;
1576 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001577 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballman5d041be2013-06-04 02:07:14 +00001578 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1579}
1580
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00001581void CodeGenModule::AddELFLibDirective(StringRef Lib) {
1582 auto &C = getLLVMContext();
1583 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1584 C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1585}
1586
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001587void CodeGenModule::AddDependentLib(StringRef Lib) {
1588 llvm::SmallString<24> Opt;
1589 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001590 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001591 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1592}
1593
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001594/// Add link options implied by the given module, including modules
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001595/// it depends on, using a postorder walk.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001596static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
Peter Collingbourne89061b22017-06-12 20:10:48 +00001597 SmallVectorImpl<llvm::MDNode *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001598 llvm::SmallPtrSet<Module *, 16> &Visited) {
1599 // Import this module's parent.
David Blaikie82e95a32014-11-19 07:49:47 +00001600 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001601 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001602 }
1603
1604 // Import this module's dependencies.
1605 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001606 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001607 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001608 }
1609
1610 // Add linker options to link against the libraries/frameworks
1611 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001612 llvm::LLVMContext &Context = CGM.getLLVMContext();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00001613
1614 // For modules that use export_as for linking, use that module
1615 // name instead.
1616 if (Mod->UseExportAsModuleLinkName)
1617 return;
1618
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001619 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001620 // Link against a framework. Frameworks are currently Darwin only, so we
1621 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001622 if (Mod->LinkLibraries[I-1].IsFramework) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001623 llvm::Metadata *Args[2] = {
1624 llvm::MDString::get(Context, "-framework"),
1625 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001626
1627 Metadata.push_back(llvm::MDNode::get(Context, Args));
1628 continue;
1629 }
1630
1631 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001632 llvm::SmallString<24> Opt;
1633 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1634 Mod->LinkLibraries[I-1].Library, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001635 auto *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001636 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1637 }
1638}
1639
1640void CodeGenModule::EmitModuleLinkOptions() {
1641 // Collect the set of all of the modules we want to visit to emit link
1642 // options, which is essentially the imported modules and all of their
1643 // non-explicit child modules.
1644 llvm::SetVector<clang::Module *> LinkModules;
1645 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1646 SmallVector<clang::Module *, 16> Stack;
1647
1648 // Seed the stack with imported modules.
Manman Ren9803ee82017-01-11 18:47:38 +00001649 for (Module *M : ImportedModules) {
1650 // Do not add any link flags when an implementation TU of a module imports
1651 // a header of that same module.
1652 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1653 !getLangOpts().isCompilingModule())
1654 continue;
Yaron Kerenb54db522015-06-11 12:33:25 +00001655 if (Visited.insert(M).second)
1656 Stack.push_back(M);
Manman Ren9803ee82017-01-11 18:47:38 +00001657 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001658
1659 // Find all of the modules to import, making a little effort to prune
1660 // non-leaf modules.
1661 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001662 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001663
1664 bool AnyChildren = false;
1665
1666 // Visit the submodules of this module.
1667 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1668 SubEnd = Mod->submodule_end();
1669 Sub != SubEnd; ++Sub) {
1670 // Skip explicit children; they need to be explicitly imported to be
1671 // linked against.
1672 if ((*Sub)->IsExplicit)
1673 continue;
1674
David Blaikie82e95a32014-11-19 07:49:47 +00001675 if (Visited.insert(*Sub).second) {
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001676 Stack.push_back(*Sub);
1677 AnyChildren = true;
1678 }
1679 }
1680
1681 // We didn't find any children, so add this module to the list of
1682 // modules to link against.
1683 if (!AnyChildren) {
1684 LinkModules.insert(Mod);
1685 }
1686 }
1687
1688 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001689 // order. We don't do anything to try to order import link flags with respect
1690 // to linker options inserted by things like #pragma comment().
Peter Collingbourne89061b22017-06-12 20:10:48 +00001691 SmallVector<llvm::MDNode *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001692 Visited.clear();
Yaron Kerenb54db522015-06-11 12:33:25 +00001693 for (Module *M : LinkModules)
1694 if (Visited.insert(M).second)
1695 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
Daniel Dunbar69e47462013-01-17 01:35:06 +00001696 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001697 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001698
Daniel Dunbar69e47462013-01-17 01:35:06 +00001699 // Add the linker options metadata flag.
Peter Collingbourne89061b22017-06-12 20:10:48 +00001700 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1701 for (auto *MD : LinkerOptionsMetadata)
1702 NMD->addOperand(MD);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001703}
1704
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001705void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +00001706 // Emit code for any potentially referenced deferred decls. Since a
1707 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001708 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001709
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001710 if (!DeferredVTables.empty()) {
1711 EmitDeferredVTables();
John McCall6bd2a892013-01-25 22:31:03 +00001712
Eric Christopherd160c502016-01-29 01:35:53 +00001713 // Emitting a vtable doesn't directly cause more vtables to
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001714 // become deferred, although it can cause functions to be
Eric Christopherd160c502016-01-29 01:35:53 +00001715 // emitted that then need those vtables.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001716 assert(DeferredVTables.empty());
1717 }
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001718
Eric Christopherd160c502016-01-29 01:35:53 +00001719 // Stop if we're out of both deferred vtables and deferred declarations.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001720 if (DeferredDeclsToEmit.empty())
1721 return;
John McCall6bd2a892013-01-25 22:31:03 +00001722
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001723 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1724 // work, it will not interfere with this.
Sanjoy Das70a60512017-05-01 06:12:13 +00001725 std::vector<GlobalDecl> CurDeclsToEmit;
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001726 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1727
Sanjoy Das70a60512017-05-01 06:12:13 +00001728 for (GlobalDecl &D : CurDeclsToEmit) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00001729 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1730 // to get GlobalValue with exactly the type we need, not something that
1731 // might had been created for another decl with the same mangled name but
1732 // different type.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001733 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
John McCalld195d4c2016-11-30 23:25:13 +00001734 GetAddrOfGlobal(D, ForDefinition));
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001735
1736 // In case of different address spaces, we may still get a cast, even with
1737 // IsForDefinition equal to true. Query mangled names table to get
1738 // GlobalValue.
1739 if (!GV)
1740 GV = GetGlobalValue(getMangledName(D));
1741
1742 // Make sure GetGlobalValue returned non-null.
1743 assert(GV);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001744
John McCallc2af9392010-05-27 01:45:30 +00001745 // Check to see if we've already emitted this. This is necessary
1746 // for a couple of reasons: first, decls can end up in the
1747 // deferred-decls queue multiple times, and second, decls can end
1748 // up with definitions in unusual ways (e.g. by an extern inline
1749 // function acquiring a strong function redefinition). Just
1750 // ignore these cases.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001751 if (!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001752 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001753
Chris Lattner45470942009-03-21 09:44:56 +00001754 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001755 EmitGlobalDefinition(D, GV);
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001756
1757 // If we found out that we need to emit more decls, do that recursively.
1758 // This has the advantage that the decls are emitted in a DFS and related
1759 // ones are close together, which is convenient for testing.
1760 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1761 EmitDeferred();
1762 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1763 }
Chris Lattner45470942009-03-21 09:44:56 +00001764 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001765}
Chris Lattner09153c02007-06-22 18:48:09 +00001766
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001767void CodeGenModule::EmitVTablesOpportunistically() {
1768 // Try to emit external vtables as available_externally if they have emitted
1769 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1770 // is not allowed to create new references to things that need to be emitted
1771 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1772
Piotr Padlewski05547742017-06-01 09:24:36 +00001773 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1774 && "Only emit opportunistic vtables with optimizations");
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001775
1776 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1777 assert(getVTables().isVTableExternal(RD) &&
1778 "This queue should only contain external vtables");
1779 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1780 VTables.GenerateClassData(RD);
1781 }
1782 OpportunisticVTables.clear();
1783}
1784
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001785void CodeGenModule::EmitGlobalAnnotations() {
1786 if (Annotations.empty())
1787 return;
1788
1789 // Create a new global variable for the ConstantStruct in the Module.
1790 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1791 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001792 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1793 llvm::GlobalValue::AppendingLinkage,
1794 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001795 gv->setSection(AnnotationSection);
1796}
1797
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001798llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001799 llvm::Constant *&AStr = AnnotationStrings[Str];
1800 if (AStr)
1801 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001802
1803 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001804 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001805 auto *gv =
1806 new llvm::GlobalVariable(getModule(), s->getType(), true,
1807 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001808 gv->setSection(AnnotationSection);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001809 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Benjamin Kramereed80612013-11-10 16:55:11 +00001810 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001811 return gv;
1812}
1813
1814llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1815 SourceManager &SM = getContext().getSourceManager();
1816 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1817 if (PLoc.isValid())
1818 return EmitAnnotationString(PLoc.getFilename());
1819 return EmitAnnotationString(SM.getBufferName(Loc));
1820}
1821
1822llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1823 SourceManager &SM = getContext().getSourceManager();
1824 PresumedLoc PLoc = SM.getPresumedLoc(L);
1825 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1826 SM.getExpansionLineNumber(L);
1827 return llvm::ConstantInt::get(Int32Ty, LineNo);
1828}
1829
Mike Stump11289f42009-09-09 15:08:12 +00001830llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001831 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001832 SourceLocation L) {
1833 // Get the globals for file name, annotation, and the line number.
1834 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1835 *UnitGV = EmitAnnotationUnit(L),
1836 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001837
Daniel Dunbar346892a2009-04-14 22:41:13 +00001838 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001839 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001840 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1841 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1842 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1843 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001844 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001845 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001846}
1847
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001848void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1849 llvm::GlobalValue *GV) {
1850 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1851 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001852 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1853 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001854}
1855
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001856bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1857 llvm::Function *Fn,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001858 SourceLocation Loc) const {
1859 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1860 // Blacklist by function name.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001861 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001862 return true;
1863 // Blacklist by location.
Yaron Kerened1fe5d2015-10-03 05:15:57 +00001864 if (Loc.isValid())
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001865 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001866 // If location is unknown, this may be a compiler-generated function. Assume
1867 // it's located in the main file.
1868 auto &SM = Context.getSourceManager();
1869 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001870 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001871 }
1872 return false;
1873}
1874
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001875bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1876 SourceLocation Loc, QualType Ty,
1877 StringRef Category) const {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001878 // For now globals can be blacklisted only in ASan and KASan.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001879 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +00001880 (SanitizerKind::Address | SanitizerKind::KernelAddress |
1881 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001882 if (!EnabledAsanMask)
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001883 return false;
1884 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001885 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001886 return true;
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001887 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001888 return true;
1889 // Check global type.
1890 if (!Ty.isNull()) {
1891 // Drill down the array types: if global variable of a fixed type is
1892 // blacklisted, we also don't instrument arrays of them.
1893 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1894 Ty = AT->getElementType();
1895 Ty = Ty.getCanonicalType().getUnqualifiedType();
1896 // We allow to blacklist only record types (classes, structs etc.)
1897 if (Ty->isRecordType()) {
1898 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001899 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001900 return true;
1901 }
1902 }
1903 return false;
1904}
1905
Dean Michael Berris835832d2017-03-30 00:29:36 +00001906bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1907 StringRef Category) const {
1908 if (!LangOpts.XRayInstrument)
1909 return false;
Dean Michael Berris488f7c22018-04-13 02:31:58 +00001910
Dean Michael Berris835832d2017-03-30 00:29:36 +00001911 const auto &XRayFilter = getContext().getXRayFilter();
1912 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
Dean Michael Berris488f7c22018-04-13 02:31:58 +00001913 auto Attr = ImbueAttr::NONE;
Dean Michael Berris835832d2017-03-30 00:29:36 +00001914 if (Loc.isValid())
1915 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1916 if (Attr == ImbueAttr::NONE)
1917 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1918 switch (Attr) {
1919 case ImbueAttr::NONE:
1920 return false;
1921 case ImbueAttr::ALWAYS:
1922 Fn->addFnAttr("function-instrument", "xray-always");
1923 break;
Dean Michael Berris170429e2017-05-24 05:46:36 +00001924 case ImbueAttr::ALWAYS_ARG1:
1925 Fn->addFnAttr("function-instrument", "xray-always");
1926 Fn->addFnAttr("xray-log-args", "1");
1927 break;
Dean Michael Berris835832d2017-03-30 00:29:36 +00001928 case ImbueAttr::NEVER:
1929 Fn->addFnAttr("function-instrument", "xray-never");
1930 break;
1931 }
1932 return true;
1933}
1934
Hans Wennborg43a0f992015-01-10 01:19:48 +00001935bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001936 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001937 if (LangOpts.EmitAllDecls)
Hans Wennborg43a0f992015-01-10 01:19:48 +00001938 return true;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001939
Hans Wennborg43a0f992015-01-10 01:19:48 +00001940 return getContext().DeclMustBeEmitted(Global);
1941}
1942
1943bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1944 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1945 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1946 // Implicit template instantiations may change linkage if they are later
1947 // explicitly instantiated, so they should not be emitted eagerly.
1948 return false;
Richard Smithd9b90092016-07-02 01:32:16 +00001949 if (const auto *VD = dyn_cast<VarDecl>(Global))
1950 if (Context.getInlineVariableDefinitionKind(VD) ==
1951 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1952 // A definition of an inline constexpr static data member may change
1953 // linkage later if it's redeclared outside the class.
1954 return false;
Samuel Antaof8b50122015-07-13 22:54:53 +00001955 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1956 // codegen for global variables, because they may be marked as threadprivate.
1957 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
Alexey Bataev96edb2e2018-06-25 15:32:05 +00001958 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
1959 !isTypeConstant(Global->getType(), false))
Samuel Antaof8b50122015-07-13 22:54:53 +00001960 return false;
Hans Wennborg43a0f992015-01-10 01:19:48 +00001961
1962 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001963}
1964
John McCall7f416cc2015-09-08 08:05:57 +00001965ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
Nico Webercf4ff5862012-10-11 10:13:44 +00001966 const CXXUuidofExpr* E) {
1967 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1968 // well-formed.
David Majnemer2041b462016-03-28 03:19:50 +00001969 StringRef Uuid = E->getUuidStr();
David Majnemercf963ce2013-08-09 08:35:59 +00001970 std::string Name = "_GUID_" + Uuid.lower();
1971 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00001972
David Majnemer65687602016-03-27 04:46:14 +00001973 // The UUID descriptor should be pointer aligned.
1974 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
John McCall7f416cc2015-09-08 08:05:57 +00001975
Nico Webercf4ff5862012-10-11 10:13:44 +00001976 // Look for an existing global.
1977 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
John McCall7f416cc2015-09-08 08:05:57 +00001978 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00001979
Nico Weber17d3a2c2014-09-08 16:26:36 +00001980 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Webercf4ff5862012-10-11 10:13:44 +00001981 assert(Init && "failed to initialize as constant");
1982
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001983 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00001984 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00001985 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001986 if (supportsCOMDAT())
1987 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolaca08d242018-03-20 15:42:58 +00001988 setDSOLocal(GV);
John McCall7f416cc2015-09-08 08:05:57 +00001989 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00001990}
1991
John McCall7f416cc2015-09-08 08:05:57 +00001992ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001993 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1994 assert(AA && "No alias?");
1995
John McCall7f416cc2015-09-08 08:05:57 +00001996 CharUnits Alignment = getContext().getDeclAlign(VD);
Chris Lattner2192fe52011-07-18 04:24:23 +00001997 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001998
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001999 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00002000 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002001 if (Entry) {
2002 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
John McCall7f416cc2015-09-08 08:05:57 +00002003 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2004 return ConstantAddress(Ptr, Alignment);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002005 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002006
2007 llvm::Constant *Aliasee;
2008 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002009 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2010 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00002011 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002012 else
John McCall7ec50432010-03-19 23:29:14 +00002013 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00002014 llvm::PointerType::getUnqual(DeclTy),
2015 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002016
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002017 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002018 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2019 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002020
John McCall7f416cc2015-09-08 08:05:57 +00002021 return ConstantAddress(Aliasee, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002022}
2023
Chris Lattnere0be0df2009-05-12 21:21:08 +00002024void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002025 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002026
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002027 // Weak references don't produce any output by themselves.
2028 if (Global->hasAttr<WeakRefAttr>())
2029 return;
2030
Chris Lattner54041692009-03-22 21:47:11 +00002031 // If this is an alias definition (which otherwise looks like a declaration)
2032 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002033 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00002034 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002035
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002036 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2037 if (Global->hasAttr<IFuncAttr>())
2038 return emitIFuncDefinition(GD);
2039
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002040 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002041 if (LangOpts.CUDA) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00002042 if (LangOpts.CUDAIsDevice) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002043 if (!Global->hasAttr<CUDADeviceAttr>() &&
2044 !Global->hasAttr<CUDAGlobalAttr>() &&
2045 !Global->hasAttr<CUDAConstantAttr>() &&
2046 !Global->hasAttr<CUDASharedAttr>())
2047 return;
2048 } else {
Artem Belevich42e19492016-03-02 18:28:50 +00002049 // We need to emit host-side 'shadows' for all global
2050 // device-side variables because the CUDA runtime needs their
2051 // size and host-side address in order to provide access to
2052 // their device-side incarnations.
2053
2054 // So device-only functions are the only things we skip.
2055 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2056 Global->hasAttr<CUDADeviceAttr>())
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002057 return;
Artem Belevich42e19492016-03-02 18:28:50 +00002058
2059 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2060 "Expected Variable or Function");
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002061 }
2062 }
2063
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002064 if (LangOpts.OpenMP) {
2065 // If this is OpenMP device, check if it is legal to emit this global
2066 // normally.
2067 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2068 return;
2069 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2070 if (MustBeEmitted(Global))
2071 EmitOMPDeclareReduction(DRD);
2072 return;
2073 }
2074 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002075
Chris Lattner45470942009-03-21 09:44:56 +00002076 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002077 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002078 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002079 if (!FD->doesThisDeclarationHaveABody()) {
2080 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2081 return;
2082
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002083 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00002084
2085 // Compute the function info and LLVM type.
2086 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2087 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2088
2089 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2090 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002091 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002092 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00002093 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002094 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002095 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
Artem Belevich42e19492016-03-02 18:28:50 +00002096 // We need to emit device-side global CUDA variables even if a
2097 // variable does not have a definition -- we still need to define
2098 // host-side shadow for it.
2099 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2100 !VD->hasDefinition() &&
2101 (VD->hasAttr<CUDAConstantAttr>() ||
2102 VD->hasAttr<CUDADeviceAttr>());
2103 if (!MustEmitForCuda &&
2104 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
Richard Smithd9b90092016-07-02 01:32:16 +00002105 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2106 // If this declaration may have caused an inline variable definition to
2107 // change linkage, make sure that it's emitted.
2108 if (Context.getInlineVariableDefinitionKind(VD) ==
2109 ASTContext::InlineVariableDefinitionKind::Strong)
2110 GetAddrOfGlobalVar(VD);
Douglas Gregorbeecd582009-04-21 17:11:58 +00002111 return;
Richard Smithd9b90092016-07-02 01:32:16 +00002112 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002113 }
2114
Hans Wennborg43a0f992015-01-10 01:19:48 +00002115 // Defer code generation to first use when possible, e.g. if this is an inline
2116 // function. If the global must always be emitted, do it eagerly if possible
2117 // to benefit from cache locality.
2118 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002119 // Emit the definition if it can't be deferred.
2120 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002121 return;
2122 }
John McCall70013b62010-07-15 23:40:35 +00002123
2124 // If we're deferring emission of a C++ variable with an
2125 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002126 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00002127 cast<VarDecl>(Global)->hasInit()) {
2128 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00002129 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00002130 }
Hans Wennborg43a0f992015-01-10 01:19:48 +00002131
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002132 StringRef MangledName = getMangledName(GD);
Sanjoy Das70a60512017-05-01 06:12:13 +00002133 if (GetGlobalValue(MangledName) != nullptr) {
Hans Wennborg43a0f992015-01-10 01:19:48 +00002134 // The value has already been used and should therefore be emitted.
Sanjoy Das70a60512017-05-01 06:12:13 +00002135 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002136 } else if (MustBeEmitted(Global)) {
2137 // The value must be emitted, but cannot be emitted eagerly.
2138 assert(!MayBeEmittedEagerly(Global));
Sanjoy Das70a60512017-05-01 06:12:13 +00002139 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002140 } else {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002141 // Otherwise, remember that we saw a deferred decl with this name. The
2142 // first use of the mangled name will cause it to move into
2143 // DeferredDeclsToEmit.
2144 DeferredDecls[MangledName] = GD;
2145 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002146}
2147
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002148// Check if T is a class type with a destructor that's not dllimport.
2149static bool HasNonDllImportDtor(QualType T) {
2150 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2151 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2152 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2153 return true;
2154
2155 return false;
2156}
2157
Rafael Espindolac5941352011-10-26 20:41:06 +00002158namespace {
2159 struct FunctionIsDirectlyRecursive :
2160 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2161 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002162 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00002163 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002164 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2165 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002166 }
2167 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2168
2169 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002170 const FunctionDecl *FD = E->getDirectCallee();
2171 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00002172 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002173 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2174 if (Attr && Name == Attr->getLabel()) {
2175 Result = true;
2176 return false;
2177 }
2178 unsigned BuiltinID = FD->getBuiltinID();
David Majnemer41011f62015-06-25 23:50:40 +00002179 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
Rafael Espindolac5941352011-10-26 20:41:06 +00002180 return true;
Eric Christopher02d5d862015-08-06 01:01:12 +00002181 StringRef BuiltinName = BI.getName(BuiltinID);
Nick Lewycky9ed5b152012-01-18 03:41:19 +00002182 if (BuiltinName.startswith("__builtin_") &&
2183 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002184 Result = true;
2185 return false;
2186 }
2187 return true;
2188 }
2189 };
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002190
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002191 // Make sure we're not referencing non-imported vars or functions.
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002192 struct DLLImportFunctionVisitor
2193 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2194 bool SafeToInline = true;
2195
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002196 bool shouldVisitImplicitCode() const { return true; }
2197
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002198 bool VisitVarDecl(VarDecl *VD) {
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002199 if (VD->getTLSKind()) {
2200 // A thread-local variable cannot be imported.
2201 SafeToInline = false;
2202 return SafeToInline;
2203 }
2204
2205 // A variable definition might imply a destructor call.
2206 if (VD->isThisDeclarationADefinition())
2207 SafeToInline = !HasNonDllImportDtor(VD->getType());
2208
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002209 return SafeToInline;
2210 }
2211
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002212 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2213 if (const auto *D = E->getTemporary()->getDestructor())
2214 SafeToInline = D->hasAttr<DLLImportAttr>();
2215 return SafeToInline;
2216 }
2217
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002218 bool VisitDeclRefExpr(DeclRefExpr *E) {
2219 ValueDecl *VD = E->getDecl();
2220 if (isa<FunctionDecl>(VD))
2221 SafeToInline = VD->hasAttr<DLLImportAttr>();
2222 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2223 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2224 return SafeToInline;
2225 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002226
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002227 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2228 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2229 return SafeToInline;
2230 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002231
Hans Wennborg251c2042017-01-23 23:57:50 +00002232 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2233 CXXMethodDecl *M = E->getMethodDecl();
2234 if (!M) {
2235 // Call through a pointer to member function. This is safe to inline.
2236 SafeToInline = true;
2237 } else {
2238 SafeToInline = M->hasAttr<DLLImportAttr>();
2239 }
2240 return SafeToInline;
2241 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002242
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002243 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2244 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2245 return SafeToInline;
2246 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002247
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002248 bool VisitCXXNewExpr(CXXNewExpr *E) {
2249 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2250 return SafeToInline;
2251 }
2252 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002253}
Rafael Espindolac5941352011-10-26 20:41:06 +00002254
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002255// isTriviallyRecursive - Check if this function calls another
2256// decl that, because of the asm attribute or the other decl being a builtin,
2257// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00002258bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002259CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2260 StringRef Name;
2261 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00002262 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002263 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2264 if (!Attr)
2265 return false;
2266 Name = Attr->getLabel();
2267 } else {
2268 Name = FD->getName();
2269 }
Rafael Espindolac5941352011-10-26 20:41:06 +00002270
David Majnemer64b0bdf2015-06-30 04:41:18 +00002271 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002272 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00002273 return Walker.Result;
2274}
2275
Hans Wennborg93f75472016-09-13 21:08:20 +00002276bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002277 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00002278 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002279 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00002280 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00002281 return false;
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002282
2283 if (F->hasAttr<DLLImportAttr>()) {
2284 // Check whether it would be safe to inline this dllimport function.
2285 DLLImportFunctionVisitor Visitor;
2286 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2287 if (!Visitor.SafeToInline)
2288 return false;
Hans Wennborg93f75472016-09-13 21:08:20 +00002289
2290 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2291 // Implicit destructor invocations aren't captured in the AST, so the
2292 // check above can't see them. Check for them manually here.
2293 for (const Decl *Member : Dtor->getParent()->decls())
2294 if (isa<FieldDecl>(Member))
2295 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2296 return false;
2297 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2298 if (HasNonDllImportDtor(B.getType()))
2299 return false;
2300 }
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002301 }
2302
Rafael Espindolac5941352011-10-26 20:41:06 +00002303 // PR9614. Avoid cases where the source code is lying to us. An available
2304 // externally function should have an equivalent function somewhere else,
2305 // but a function that calls itself is clearly not equivalent to the real
2306 // implementation.
2307 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002308 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00002309}
2310
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002311bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2312 return CodeGenOpts.OptimizationLevel > 0;
2313}
2314
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002315void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002316 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002317
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002318 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00002319 Context.getSourceManager(),
2320 "Generating code for declaration");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002321
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002322 if (isa<FunctionDecl>(D)) {
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002323 // At -O0, don't generate IR for functions with available_externally
Douglas Gregora700f682010-07-13 06:02:28 +00002324 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002325 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00002326 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00002327
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002328 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +00002329 // Make sure to emit the definition(s) before we emit the thunks.
2330 // This is necessary for the generation of certain thunks.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002331 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002332 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002333 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002334 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Eli Friedman49a94b12011-05-06 17:27:27 +00002335 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002336 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002337
Douglas Gregora700f682010-07-13 06:02:28 +00002338 if (Method->isVirtual())
2339 getVTables().EmitThunks(GD);
2340
Eli Friedman49a94b12011-05-06 17:27:27 +00002341 return;
Douglas Gregora700f682010-07-13 06:02:28 +00002342 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00002343
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002344 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00002345 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002346
2347 if (const auto *VD = dyn_cast<VarDecl>(D))
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002348 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002349
David Blaikie83d382b2011-09-23 05:06:16 +00002350 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00002351}
2352
Andrey Bokhankocab58582015-08-31 13:20:44 +00002353static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2354 llvm::Function *NewFn);
2355
Erich Keane281d20b2018-01-08 21:34:17 +00002356void CodeGenModule::emitMultiVersionFunctions() {
2357 for (GlobalDecl GD : MultiVersionFuncs) {
2358 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2359 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2360 getContext().forEachMultiversionedFunctionVersion(
2361 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2362 GlobalDecl CurGD{
2363 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2364 StringRef MangledName = getMangledName(CurGD);
2365 llvm::Constant *Func = GetGlobalValue(MangledName);
2366 if (!Func) {
2367 if (CurFD->isDefined()) {
2368 EmitGlobalFunctionDefinition(CurGD, nullptr);
2369 Func = GetGlobalValue(MangledName);
2370 } else {
2371 const CGFunctionInfo &FI =
2372 getTypes().arrangeGlobalDeclaration(GD);
2373 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2374 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2375 /*DontDefer=*/false, ForDefinition);
2376 }
2377 assert(Func && "This should have just been created");
2378 }
2379 Options.emplace_back(getTarget(), cast<llvm::Function>(Func),
2380 CurFD->getAttr<TargetAttr>()->parse());
2381 });
2382
2383 llvm::Function *ResolverFunc = cast<llvm::Function>(
2384 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
Erich Keane0a6fde42018-01-16 19:49:52 +00002385 if (supportsCOMDAT())
2386 ResolverFunc->setComdat(
2387 getModule().getOrInsertComdat(ResolverFunc->getName()));
Erich Keane281d20b2018-01-08 21:34:17 +00002388 std::stable_sort(
2389 Options.begin(), Options.end(),
2390 std::greater<CodeGenFunction::MultiVersionResolverOption>());
2391 CodeGenFunction CGF(*this);
2392 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2393 }
2394}
2395
2396/// If an ifunc for the specified mangled name is not in the module, create and
2397/// return an llvm IFunc Function with the specified type.
2398llvm::Constant *
2399CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
2400 StringRef MangledName,
2401 const FunctionDecl *FD) {
2402 std::string IFuncName = (MangledName + ".ifunc").str();
2403 if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
2404 return IFuncGV;
2405
2406 // Since this is the first time we've created this IFunc, make sure
2407 // that we put this multiversioned function into the list to be
2408 // replaced later.
2409 MultiVersionFuncs.push_back(GD);
2410
2411 std::string ResolverName = (MangledName + ".resolver").str();
2412 llvm::Type *ResolverType = llvm::FunctionType::get(
2413 llvm::PointerType::get(DeclTy,
2414 Context.getTargetAddressSpace(FD->getType())),
2415 false);
2416 llvm::Constant *Resolver =
2417 GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2418 /*ForVTable=*/false);
2419 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2420 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2421 GIF->setName(IFuncName);
2422 SetCommonAttributes(FD, GIF);
2423
2424 return GIF;
2425}
2426
Chris Lattnerd4808922009-03-22 21:03:39 +00002427/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2428/// module, create and return an llvm Function with the specified type. If there
2429/// is something in the module with the specified name, return it potentially
2430/// bitcasted to the right type.
2431///
2432/// If D is non-null, it specifies a decl that correspond to this. This is used
2433/// to set the attributes on the function when it is first created.
Reid Klecknerde864822017-03-21 16:57:30 +00002434llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2435 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2436 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2437 ForDefinition_t IsForDefinition) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002438 const Decl *D = GD.getDecl();
2439
Erich Keane281d20b2018-01-08 21:34:17 +00002440 // Any attempts to use a MultiVersion function should result in retrieving
2441 // the iFunc instead. Name Mangling will handle the rest of the changes.
2442 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002443 // For the device mark the function as one that should be emitted.
2444 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
Alexey Bataev6d944102018-05-02 15:45:28 +00002445 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002446 !DontDefer && !IsForDefinition) {
2447 const FunctionDecl *FDDef = FD->getDefinition();
2448 GlobalDecl GDDef;
2449 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2450 GDDef = GlobalDecl(CD, GD.getCtorType());
2451 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2452 GDDef = GlobalDecl(DD, GD.getDtorType());
2453 else
2454 GDDef = GlobalDecl(FDDef);
2455 addDeferredDeclToEmit(GDDef);
2456 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002457
Erich Keane281d20b2018-01-08 21:34:17 +00002458 if (FD->isMultiVersion() && FD->getAttr<TargetAttr>()->isDefaultVersion()) {
2459 UpdateMultiVersionNames(GD, FD);
2460 if (!IsForDefinition)
2461 return GetOrCreateMultiVersionIFunc(GD, Ty, MangledName, FD);
2462 }
2463 }
2464
Chris Lattnera85d68e2009-03-21 09:25:43 +00002465 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002466 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002467 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002468 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002469 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002470 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002471 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002472 }
2473
Hans Wennborg0a20f542014-08-29 00:16:06 +00002474 // Handle dropped DLL attributes.
Rafael Espindolac9643d82018-03-29 16:45:18 +00002475 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
Hans Wennborg0a20f542014-08-29 00:16:06 +00002476 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
Rafael Espindolac9643d82018-03-29 16:45:18 +00002477 setDSOLocal(Entry);
2478 }
Hans Wennborg0a20f542014-08-29 00:16:06 +00002479
Andrey Bokhankocab58582015-08-31 13:20:44 +00002480 // If there are two attempts to define the same mangled name, issue an
2481 // error.
2482 if (IsForDefinition && !Entry->isDeclaration()) {
2483 GlobalDecl OtherGD;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002484 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2485 // to make sure that we issue an error only once.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002486 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2487 (GD.getCanonicalDecl().getDecl() !=
2488 OtherGD.getCanonicalDecl().getDecl()) &&
2489 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00002490 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2491 << MangledName;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002492 getDiags().Report(OtherGD.getDecl()->getLocation(),
2493 diag::note_previous_definition);
2494 }
2495 }
2496
2497 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2498 (Entry->getType()->getElementType() == Ty)) {
Chris Lattnera85d68e2009-03-21 09:25:43 +00002499 return Entry;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002500 }
Mike Stump11289f42009-09-09 15:08:12 +00002501
Chris Lattnera85d68e2009-03-21 09:25:43 +00002502 // Make sure the result is of the correct type.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002503 // (If function is requested for a definition, we always need to create a new
2504 // function, not just return a bitcast.)
2505 if (!IsForDefinition)
2506 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00002507 }
Mike Stump11289f42009-09-09 15:08:12 +00002508
Eli Friedmancc522d92009-11-09 05:07:37 +00002509 // This function doesn't have a complete type (for example, the return
2510 // type is an incomplete struct). Use a fake type instead, and make
2511 // sure not to try to set attributes.
2512 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00002513
Chris Lattner2192fe52011-07-18 04:24:23 +00002514 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00002515 if (isa<llvm::FunctionType>(Ty)) {
2516 FTy = cast<llvm::FunctionType>(Ty);
2517 } else {
John McCall9dc0db22011-05-15 01:53:33 +00002518 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00002519 IsIncompleteFunction = true;
2520 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002521
2522 llvm::Function *F =
2523 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2524 Entry ? StringRef() : MangledName, &getModule());
2525
2526 // If we already created a function with the same mangled name (but different
2527 // type) before, take its name and add it to the list of functions to be
2528 // replaced with F at the end of CodeGen.
2529 //
2530 // This happens if there is a prototype for a function (e.g. "int f()") and
2531 // then a definition of a different type (e.g. "int f(int x)").
2532 if (Entry) {
2533 F->takeName(Entry);
2534
2535 // This might be an implementation of a function without a prototype, in
2536 // which case, try to do special replacement of calls which match the new
2537 // prototype. The really key thing here is that we also potentially drop
2538 // arguments from the call site so as to make a direct call, which makes the
2539 // inliner happier and suppresses a number of optimizer warnings (!) about
2540 // dropping arguments.
2541 if (!Entry->use_empty()) {
2542 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2543 Entry->removeDeadConstantUsers();
2544 }
2545
2546 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2547 F, Entry->getType()->getElementType()->getPointerTo());
2548 addGlobalValReplacement(Entry, BC);
2549 }
2550
John McCall7ec50432010-03-19 23:29:14 +00002551 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002552 if (D)
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002553 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Reid Klecknerde864822017-03-21 16:57:30 +00002554 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2555 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
Reid Kleckneree4930b2017-05-02 22:07:37 +00002556 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Bill Wendling9a677922013-01-23 00:21:06 +00002557 }
Eli Friedmancc522d92009-11-09 05:07:37 +00002558
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002559 if (!DontDefer) {
2560 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2561 // each other bottoming out with the base dtor. Therefore we emit non-base
2562 // dtors on usage, even if there is no dtor definition in the TU.
2563 if (D && isa<CXXDestructorDecl>(D) &&
2564 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2565 GD.getDtorType()))
Sanjoy Das70a60512017-05-01 06:12:13 +00002566 addDeferredDeclToEmit(GD);
John McCall357d0f32010-12-15 04:00:32 +00002567
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002568 // This is the first use or definition of a mangled name. If there is a
2569 // deferred decl with this name, remember that we need to emit it at the end
2570 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002571 auto DDI = DeferredDecls.find(MangledName);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002572 if (DDI != DeferredDecls.end()) {
2573 // Move the potentially referenced deferred decl to the
2574 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2575 // don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002576 addDeferredDeclToEmit(DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002577 DeferredDecls.erase(DDI);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002578
2579 // Otherwise, there are cases we have to worry about where we're
2580 // using a declaration for which we must emit a definition but where
2581 // we might not find a top-level definition:
2582 // - member functions defined inline in their classes
2583 // - friend functions defined inline in some class
2584 // - special member functions with implicit definitions
2585 // If we ever change our AST traversal to walk into class methods,
2586 // this will be unnecessary.
2587 //
2588 // We also don't emit a definition for a function if it's going to be an
Richard Smith46bb5812014-08-01 01:56:39 +00002589 // entry in a vtable, unless it's already marked as used.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002590 } else if (getLangOpts().CPlusPlus && D) {
2591 // Look for a declaration that's lexically in a record.
Richard Smith46bb5812014-08-01 01:56:39 +00002592 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2593 FD = FD->getPreviousDecl()) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002594 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Richard Smith46bb5812014-08-01 01:56:39 +00002595 if (FD->doesThisDeclarationHaveABody()) {
Sanjoy Das70a60512017-05-01 06:12:13 +00002596 addDeferredDeclToEmit(GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002597 break;
2598 }
John McCall357d0f32010-12-15 04:00:32 +00002599 }
Richard Smith46bb5812014-08-01 01:56:39 +00002600 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002601 }
Chris Lattner45470942009-03-21 09:44:56 +00002602 }
Mike Stump11289f42009-09-09 15:08:12 +00002603
John McCalld06fb862010-04-28 00:00:30 +00002604 // Make sure the result is of the requested type.
2605 if (!IsIncompleteFunction) {
2606 assert(F->getType()->getElementType() == Ty);
2607 return F;
2608 }
2609
Chris Lattnera5f58b02011-07-09 17:41:47 +00002610 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00002611 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002612}
2613
Chris Lattnerd4808922009-03-22 21:03:39 +00002614/// GetAddrOfFunction - Return the address of the given function. If Ty is
2615/// non-null, then this function will use the specified type if it has to
2616/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00002617llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00002618 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002619 bool ForVTable,
Andrey Bokhankocab58582015-08-31 13:20:44 +00002620 bool DontDefer,
John McCalld195d4c2016-11-30 23:25:13 +00002621 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002622 // If there was no specific requested type, just convert it now.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002623 if (!Ty) {
2624 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2625 auto CanonTy = Context.getCanonicalType(FD->getType());
2626 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2627 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002628
Reid Kleckner28103252018-03-16 22:20:57 +00002629 // Devirtualized destructor calls may come through here instead of via
2630 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2631 // of the complete destructor when necessary.
2632 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
2633 if (getTarget().getCXXABI().isMicrosoft() &&
2634 GD.getDtorType() == Dtor_Complete &&
2635 DD->getParent()->getNumVBases() == 0)
2636 GD = GlobalDecl(DD, Dtor_Base);
2637 }
2638
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002639 StringRef MangledName = getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002640 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +00002641 /*IsThunk=*/false, llvm::AttributeList(),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002642 IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002643}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002644
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002645static const FunctionDecl *
2646GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2647 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2648 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2649
2650 IdentifierInfo &CII = C.Idents.get(Name);
2651 for (const auto &Result : DC->lookup(&CII))
2652 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2653 return FD;
2654
2655 if (!C.getLangOpts().CPlusPlus)
2656 return nullptr;
2657
2658 // Demangle the premangled name from getTerminateFn()
2659 IdentifierInfo &CXXII =
Reid Klecknerfb931542018-03-16 20:36:49 +00002660 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002661 ? C.Idents.get("terminate")
2662 : C.Idents.get(Name);
2663
2664 for (const auto &N : {"__cxxabiv1", "std"}) {
2665 IdentifierInfo &NS = C.Idents.get(N);
2666 for (const auto &Result : DC->lookup(&NS)) {
2667 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2668 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2669 for (const auto &Result : LSD->lookup(&NS))
2670 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2671 break;
2672
2673 if (ND)
2674 for (const auto &Result : ND->lookup(&CXXII))
2675 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2676 return FD;
2677 }
2678 }
2679
2680 return nullptr;
2681}
2682
Chris Lattnerd4808922009-03-22 21:03:39 +00002683/// CreateRuntimeFunction - Create a new runtime function with the specified
2684/// type and name.
2685llvm::Constant *
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002686CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
Reid Klecknerde864822017-03-21 16:57:30 +00002687 llvm::AttributeList ExtraAttrs,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002688 bool Local) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002689 llvm::Constant *C =
2690 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002691 /*DontDefer=*/false, /*IsThunk=*/false,
2692 ExtraAttrs);
2693
2694 if (auto *F = dyn_cast<llvm::Function>(C)) {
2695 if (F->empty()) {
John McCall882987f2013-02-28 19:01:20 +00002696 F->setCallingConv(getRuntimeCC());
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002697
2698 if (!Local && getTriple().isOSBinFormatCOFF() &&
Martell Maloneb22e6002017-11-04 02:15:49 +00002699 !getCodeGenOpts().LTOVisibilityPublicStd &&
2700 !getTriple().isWindowsGNUEnvironment()) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002701 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2702 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2703 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2704 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2705 }
2706 }
Rafael Espindola3c9be622018-03-20 20:27:30 +00002707 setDSOLocal(F);
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002708 }
2709 }
2710
John McCall882987f2013-02-28 19:01:20 +00002711 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00002712}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002713
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002714/// CreateBuiltinFunction - Create a new builtin function with the specified
2715/// type and name.
2716llvm::Constant *
Reid Klecknerde864822017-03-21 16:57:30 +00002717CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2718 llvm::AttributeList ExtraAttrs) {
Rafael Espindola1193c372018-03-22 18:03:13 +00002719 return CreateRuntimeFunction(FTy, Name, ExtraAttrs, true);
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002720}
2721
Richard Smithe070fd22012-02-17 06:48:11 +00002722/// isTypeConstant - Determine whether an object of this type can be emitted
2723/// as a constant.
2724///
2725/// If ExcludeCtor is true, the duration when the object's constructor runs
2726/// will not be considered. The caller will need to verify that the object is
2727/// not written to during its construction.
2728bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2729 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00002730 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00002731
David Blaikiebbafb8a2012-03-11 07:00:24 +00002732 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00002733 if (const CXXRecordDecl *Record
2734 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2735 return ExcludeCtor && !Record->hasMutableFields() &&
2736 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00002737 }
Richard Smithe070fd22012-02-17 06:48:11 +00002738
Eli Friedmanb095e152009-12-11 21:23:03 +00002739 return true;
2740}
2741
Chris Lattnerd4808922009-03-22 21:03:39 +00002742/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2743/// create and return an llvm GlobalVariable with the specified type. If there
2744/// is something in the module with the specified name, return it potentially
2745/// bitcasted to the right type.
2746///
2747/// If D is non-null, it specifies a decl that correspond to this. This is used
2748/// to set the attributes on the global when it is first created.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002749///
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002750/// If IsForDefinition is true, it is guaranteed that an actual global with
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002751/// type Ty will be returned, not conversion of a variable with the same
2752/// mangled name but some other type.
John McCall7ec50432010-03-19 23:29:14 +00002753llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002754CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00002755 llvm::PointerType *Ty,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002756 const VarDecl *D,
John McCalld195d4c2016-11-30 23:25:13 +00002757 ForDefinition_t IsForDefinition) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00002758 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002759 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00002760 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002761 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002762 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002763 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002764 }
2765
Hans Wennborg0a20f542014-08-29 00:16:06 +00002766 // Handle dropped DLL attributes.
2767 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2768 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2769
Alexey Bataev03f270c2018-03-30 18:31:07 +00002770 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
2771 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
2772
Chris Lattnerd4808922009-03-22 21:03:39 +00002773 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00002774 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00002775
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002776 // If there are two attempts to define the same mangled name, issue an
2777 // error.
2778 if (IsForDefinition && !Entry->isDeclaration()) {
2779 GlobalDecl OtherGD;
2780 const VarDecl *OtherD;
2781
2782 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2783 // to make sure that we issue an error only once.
Artem Belevich2c323a02016-05-19 18:00:18 +00002784 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002785 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2786 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2787 OtherD->hasInit() &&
2788 DiagnosedConflictingDefinitions.insert(D).second) {
Richard Smithb5345102018-05-30 01:52:16 +00002789 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2790 << MangledName;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002791 getDiags().Report(OtherGD.getDecl()->getLocation(),
2792 diag::note_previous_definition);
2793 }
2794 }
2795
Chris Lattner3bfce182009-03-21 08:03:33 +00002796 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00002797 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2798 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2799
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002800 // (If global is requested for a definition, we always need to create a new
2801 // global, not just return a bitcast.)
2802 if (!IsForDefinition)
2803 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00002804 }
Mike Stump11289f42009-09-09 15:08:12 +00002805
Yaxun Liucbf647c2017-07-08 13:24:52 +00002806 auto AddrSpace = GetGlobalVarAddressSpace(D);
2807 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2808
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002809 auto *GV = new llvm::GlobalVariable(
2810 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002811 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Yaxun Liucbf647c2017-07-08 13:24:52 +00002812 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00002813
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002814 // If we already created a global with the same mangled name (but different
2815 // type) before, take its name and remove it from its parent.
2816 if (Entry) {
2817 GV->takeName(Entry);
2818
2819 if (!Entry->use_empty()) {
2820 llvm::Constant *NewPtrForOldDecl =
2821 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2822 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2823 }
2824
2825 Entry->eraseFromParent();
2826 }
2827
Chris Lattner45470942009-03-21 09:44:56 +00002828 // This is the first use or definition of a mangled name. If there is a
2829 // deferred decl with this name, remember that we need to emit it at the end
2830 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002831 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00002832 if (DDI != DeferredDecls.end()) {
2833 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2834 // list, and remove it from DeferredDecls (since we don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002835 addDeferredDeclToEmit(DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00002836 DeferredDecls.erase(DDI);
2837 }
Mike Stump11289f42009-09-09 15:08:12 +00002838
Chris Lattner3bfce182009-03-21 08:03:33 +00002839 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00002840 if (D) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00002841 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
2842 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
2843
Mike Stump18bb9282009-05-16 07:57:57 +00002844 // FIXME: This code is overly simple and should be merged with other global
2845 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00002846 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00002847
Ulrich Weigand46084382015-04-21 17:27:59 +00002848 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2849
Jake Ehrlichba874ad2017-11-29 00:54:20 +00002850 setLinkageForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00002851
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002852 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00002853 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00002854 CXXThreadLocals.push_back(D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +00002855 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002856 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00002857
Rafael Espindola3dd49812018-02-23 00:22:15 +00002858 setGVProperties(GV, D);
2859
Hans Wennborgfeedf852013-11-21 00:15:56 +00002860 // If required by the ABI, treat declarations of static data members with
2861 // inline initializers as definitions.
Hans Wennborg56fc62b2014-07-17 20:25:23 +00002862 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Hans Wennborgfeedf852013-11-21 00:15:56 +00002863 EmitGlobalVarDefinition(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +00002864 }
Robert Lyttonf80d6882014-05-02 09:33:30 +00002865
Erich Keane99fdfb62017-09-26 23:42:34 +00002866 // Emit section information for extern variables.
2867 if (D->hasExternalStorage()) {
2868 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
2869 GV->setSection(SA->getName());
2870 }
2871
Robert Lyttonf80d6882014-05-02 09:33:30 +00002872 // Handle XCore specific ABI requirements.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00002873 if (getTriple().getArch() == llvm::Triple::xcore &&
Robert Lyttonf80d6882014-05-02 09:33:30 +00002874 D->getLanguageLinkage() == CLanguageLinkage &&
2875 D->getType().isConstant(Context) &&
2876 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2877 GV->setSection(".cp.rodata");
Mehdi Amini7cb1b302017-09-05 03:58:35 +00002878
2879 // Check if we a have a const declaration with an initializer, we may be
2880 // able to emit it as available_externally to expose it's value to the
2881 // optimizer.
2882 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
2883 D->getType().isConstQualified() && !GV->hasInitializer() &&
2884 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
2885 const auto *Record =
2886 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
2887 bool HasMutableFields = Record && Record->hasMutableFields();
2888 if (!HasMutableFields) {
2889 const VarDecl *InitDecl;
2890 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2891 if (InitExpr) {
2892 ConstantEmitter emitter(*this);
2893 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
2894 if (Init) {
2895 auto *InitType = Init->getType();
2896 if (GV->getType()->getElementType() != InitType) {
2897 // The type of the initializer does not match the definition.
2898 // This happens when an initializer has a different type from
2899 // the type of the global (because of padding at the end of a
2900 // structure for instance).
2901 GV->setName(StringRef());
2902 // Make a new global with the correct type, this is now guaranteed
2903 // to work.
2904 auto *NewGV = cast<llvm::GlobalVariable>(
2905 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
2906
2907 // Erase the old global, since it is no longer used.
George Burgess IV00f70bd2018-03-01 05:43:23 +00002908 GV->eraseFromParent();
Mehdi Amini7cb1b302017-09-05 03:58:35 +00002909 GV = NewGV;
2910 } else {
2911 GV->setInitializer(Init);
2912 GV->setConstant(true);
2913 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
2914 }
2915 emitter.finalize(GV);
2916 }
2917 }
2918 }
2919 }
Chris Lattnerd4808922009-03-22 21:03:39 +00002920 }
Mike Stump11289f42009-09-09 15:08:12 +00002921
Alexander Richardson6d989432017-10-15 18:48:14 +00002922 LangAS ExpectedAS =
Yaxun Liucbf647c2017-07-08 13:24:52 +00002923 D ? D->getType().getAddressSpace()
Alexander Richardson6d989432017-10-15 18:48:14 +00002924 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
Benjamin Kramer6fbfdec2017-07-08 14:14:57 +00002925 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
2926 Ty->getPointerAddressSpace());
Yaxun Liucbf647c2017-07-08 13:24:52 +00002927 if (AddrSpace != ExpectedAS)
2928 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
2929 ExpectedAS, Ty);
Matt Arsenault00e65b22013-11-15 02:19:52 +00002930
2931 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002932}
2933
Andrey Bokhankocab58582015-08-31 13:20:44 +00002934llvm::Constant *
2935CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
John McCalld195d4c2016-11-30 23:25:13 +00002936 ForDefinition_t IsForDefinition) {
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002937 const Decl *D = GD.getDecl();
2938 if (isa<CXXConstructorDecl>(D))
2939 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002940 getFromCtorType(GD.getCtorType()),
2941 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2942 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002943 else if (isa<CXXDestructorDecl>(D))
2944 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002945 getFromDtorType(GD.getDtorType()),
2946 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2947 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002948 else if (isa<CXXMethodDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00002949 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002950 cast<CXXMethodDecl>(D));
Andrey Bokhankocab58582015-08-31 13:20:44 +00002951 auto Ty = getTypes().GetFunctionType(*FInfo);
2952 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2953 IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002954 } else if (isa<FunctionDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00002955 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2956 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2957 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2958 IsForDefinition);
2959 } else
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002960 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002961 IsForDefinition);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002962}
Chris Lattnerd4808922009-03-22 21:03:39 +00002963
Anders Carlssonda80af32011-01-29 18:20:20 +00002964llvm::GlobalVariable *
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002965CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00002966 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00002967 llvm::GlobalValue::LinkageTypes Linkage) {
2968 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00002969 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00002970
Anders Carlssonda80af32011-01-29 18:20:20 +00002971 if (GV) {
2972 // Check if the variable has the right type.
2973 if (GV->getType()->getElementType() == Ty)
2974 return GV;
2975
2976 // Because C++ name mangling, the only way we can end up with an already
2977 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00002978 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00002979 OldGV = GV;
2980 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002981
Anders Carlssonda80af32011-01-29 18:20:20 +00002982 // Create a new variable.
2983 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00002984 Linkage, nullptr, Name);
2985
Anders Carlssonda80af32011-01-29 18:20:20 +00002986 if (OldGV) {
2987 // Replace occurrences of the old variable if needed.
2988 GV->takeName(OldGV);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002989
Anders Carlssonda80af32011-01-29 18:20:20 +00002990 if (!OldGV->use_empty()) {
2991 llvm::Constant *NewPtrForOldDecl =
2992 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2993 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2994 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002995
Anders Carlssonda80af32011-01-29 18:20:20 +00002996 OldGV->eraseFromParent();
2997 }
Rafael Espindolacb92c192015-01-15 23:18:01 +00002998
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002999 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3000 !GV->hasAvailableExternallyLinkage())
3001 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00003002
Anders Carlssonda80af32011-01-29 18:20:20 +00003003 return GV;
3004}
3005
Chris Lattnerd4808922009-03-22 21:03:39 +00003006/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3007/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00003008/// then it will be created with the specified type instead of whatever the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003009/// normal requested type would be. If IsForDefinition is true, it is guaranteed
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003010/// that an actual global with type Ty will be returned, not conversion of a
3011/// variable with the same mangled name but some other type.
Chris Lattnerd4808922009-03-22 21:03:39 +00003012llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003013 llvm::Type *Ty,
John McCalld195d4c2016-11-30 23:25:13 +00003014 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00003015 assert(D->hasGlobalStorage() && "Not a global variable");
3016 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00003017 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00003018 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00003019
Chris Lattner2192fe52011-07-18 04:24:23 +00003020 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003021 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00003022
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003023 StringRef MangledName = getMangledName(D);
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003024 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00003025}
3026
3027/// CreateRuntimeVariable - Create a new runtime global variable with the
3028/// specified type and name.
3029llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00003030CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003031 StringRef Name) {
Rafael Espindola6ab4ae42018-03-21 01:30:16 +00003032 auto *Ret =
3033 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
3034 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3035 return Ret;
Chris Lattnerd4808922009-03-22 21:03:39 +00003036}
3037
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003038void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3039 assert(!D->getInit() && "Cannot emit definite definitions here!");
3040
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003041 StringRef MangledName = getMangledName(D);
3042 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3043
3044 // We already have a definition, not declaration, with the same mangled name.
3045 // Emitting of declaration is not required (and actually overwrites emitted
3046 // definition).
3047 if (GV && !GV->isDeclaration())
3048 return;
3049
3050 // If we have not seen a reference to this variable yet, place it into the
3051 // deferred declarations table to be emitted if needed later.
3052 if (!MustBeEmitted(D) && !GV) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003053 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003054 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00003055 }
3056
3057 // The tentative definition is the only definition.
Reid Kleckner953fe032015-12-05 01:52:14 +00003058 EmitGlobalVarDefinition(D);
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003059}
3060
Chris Lattner2192fe52011-07-18 04:24:23 +00003061CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00003062 return Context.toCharUnitsFromBits(
3063 getDataLayout().getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00003064}
3065
Alexander Richardson6d989432017-10-15 18:48:14 +00003066LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3067 LangAS AddrSpace = LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003068 if (LangOpts.OpenCL) {
Alexander Richardson6d989432017-10-15 18:48:14 +00003069 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003070 assert(AddrSpace == LangAS::opencl_global ||
3071 AddrSpace == LangAS::opencl_constant ||
3072 AddrSpace == LangAS::opencl_local ||
3073 AddrSpace >= LangAS::FirstTargetAddressSpace);
3074 return AddrSpace;
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003075 }
3076
Yaxun Liucbf647c2017-07-08 13:24:52 +00003077 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3078 if (D && D->hasAttr<CUDAConstantAttr>())
3079 return LangAS::cuda_constant;
3080 else if (D && D->hasAttr<CUDASharedAttr>())
3081 return LangAS::cuda_shared;
3082 else
3083 return LangAS::cuda_device;
3084 }
3085
3086 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003087}
3088
Yaxun Liudaceb1e2018-05-14 19:20:12 +00003089LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3090 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3091 if (LangOpts.OpenCL)
3092 return LangAS::opencl_constant;
3093 if (auto AS = getTarget().getConstantAddressSpace())
3094 return AS.getValue();
3095 return LangAS::Default;
3096}
3097
3098// In address space agnostic languages, string literals are in default address
3099// space in AST. However, certain targets (e.g. amdgcn) request them to be
3100// emitted in constant address space in LLVM IR. To be consistent with other
3101// parts of AST, string literal global variables in constant address space
3102// need to be casted to default address space before being put into address
3103// map and referenced by other part of CodeGen.
3104// In OpenCL, string literals are in constant address space in AST, therefore
3105// they should not be casted to default address space.
3106static llvm::Constant *
3107castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3108 llvm::GlobalVariable *GV) {
3109 llvm::Constant *Cast = GV;
3110 if (!CGM.getLangOpts().OpenCL) {
3111 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3112 if (AS != LangAS::Default)
3113 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3114 CGM, GV, AS.getValue(), LangAS::Default,
3115 GV->getValueType()->getPointerTo(
3116 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3117 }
3118 }
3119 return Cast;
3120}
3121
Richard Smithdf931ce2013-04-06 05:00:46 +00003122template<typename SomeDecl>
3123void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3124 llvm::GlobalValue *GV) {
3125 if (!getLangOpts().CPlusPlus)
3126 return;
3127
3128 // Must have 'used' attribute, or else inline assembly can't rely on
3129 // the name existing.
3130 if (!D->template hasAttr<UsedAttr>())
3131 return;
3132
3133 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00003134 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00003135 return;
3136
3137 // Must be in an extern "C" context. Entities declared directly within
3138 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003139 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00003140 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00003141 return;
3142
3143 // OK, this is an internal linkage entity inside an extern "C" linkage
3144 // specification. Make a note of that so we can give it the "expected"
3145 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00003146 std::pair<StaticExternCMap::iterator, bool> R =
3147 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00003148
3149 // If we have multiple internal linkage entities with the same name
3150 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00003151 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00003152 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00003153}
3154
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003155static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3156 if (!CGM.supportsCOMDAT())
3157 return false;
3158
3159 if (D.hasAttr<SelectAnyAttr>())
3160 return true;
3161
3162 GVALinkage Linkage;
3163 if (auto *VD = dyn_cast<VarDecl>(&D))
3164 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3165 else
3166 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3167
3168 switch (Linkage) {
3169 case GVA_Internal:
3170 case GVA_AvailableExternally:
3171 case GVA_StrongExternal:
3172 return false;
3173 case GVA_DiscardableODR:
3174 case GVA_StrongODR:
3175 return true;
3176 }
3177 llvm_unreachable("No such linkage");
3178}
3179
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003180void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3181 llvm::GlobalObject &GO) {
3182 if (!shouldBeInCOMDAT(*this, D))
3183 return;
3184 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3185}
3186
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003187/// Pass IsTentative as true if you want to create a tentative definition.
3188void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3189 bool IsTentative) {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003190 // OpenCL global variables of sampler type are translated to function calls,
3191 // therefore no need to be translated.
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003192 QualType ASTTy = D->getType();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003193 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3194 return;
3195
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00003196 // If this is OpenMP device, check if it is legal to emit this global
3197 // normally.
3198 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3199 OpenMPRuntime->emitTargetGlobalVariable(D))
3200 return;
3201
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003202 llvm::Constant *Init = nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00003203 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3204 bool NeedsGlobalCtor = false;
3205 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00003206
Richard Smithdafff942012-01-14 04:30:29 +00003207 const VarDecl *InitDecl;
3208 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003209
John McCallde0fe072017-08-15 21:42:52 +00003210 Optional<ConstantEmitter> emitter;
3211
Artem Belevich97c01c32016-02-02 22:29:48 +00003212 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3213 // as part of their declaration." Sema has already checked for
3214 // error cases, so we just need to set Init to UndefValue.
3215 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
3216 D->hasAttr<CUDASharedAttr>())
Jingyue Wu284ebe22015-08-22 05:49:28 +00003217 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
Artem Belevich97c01c32016-02-02 22:29:48 +00003218 else if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00003219 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003220 // implicitly initialized with { 0 }.
3221 //
3222 // Note that tentative definitions are only emitted at the end of
3223 // a translation unit, so they should never have incomplete
3224 // type. In addition, EmitTentativeDefinition makes sure that we
3225 // never attempt to emit a tentative definition if a real one
3226 // exists. A use may still exists, however, so we still may need
3227 // to do a RAUW.
3228 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00003229 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003230 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003231 initializedGlobalDecl = GlobalDecl(D);
John McCallde0fe072017-08-15 21:42:52 +00003232 emitter.emplace(*this);
3233 Init = emitter->tryEmitForInitializer(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003234
Fariborz Jahanian63628032012-06-26 16:06:38 +00003235 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00003236 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00003237 if (D->getType()->isReferenceType())
3238 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00003239
David Blaikiebbafb8a2012-03-11 07:00:24 +00003240 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003241 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00003242 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003243 } else {
3244 ErrorUnsupported(D, "static initializer");
3245 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3246 }
John McCall70013b62010-07-15 23:40:35 +00003247 } else {
3248 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00003249 // initializer position (just in case this entry was delayed) if we
3250 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003251 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00003252 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00003253 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003254 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003255
Chris Lattner2192fe52011-07-18 04:24:23 +00003256 llvm::Type* InitType = Init->getType();
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003257 llvm::Constant *Entry =
John McCalld195d4c2016-11-30 23:25:13 +00003258 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
Mike Stump11289f42009-09-09 15:08:12 +00003259
Chris Lattner149927c2009-03-21 09:16:30 +00003260 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003261 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00003262 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00003263 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3264 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00003265 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00003266 Entry = CE->getOperand(0);
3267 }
Mike Stump11289f42009-09-09 15:08:12 +00003268
Chris Lattner149927c2009-03-21 09:16:30 +00003269 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003270 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003271
Chris Lattner149927c2009-03-21 09:16:30 +00003272 // We have a definition after a declaration with the wrong type.
3273 // We must make a new GlobalVariable* and update everything that used OldGV
3274 // (a declaration or tentative definition) with the new GlobalVariable*
3275 // (which will be a definition).
3276 //
3277 // This happens if there is a prototype for a global (e.g.
3278 // "extern int x[];") and then a definition of a different type (e.g.
3279 // "int x[10];"). This also happens when an initializer has a different type
3280 // from the type of the global (this happens with unions).
Yaxun Liucbf647c2017-07-08 13:24:52 +00003281 if (!GV || GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003282 GV->getType()->getAddressSpace() !=
Yaxun Liucbf647c2017-07-08 13:24:52 +00003283 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
Mike Stump11289f42009-09-09 15:08:12 +00003284
John McCall7ec50432010-03-19 23:29:14 +00003285 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003286 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00003287
Chris Lattner149927c2009-03-21 09:16:30 +00003288 // Make a new global with the correct type, this is now guaranteed to work.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003289 GV = cast<llvm::GlobalVariable>(
John McCalld195d4c2016-11-30 23:25:13 +00003290 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
Chris Lattnera85d68e2009-03-21 09:25:43 +00003291
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003292 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00003293 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00003294 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00003295 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003296
3297 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00003298 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00003299 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00003300
Richard Smithdf931ce2013-04-06 05:00:46 +00003301 MaybeHandleStaticInExternC(D, GV);
3302
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003303 if (D->hasAttr<AnnotateAttr>())
3304 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00003305
Artem Belevich42e19492016-03-02 18:28:50 +00003306 // Set the llvm linkage type as appropriate.
3307 llvm::GlobalValue::LinkageTypes Linkage =
3308 getLLVMLinkageVarDefinition(D, GV->isConstant());
3309
Jingyue Wu284ebe22015-08-22 05:49:28 +00003310 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3311 // the device. [...]"
3312 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3313 // __device__, declares a variable that: [...]
3314 // Is accessible from all the threads within the grid and from the host
3315 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3316 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
Artem Belevich42e19492016-03-02 18:28:50 +00003317 if (GV && LangOpts.CUDA) {
3318 if (LangOpts.CUDAIsDevice) {
3319 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3320 GV->setExternallyInitialized(true);
3321 } else {
3322 // Host-side shadows of external declarations of device-side
3323 // global variables become internal definitions. These have to
3324 // be internal in order to prevent name conflicts with global
3325 // host variables with the same name in a different TUs.
3326 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3327 Linkage = llvm::GlobalValue::InternalLinkage;
3328
3329 // Shadow variables and their properties must be registered
3330 // with CUDA runtime.
3331 unsigned Flags = 0;
3332 if (!D->hasDefinition())
3333 Flags |= CGCUDARuntime::ExternDeviceVar;
3334 if (D->hasAttr<CUDAConstantAttr>())
3335 Flags |= CGCUDARuntime::ConstantDeviceVar;
3336 getCUDARuntime().registerDeviceVar(*GV, Flags);
3337 } else if (D->hasAttr<CUDASharedAttr>())
3338 // __shared__ variables are odd. Shadows do get created, but
3339 // they are not registered with the CUDA runtime, so they
3340 // can't really be used to access their device-side
3341 // counterparts. It's not clear yet whether it's nvcc's bug or
3342 // a feature, but we've got to do the same for compatibility.
3343 Linkage = llvm::GlobalValue::InternalLinkage;
3344 }
Jingyue Wu284ebe22015-08-22 05:49:28 +00003345 }
John McCallde0fe072017-08-15 21:42:52 +00003346
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003347 GV->setInitializer(Init);
John McCallde0fe072017-08-15 21:42:52 +00003348 if (emitter) emitter->finalize(GV);
Chris Lattnerf49573d2009-08-05 05:20:29 +00003349
3350 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00003351 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3352 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00003353
Hans Wennborg899ded92014-10-16 20:52:46 +00003354 // If it is in a read-only section, mark it 'constant'.
3355 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3356 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3357 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3358 GV->setConstant(true);
3359 }
3360
Ken Dyck160146e2010-01-27 17:10:57 +00003361 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00003362
David Majnemer35ab3282014-06-11 04:08:55 +00003363
Manman Ren68150262015-11-11 22:42:31 +00003364 // On Darwin, if the normal linkage of a C++ thread_local variable is
3365 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3366 // copies within a linkage unit; otherwise, the backing variable has
3367 // internal linkage and all accesses should just be calls to the
David Majnemer35ab3282014-06-11 04:08:55 +00003368 // Itanium-specified entry point, which has the normal linkage of the
Manman Ren68150262015-11-11 22:42:31 +00003369 // variable. This is to preserve the ability to change the implementation
3370 // behind the scenes.
David Majnemerbb525f7c2014-10-15 22:38:23 +00003371 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00003372 Context.getTargetInfo().getTriple().isOSDarwin() &&
Manman Ren68150262015-11-11 22:42:31 +00003373 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3374 !llvm::GlobalVariable::isWeakLinkage(Linkage))
David Majnemerbb525f7c2014-10-15 22:38:23 +00003375 Linkage = llvm::GlobalValue::InternalLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00003376
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003377 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00003378 if (D->hasAttr<DLLImportAttr>())
3379 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3380 else if (D->hasAttr<DLLExportAttr>())
3381 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00003382 else
3383 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00003384
Yaxun Liu402804b2016-12-15 08:09:08 +00003385 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
Chris Lattnerf49573d2009-08-05 05:20:29 +00003386 // common vars aren't constant even if declared const.
3387 GV->setConstant(false);
Yaxun Liu402804b2016-12-15 08:09:08 +00003388 // Tentative definition of global variables may be initialized with
3389 // non-zero null pointers. In this case they should have weak linkage
3390 // since common linkage must have zero initializer and must not have
3391 // explicit section therefore cannot have non-zero initial value.
3392 if (!GV->getInitializer()->isNullValue())
3393 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3394 }
Daniel Dunbard272cca2009-04-10 20:26:50 +00003395
Rafael Espindola502f65a2014-05-05 20:21:03 +00003396 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00003397
David Majnemerbb525f7c2014-10-15 22:38:23 +00003398 if (D->getTLSKind() && !GV->isThreadLocal()) {
3399 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003400 CXXThreadLocals.push_back(D);
David Majnemerbb525f7c2014-10-15 22:38:23 +00003401 setTLSMode(GV, *D);
3402 }
3403
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003404 maybeSetTrivialComdat(*D, *GV);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003405
John McCallcdf7ef52010-11-06 09:44:32 +00003406 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00003407 if (NeedsGlobalCtor || NeedsGlobalDtor)
3408 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00003409
Alexey Samsonov4b8de112014-08-01 21:35:28 +00003410 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany28a26c82012-08-21 06:53:28 +00003411
Sanjiv Gupta158143a2008-06-05 08:59:10 +00003412 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00003413 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00003414 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00003415 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003416}
Chris Lattner09153c02007-06-22 18:48:09 +00003417
David Majnemerc017d362014-08-05 00:01:13 +00003418static bool isVarDeclStrongDefinition(const ASTContext &Context,
Nico Weber608e7682015-04-15 23:04:24 +00003419 CodeGenModule &CGM, const VarDecl *D,
3420 bool NoCommon) {
David Majnemer9832a3d2014-04-10 16:53:16 +00003421 // Don't give variables common linkage if -fno-common was specified unless it
3422 // was overridden by a NoCommon attribute.
3423 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3424 return true;
3425
3426 // C11 6.9.2/2:
3427 // A declaration of an identifier for an object that has file scope without
3428 // an initializer, and without a storage-class specifier or with the
3429 // storage-class specifier static, constitutes a tentative definition.
3430 if (D->getInit() || D->hasExternalStorage())
3431 return true;
3432
3433 // A variable cannot be both common and exist in a section.
3434 if (D->hasAttr<SectionAttr>())
3435 return true;
3436
Javed Absar2a67c9e2017-06-05 10:11:57 +00003437 // A variable cannot be both common and exist in a section.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003438 // We don't try to determine which is the right section in the front-end.
Javed Absar2a67c9e2017-06-05 10:11:57 +00003439 // If no specialized section name is applicable, it will resort to default.
3440 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3441 D->hasAttr<PragmaClangDataSectionAttr>() ||
3442 D->hasAttr<PragmaClangRodataSectionAttr>())
3443 return true;
3444
David Majnemer9832a3d2014-04-10 16:53:16 +00003445 // Thread local vars aren't considered common linkage.
3446 if (D->getTLSKind())
3447 return true;
3448
3449 // Tentative definitions marked with WeakImportAttr are true definitions.
3450 if (D->hasAttr<WeakImportAttr>())
3451 return true;
3452
Nico Weber608e7682015-04-15 23:04:24 +00003453 // A variable cannot be both common and exist in a comdat.
3454 if (shouldBeInCOMDAT(CGM, *D))
3455 return true;
3456
Sanjay Patel2f9303a2016-06-30 21:02:40 +00003457 // Declarations with a required alignment do not have common linkage in MSVC
David Majnemerc017d362014-08-05 00:01:13 +00003458 // mode.
David Majnemer3f021502015-10-08 04:53:31 +00003459 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemere1a0b2e2015-02-03 08:49:32 +00003460 if (D->hasAttr<AlignedAttr>())
3461 return true;
3462 QualType VarType = D->getType();
3463 if (Context.isAlignmentRequired(VarType))
3464 return true;
3465
3466 if (const auto *RT = VarType->getAs<RecordType>()) {
3467 const RecordDecl *RD = RT->getDecl();
3468 for (const FieldDecl *FD : RD->fields()) {
3469 if (FD->isBitField())
3470 continue;
3471 if (FD->hasAttr<AlignedAttr>())
3472 return true;
3473 if (Context.isAlignmentRequired(FD->getType()))
3474 return true;
3475 }
3476 }
3477 }
David Majnemerc017d362014-08-05 00:01:13 +00003478
David Majnemer9832a3d2014-04-10 16:53:16 +00003479 return false;
3480}
3481
Hans Wennborg1a3a0742014-05-14 19:54:53 +00003482llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00003483 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003484 if (Linkage == GVA_Internal)
3485 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003486
3487 if (D->hasAttr<WeakAttr>()) {
3488 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003489 return llvm::GlobalVariable::WeakODRLinkage;
3490 else
3491 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003492 }
3493
3494 // We are guaranteed to have a strong definition somewhere else,
3495 // so we can use available_externally linkage.
3496 if (Linkage == GVA_AvailableExternally)
David Blaikie9ffe5a32017-01-30 05:00:26 +00003497 return llvm::GlobalValue::AvailableExternallyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003498
David Majnemer27d69db2014-04-28 22:17:59 +00003499 // Note that Apple's kernel linker doesn't support symbol
3500 // coalescing, so we need to avoid linkonce and weak linkages there.
3501 // Normally, this means we just map to internal, but for explicit
3502 // instantiations we'll map to external.
3503
3504 // In C++, the compiler has to emit a definition in every translation unit
3505 // that references the function. We should use linkonce_odr because
3506 // a) if all references in this translation unit are optimized away, we
3507 // don't need to codegen it. b) if the function persists, it needs to be
3508 // merged with other definitions. c) C++ has the ODR, so we know the
3509 // definition is dependable.
3510 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00003511 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00003512 : llvm::Function::InternalLinkage;
3513
3514 // An explicit instantiation of a template has weak linkage, since
3515 // explicit instantiations can occur in multiple translation units
3516 // and must all be equivalent. However, we are not allowed to
3517 // throw away these explicit instantiations.
Justin Lebar27ee1302016-06-30 18:41:33 +00003518 //
3519 // We don't currently support CUDA device code spread out across multiple TUs,
3520 // so say that CUDA templates are either external (for kernels) or internal.
3521 // This lets llvm perform aggressive inter-procedural optimizations.
3522 if (Linkage == GVA_StrongODR) {
3523 if (Context.getLangOpts().AppleKext)
3524 return llvm::Function::ExternalLinkage;
3525 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3526 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3527 : llvm::Function::InternalLinkage;
3528 return llvm::Function::WeakODRLinkage;
3529 }
David Majnemer27d69db2014-04-28 22:17:59 +00003530
David Majnemer27d69db2014-04-28 22:17:59 +00003531 // C++ doesn't have tentative definitions and thus cannot have common
3532 // linkage.
3533 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Nico Weber608e7682015-04-15 23:04:24 +00003534 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
David Majnemerc017d362014-08-05 00:01:13 +00003535 CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00003536 return llvm::GlobalVariable::CommonLinkage;
3537
David Majnemer27d69db2014-04-28 22:17:59 +00003538 // selectany symbols are externally visible, so use weak instead of
3539 // linkonce. MSVC optimizes away references to const selectany globals, so
3540 // all definitions should be the same and ODR linkage should be used.
3541 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3542 if (D->hasAttr<SelectAnyAttr>())
3543 return llvm::GlobalVariable::WeakODRLinkage;
3544
3545 // Otherwise, we have strong external linkage.
3546 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003547 return llvm::GlobalVariable::ExternalLinkage;
3548}
3549
David Majnemer27d69db2014-04-28 22:17:59 +00003550llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3551 const VarDecl *VD, bool IsConstant) {
3552 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00003553 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00003554}
3555
John McCall49954ca2012-12-12 22:21:47 +00003556/// Replace the uses of a function that was declared with a non-proto type.
3557/// We want to silently drop extra arguments from call sites
3558static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3559 llvm::Function *newFn) {
3560 // Fast path.
3561 if (old->use_empty()) return;
3562
3563 llvm::Type *newRetTy = newFn->getReturnType();
3564 SmallVector<llvm::Value*, 4> newArgs;
David Majnemer0b17d442015-12-15 21:27:59 +00003565 SmallVector<llvm::OperandBundleDef, 1> newBundles;
John McCall49954ca2012-12-12 22:21:47 +00003566
3567 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3568 ui != ue; ) {
3569 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003570 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00003571
3572 // Recognize and replace uses of bitcasts. Most calls to
3573 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003574 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00003575 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3576 replaceUsesOfNonProtoConstant(bitcast, newFn);
3577 continue;
3578 }
3579
3580 // Recognize calls to the function.
3581 llvm::CallSite callSite(user);
3582 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003583 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00003584
3585 // If the return types don't match exactly, then we can't
3586 // transform this call unless it's dead.
3587 if (callSite->getType() != newRetTy && !callSite->use_empty())
3588 continue;
3589
3590 // Get the call site's attribute list.
Reid Kleckner7f720332017-04-13 00:58:09 +00003591 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
Reid Klecknerde864822017-03-21 16:57:30 +00003592 llvm::AttributeList oldAttrs = callSite.getAttributes();
John McCall49954ca2012-12-12 22:21:47 +00003593
John McCall49954ca2012-12-12 22:21:47 +00003594 // If the function was passed too few arguments, don't transform.
3595 unsigned newNumArgs = newFn->arg_size();
3596 if (callSite.arg_size() < newNumArgs) continue;
3597
3598 // If extra arguments were passed, we silently drop them.
3599 // If any of the types mismatch, we don't transform.
3600 unsigned argNo = 0;
3601 bool dontTransform = false;
Reid Kleckner7f720332017-04-13 00:58:09 +00003602 for (llvm::Argument &A : newFn->args()) {
3603 if (callSite.getArgument(argNo)->getType() != A.getType()) {
John McCall49954ca2012-12-12 22:21:47 +00003604 dontTransform = true;
3605 break;
3606 }
3607
3608 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00003609 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
Reid Kleckner7f720332017-04-13 00:58:09 +00003610 argNo++;
John McCall49954ca2012-12-12 22:21:47 +00003611 }
3612 if (dontTransform)
3613 continue;
3614
John McCall49954ca2012-12-12 22:21:47 +00003615 // Okay, we can transform this. Create the new call instruction and copy
3616 // over the required information.
3617 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3618
David Majnemer0b17d442015-12-15 21:27:59 +00003619 // Copy over any operand bundles.
3620 callSite.getOperandBundlesAsDefs(newBundles);
3621
John McCall49954ca2012-12-12 22:21:47 +00003622 llvm::CallSite newCall;
3623 if (callSite.isCall()) {
David Majnemer0b17d442015-12-15 21:27:59 +00003624 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003625 callSite.getInstruction());
3626 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003627 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCall49954ca2012-12-12 22:21:47 +00003628 newCall = llvm::InvokeInst::Create(newFn,
3629 oldInvoke->getNormalDest(),
3630 oldInvoke->getUnwindDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003631 newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003632 callSite.getInstruction());
3633 }
3634 newArgs.clear(); // for the next iteration
3635
3636 if (!newCall->getType()->isVoidTy())
3637 newCall->takeName(callSite.getInstruction());
Reid Kleckner7f720332017-04-13 00:58:09 +00003638 newCall.setAttributes(llvm::AttributeList::get(
3639 newFn->getContext(), oldAttrs.getFnAttributes(),
3640 oldAttrs.getRetAttributes(), newArgAttrs));
John McCall49954ca2012-12-12 22:21:47 +00003641 newCall.setCallingConv(callSite.getCallingConv());
3642
3643 // Finally, remove the old call, replacing any uses with the new one.
3644 if (!callSite->use_empty())
3645 callSite->replaceAllUsesWith(newCall.getInstruction());
3646
3647 // Copy debug location attached to CI.
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00003648 if (callSite->getDebugLoc())
John McCall49954ca2012-12-12 22:21:47 +00003649 newCall->setDebugLoc(callSite->getDebugLoc());
David Majnemer0b17d442015-12-15 21:27:59 +00003650
John McCall49954ca2012-12-12 22:21:47 +00003651 callSite->eraseFromParent();
3652 }
3653}
3654
Chris Lattner36797ab2009-05-05 06:16:31 +00003655/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3656/// implement a function with no prototype, e.g. "int foo() {}". If there are
3657/// existing call uses of the old function in the module, this adjusts them to
3658/// call the new function directly.
3659///
3660/// This is not just a cleanup: the always_inline pass requires direct calls to
3661/// functions to be able to inline them. If there is a bitcast in the way, it
3662/// won't inline them. Instcombine normally deletes these calls, but it isn't
3663/// run at -O0.
3664static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3665 llvm::Function *NewFn) {
3666 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00003667 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00003668
John McCall49954ca2012-12-12 22:21:47 +00003669 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00003670}
3671
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003672void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
David Majnemer60e5bdc2016-07-11 04:28:21 +00003673 auto DK = VD->isThisDeclarationADefinition();
3674 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3675 return;
3676
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003677 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3678 // If we have a definition, this might be a deferred decl. If the
3679 // instantiation is explicit, make sure we emit it at the end.
3680 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3681 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003682
3683 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00003684}
Daniel Dunbar9c426522008-07-29 23:18:29 +00003685
Rafael Espindolacd7743b2013-12-09 16:01:03 +00003686void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3687 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003688 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00003689
John McCall46288ef2011-03-09 08:12:35 +00003690 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00003691 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3692 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00003693
Chris Lattnereb7466d2009-05-12 20:58:15 +00003694 // Get or create the prototype for the function.
Andrey Bokhankocab58582015-08-31 13:20:44 +00003695 if (!GV || (GV->getType()->getElementType() != Ty))
3696 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3697 /*DontDefer=*/true,
John McCalld195d4c2016-11-30 23:25:13 +00003698 ForDefinition));
Mike Stump11289f42009-09-09 15:08:12 +00003699
Andrey Bokhankocab58582015-08-31 13:20:44 +00003700 // Already emitted.
3701 if (!GV->isDeclaration())
Renato Golinc640ff62015-04-15 08:44:40 +00003702 return;
Mike Stump11289f42009-09-09 15:08:12 +00003703
John McCall8e7cb6d2010-11-02 21:04:24 +00003704 // We need to set linkage and visibility on the function before
3705 // generating code for it because various parts of IR generation
3706 // want to propagate this information down (e.g. to local static
3707 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003708 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00003709 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003710
Rafael Espindolae033c8c2014-05-08 15:26:12 +00003711 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Rafael Espindolab7350042018-03-01 00:35:47 +00003712 setGVProperties(Fn, GD);
John McCall8e7cb6d2010-11-02 21:04:24 +00003713
Richard Smithdf931ce2013-04-06 05:00:46 +00003714 MaybeHandleStaticInExternC(D, Fn);
3715
Yaxun Liu4306f202018-04-20 17:01:03 +00003716
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003717 maybeSetTrivialComdat(*D, *Fn);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003718
John McCalla738c252011-03-09 04:27:21 +00003719 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00003720
Rafael Espindolae4e78132018-03-01 00:00:02 +00003721 setNonAliasAttributes(GD, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00003722 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00003723
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003724 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003725 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003726 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003727 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003728 if (D->hasAttr<AnnotateAttr>())
3729 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003730}
3731
John McCall7ec50432010-03-19 23:29:14 +00003732void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003733 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003734 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00003735 assert(AA && "Not an alias?");
3736
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003737 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00003738
Hal Finkel0e2b9752015-09-04 21:49:21 +00003739 if (AA->getAliasee() == MangledName) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003740 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Hal Finkel0e2b9752015-09-04 21:49:21 +00003741 return;
3742 }
3743
John McCall7ec50432010-03-19 23:29:14 +00003744 // If there is a definition in the module, then it wins over the alias.
3745 // This is dubious, but allow it to be safe. Just ignore the alias.
3746 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3747 if (Entry && !Entry->isDeclaration())
3748 return;
3749
Rafael Espindola208b5c02013-10-22 19:26:13 +00003750 Aliases.push_back(GD);
3751
Chris Lattner2192fe52011-07-18 04:24:23 +00003752 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00003753
3754 // Create a reference to the named value. This ensures that it is emitted
3755 // if a deferred decl.
3756 llvm::Constant *Aliasee;
3757 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00003758 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00003759 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00003760 else
John McCall7ec50432010-03-19 23:29:14 +00003761 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00003762 llvm::PointerType::getUnqual(DeclTy),
David Majnemerbb525f7c2014-10-15 22:38:23 +00003763 /*D=*/nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00003764
3765 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00003766 auto *GA = llvm::GlobalAlias::create(
David Blaikie2a791d72015-09-14 18:38:22 +00003767 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00003768
Chris Lattner54041692009-03-22 21:47:11 +00003769 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00003770 if (GA->getAliasee() == Entry) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003771 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Rafael Espindolab2633b92014-05-16 19:35:48 +00003772 return;
3773 }
3774
John McCall7ec50432010-03-19 23:29:14 +00003775 assert(Entry->isDeclaration());
3776
Chris Lattner54041692009-03-22 21:47:11 +00003777 // If there is a declaration in the module, then we had an extern followed
3778 // by the alias, as in:
3779 // extern int test6();
3780 // ...
3781 // int test6() __attribute__((alias("test7")));
3782 //
3783 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00003784 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003785
Owen Andersonade90fd2009-07-29 18:54:39 +00003786 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00003787 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00003788 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00003789 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00003790 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00003791 }
Mike Stump11289f42009-09-09 15:08:12 +00003792
Daniel Dunbar38932572009-04-14 08:05:55 +00003793 // Set attributes which are particular to an alias; this is a
3794 // specialization of the attributes which may be set on a global
3795 // variable/function.
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00003796 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3797 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00003798 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3799 }
3800
David Majnemerbb525f7c2014-10-15 22:38:23 +00003801 if (const auto *VD = dyn_cast<VarDecl>(D))
3802 if (VD->getTLSKind())
3803 setTLSMode(GA, *VD);
3804
Rafael Espindolab7350042018-03-01 00:35:47 +00003805 SetCommonAttributes(GD, GA);
Chris Lattner54041692009-03-22 21:47:11 +00003806}
3807
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003808void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3809 const auto *D = cast<ValueDecl>(GD.getDecl());
3810 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3811 assert(IFA && "Not an ifunc?");
3812
3813 StringRef MangledName = getMangledName(GD);
3814
3815 if (IFA->getResolver() == MangledName) {
3816 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3817 return;
3818 }
3819
3820 // Report an error if some definition overrides ifunc.
3821 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3822 if (Entry && !Entry->isDeclaration()) {
3823 GlobalDecl OtherGD;
3824 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3825 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00003826 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
3827 << MangledName;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003828 Diags.Report(OtherGD.getDecl()->getLocation(),
3829 diag::note_previous_definition);
3830 }
3831 return;
3832 }
3833
3834 Aliases.push_back(GD);
3835
3836 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3837 llvm::Constant *Resolver =
3838 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3839 /*ForVTable=*/false);
3840 llvm::GlobalIFunc *GIF =
3841 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3842 "", Resolver, &getModule());
3843 if (Entry) {
3844 if (GIF->getResolver() == Entry) {
3845 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3846 return;
3847 }
3848 assert(Entry->isDeclaration());
3849
3850 // If there is a declaration in the module, then we had an extern followed
3851 // by the ifunc, as in:
3852 // extern int test();
3853 // ...
3854 // int test() __attribute__((ifunc("resolver")));
3855 //
3856 // Remove it and replace uses of it with the ifunc.
3857 GIF->takeName(Entry);
3858
3859 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3860 Entry->getType()));
3861 Entry->eraseFromParent();
3862 } else
3863 GIF->setName(MangledName);
3864
Rafael Espindola75c649c2018-03-01 00:06:55 +00003865 SetCommonAttributes(GD, GIF);
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003866}
3867
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003868llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00003869 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00003870 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003871 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00003872}
Chris Lattner1eec6602007-08-31 04:31:45 +00003873
David Blaikie2e804282015-04-05 22:47:07 +00003874static llvm::StringMapEntry<llvm::GlobalVariable *> &
3875GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3876 const StringLiteral *Literal, bool TargetIsLSB,
3877 bool &IsUTF16, unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003878 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003879 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00003880
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00003881 // Check for simple case.
3882 if (!Literal->containsNonAsciiOrNull()) {
3883 StringLength = NumBytes;
David Blaikie13156b62014-11-19 03:06:06 +00003884 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00003885 }
3886
Bill Wendling82b87f12012-03-30 00:26:17 +00003887 // Otherwise, convert the UTF8 literals into a string of shorts.
3888 IsUTF16 = true;
3889
Justin Lebar90910552016-09-30 00:38:45 +00003890 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3891 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3892 llvm::UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00003893
Justin Lebar90910552016-09-30 00:38:45 +00003894 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3895 ToPtr + NumBytes, llvm::strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00003896
Daniel Dunbar91ade142009-07-23 23:41:22 +00003897 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00003898 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00003899
Bill Wendling82b87f12012-03-30 00:26:17 +00003900 // Add an explicit null.
3901 *ToPtr = 0;
David Blaikie13156b62014-11-19 03:06:06 +00003902 return *Map.insert(std::make_pair(
3903 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3904 (StringLength + 1) * 2),
3905 nullptr)).first;
Daniel Dunbar64509b22009-07-23 22:52:48 +00003906}
3907
John McCall7f416cc2015-09-08 08:05:57 +00003908ConstantAddress
Daniel Dunbar64509b22009-07-23 22:52:48 +00003909CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3910 unsigned StringLength = 0;
3911 bool isUTF16 = false;
David Blaikie2e804282015-04-05 22:47:07 +00003912 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3913 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3914 getDataLayout().isLittleEndian(), isUTF16,
3915 StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00003916
David Blaikie13156b62014-11-19 03:06:06 +00003917 if (auto *C = Entry.second)
John McCall7f416cc2015-09-08 08:05:57 +00003918 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Mike Stump11289f42009-09-09 15:08:12 +00003919
Chris Lattnerece04092012-02-07 00:39:47 +00003920 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00003921 llvm::Constant *Zeros[] = { Zero, Zero };
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003922
Chris Lattneraa64ca22009-07-16 16:48:25 +00003923 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00003924 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003925 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00003926 Ty = llvm::ArrayType::get(Ty, 0);
Rafael Espindoladca06022018-03-20 15:48:00 +00003927 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(
3928 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"));
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003929
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003930 if (getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003931 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3932 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3933 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003934
3935 const VarDecl *VD = nullptr;
3936 for (const auto &Result : DC->lookup(&II))
3937 if ((VD = dyn_cast<VarDecl>(Result)))
3938 break;
3939
3940 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
Rafael Espindoladca06022018-03-20 15:48:00 +00003941 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3942 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003943 } else {
Rafael Espindoladca06022018-03-20 15:48:00 +00003944 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3945 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003946 }
3947 }
Rafael Espindoladca06022018-03-20 15:48:00 +00003948 setDSOLocal(GV);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003949
Daniel Dunbard644ad62008-08-23 18:37:06 +00003950 // Decay array -> ptr
Saleem Abdulrasool4fab7452016-09-11 01:25:15 +00003951 CFConstantStringClassRef =
3952 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003953 }
Mike Stump11289f42009-09-09 15:08:12 +00003954
Anders Carlssonc2480a52008-11-15 18:54:24 +00003955 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00003956
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003957 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00003958
John McCall23c9dc62016-11-28 22:18:27 +00003959 ConstantInitBuilder Builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003960 auto Fields = Builder.beginStruct(STy);
Douglas Gregor91f84212008-12-11 16:49:14 +00003961
Anders Carlssonb04ea612007-08-21 00:21:21 +00003962 // Class pointer.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003963 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
Mike Stump11289f42009-09-09 15:08:12 +00003964
Anders Carlssonb04ea612007-08-21 00:21:21 +00003965 // Flags.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003966 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
Anders Carlsson157c3212009-08-16 05:55:31 +00003967
Anders Carlssonb04ea612007-08-21 00:21:21 +00003968 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00003969 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00003970 if (isUTF16) {
Craig Topperc005cc02015-09-27 03:44:08 +00003971 auto Arr = llvm::makeArrayRef(
David Blaikie13156b62014-11-19 03:06:06 +00003972 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3973 Entry.first().size() / 2);
Bill Wendling82b87f12012-03-30 00:26:17 +00003974 C = llvm::ConstantDataArray::get(VMContext, Arr);
3975 } else {
David Blaikie13156b62014-11-19 03:06:06 +00003976 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling82b87f12012-03-30 00:26:17 +00003977 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00003978
Bill Wendling86131f22012-01-10 08:46:39 +00003979 // Note: -fwritable-strings doesn't make the backing store strings of
3980 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003981 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00003982 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3983 llvm::GlobalValue::PrivateLinkage, C, ".str");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003984 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigandfa806422013-05-06 16:23:57 +00003985 // Don't enforce the target's minimum global alignment, since the only use
3986 // of the string is via this class initializer.
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003987 CharUnits Align = isUTF16
3988 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3989 : getContext().getTypeAlignInChars(getContext().CharTy);
3990 GV->setAlignment(Align.getQuantity());
3991
3992 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3993 // Without it LLVM can merge the string with a non unnamed_addr one during
3994 // LTO. Doing that changes the section it ends in, which surprises ld64.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003995 if (getTriple().isOSBinFormatMachO())
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003996 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3997 : "__TEXT,__cstring,cstring_literals");
Bill Wendling82b87f12012-03-30 00:26:17 +00003998
3999 // String.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004000 llvm::Constant *Str =
David Blaikied3c127e2015-05-07 17:27:56 +00004001 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00004002
Bill Wendling82b87f12012-03-30 00:26:17 +00004003 if (isUTF16)
4004 // Cast the UTF16 string to the correct type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004005 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4006 Fields.add(Str);
Bill Wendling82b87f12012-03-30 00:26:17 +00004007
Anders Carlssonb04ea612007-08-21 00:21:21 +00004008 // String length.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004009 auto Ty = getTypes().ConvertType(getContext().LongTy);
4010 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00004011
John McCall7f416cc2015-09-08 08:05:57 +00004012 CharUnits Alignment = getPointerAlign();
4013
Anders Carlssonb04ea612007-08-21 00:21:21 +00004014 // The struct.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004015 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4016 /*isConstant=*/false,
4017 llvm::GlobalVariable::PrivateLinkage);
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00004018 switch (getTriple().getObjectFormat()) {
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004019 case llvm::Triple::UnknownObjectFormat:
4020 llvm_unreachable("unknown file format");
4021 case llvm::Triple::COFF:
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004022 case llvm::Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00004023 case llvm::Triple::Wasm:
Saleem Abdulrasool0295f8c2016-07-09 01:59:51 +00004024 GV->setSection("cfstring");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004025 break;
4026 case llvm::Triple::MachO:
4027 GV->setSection("__DATA,__cfstring");
4028 break;
4029 }
David Blaikie13156b62014-11-19 03:06:06 +00004030 Entry.second = GV;
Mike Stump11289f42009-09-09 15:08:12 +00004031
John McCall7f416cc2015-09-08 08:05:57 +00004032 return ConstantAddress(GV, Alignment);
Anders Carlssonb04ea612007-08-21 00:21:21 +00004033}
Chris Lattnerfb300092007-11-28 05:34:05 +00004034
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +00004035bool CodeGenModule::getExpressionLocationsEnabled() const {
4036 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4037}
4038
Douglas Gregor636e2002011-08-09 17:23:49 +00004039QualType CodeGenModule::getObjCFastEnumerationStateType() {
4040 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004041 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00004042 D->startDefinition();
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004043
Douglas Gregor636e2002011-08-09 17:23:49 +00004044 QualType FieldTypes[] = {
4045 Context.UnsignedLongTy,
4046 Context.getPointerType(Context.getObjCIdType()),
4047 Context.getPointerType(Context.UnsignedLongTy),
4048 Context.getConstantArrayType(Context.UnsignedLongTy,
4049 llvm::APInt(32, 5), ArrayType::Normal, 0)
4050 };
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004051
Douglas Gregor636e2002011-08-09 17:23:49 +00004052 for (size_t i = 0; i < 4; ++i) {
4053 FieldDecl *Field = FieldDecl::Create(Context,
4054 D,
4055 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004056 SourceLocation(), nullptr,
4057 FieldTypes[i], /*TInfo=*/nullptr,
4058 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00004059 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004060 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00004061 Field->setAccess(AS_public);
4062 D->addDecl(Field);
4063 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004064
Douglas Gregor636e2002011-08-09 17:23:49 +00004065 D->completeDefinition();
4066 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4067 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004068
Douglas Gregor636e2002011-08-09 17:23:49 +00004069 return ObjCFastEnumerationStateType;
4070}
4071
Eli Friedmanfcec6302011-11-01 02:23:42 +00004072llvm::Constant *
4073CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4074 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004075
Eli Friedmanfcec6302011-11-01 02:23:42 +00004076 // Don't emit it as the address of the string, emit the string data itself
4077 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00004078 if (E->getCharByteWidth() == 1) {
4079 SmallString<64> Str(E->getString());
4080
4081 // Resize the string to the right size, which is indicated by its type.
4082 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4083 Str.resize(CAT->getSize().getZExtValue());
4084 return llvm::ConstantDataArray::getString(VMContext, Str, false);
4085 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004086
4087 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00004088 llvm::Type *ElemTy = AType->getElementType();
4089 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00004090
4091 // Wide strings have either 2-byte or 4-byte elements.
4092 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4093 SmallVector<uint16_t, 32> Elements;
4094 Elements.reserve(NumElements);
4095
4096 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4097 Elements.push_back(E->getCodeUnit(i));
4098 Elements.resize(NumElements);
4099 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00004100 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004101
Chris Lattner02cb1712012-02-06 22:52:04 +00004102 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4103 SmallVector<uint32_t, 32> Elements;
4104 Elements.reserve(NumElements);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004105
Chris Lattner02cb1712012-02-06 22:52:04 +00004106 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4107 Elements.push_back(E->getCodeUnit(i));
4108 Elements.resize(NumElements);
4109 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00004110}
4111
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004112static llvm::GlobalVariable *
4113GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4114 CodeGenModule &CGM, StringRef GlobalName,
John McCall7f416cc2015-09-08 08:05:57 +00004115 CharUnits Alignment) {
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004116 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4117 CGM.getStringLiteralAddressSpace());
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004118
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004119 llvm::Module &M = CGM.getModule();
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004120 // Create a global variable for this string
4121 auto *GV = new llvm::GlobalVariable(
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004122 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4123 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +00004124 GV->setAlignment(Alignment.getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004125 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004126 if (GV->isWeakForLinker()) {
4127 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4128 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4129 }
Rafael Espindola0d40f122018-03-20 20:42:55 +00004130 CGM.setDSOLocal(GV);
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004131
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004132 return GV;
4133}
4134
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004135/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4136/// constant array for the given string literal.
John McCall7f416cc2015-09-08 08:05:57 +00004137ConstantAddress
Alexey Bataevec474782014-10-09 08:45:04 +00004138CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4139 StringRef Name) {
John McCall7f416cc2015-09-08 08:05:57 +00004140 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
James Molloye735b2b2014-05-09 16:28:56 +00004141
Richard Smith00db2f12014-07-29 21:20:12 +00004142 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4143 llvm::GlobalVariable **Entry = nullptr;
David Majnemer58e5bee2014-03-24 21:43:36 +00004144 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004145 Entry = &ConstantStringMap[C];
4146 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004147 if (Alignment.getQuantity() > GV->getAlignment())
4148 GV->setAlignment(Alignment.getQuantity());
4149 return ConstantAddress(GV, Alignment);
David Majnemer58e5bee2014-03-24 21:43:36 +00004150 }
Eli Friedman49ddc5f2009-11-16 05:55:46 +00004151 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00004152
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004153 SmallString<256> MangledNameBuffer;
4154 StringRef GlobalVariableName;
4155 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00004156
Evgeniy Stepanovc69e0672018-06-26 23:10:48 +00004157 // Mangle the string literal if the ABI allows for it. However, we cannot
4158 // do this if we are compiling with ASan or -fwritable-strings because they
4159 // rely on strings having normal linkage.
4160 if (!LangOpts.WritableStrings &&
4161 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4162 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004163 llvm::raw_svector_ostream Out(MangledNameBuffer);
4164 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
Evgeniy Stepanovc69e0672018-06-26 23:10:48 +00004165
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004166 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4167 GlobalVariableName = MangledNameBuffer;
4168 } else {
4169 LT = llvm::GlobalValue::PrivateLinkage;
Alexey Bataevec474782014-10-09 08:45:04 +00004170 GlobalVariableName = Name;
David Majnemer58e5bee2014-03-24 21:43:36 +00004171 }
4172
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004173 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4174 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004175 *Entry = GV;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00004176
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00004177 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4178 QualType());
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004179
4180 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4181 Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004182}
4183
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004184/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4185/// array for the given ObjCEncodeExpr node.
John McCall7f416cc2015-09-08 08:05:57 +00004186ConstantAddress
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004187CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4188 std::string Str;
4189 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00004190
4191 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004192}
4193
Alexey Samsonovadc90372014-06-04 20:25:57 +00004194/// GetAddrOfConstantCString - Returns a pointer to a character array containing
4195/// the literal and a terminating '\0' character.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004196/// The result has pointer to array type.
John McCall7f416cc2015-09-08 08:05:57 +00004197ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4198 const std::string &Str, const char *GlobalName) {
Alexey Samsonovadc90372014-06-04 20:25:57 +00004199 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall7f416cc2015-09-08 08:05:57 +00004200 CharUnits Alignment =
4201 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004202
Richard Smith00db2f12014-07-29 21:20:12 +00004203 llvm::Constant *C =
4204 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4205
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004206 // Don't share any string literals if strings aren't constant.
Richard Smith00db2f12014-07-29 21:20:12 +00004207 llvm::GlobalVariable **Entry = nullptr;
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004208 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004209 Entry = &ConstantStringMap[C];
4210 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004211 if (Alignment.getQuantity() > GV->getAlignment())
4212 GV->setAlignment(Alignment.getQuantity());
4213 return ConstantAddress(GV, Alignment);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004214 }
4215 }
4216
Daniel Dunbar08b216a2009-03-31 23:42:16 +00004217 // Get the default prefix if a name wasn't specified.
4218 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00004219 GlobalName = ".str";
Chris Lattnerfb300092007-11-28 05:34:05 +00004220 // Create a global variable for this.
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004221 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4222 GlobalName, Alignment);
4223 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004224 *Entry = GV;
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004225
4226 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4227 Alignment);
Chris Lattnerfb300092007-11-28 05:34:05 +00004228}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004229
John McCall7f416cc2015-09-08 08:05:57 +00004230ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00004231 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00004232 assert((E->getStorageDuration() == SD_Static ||
4233 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004234 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00004235
4236 // If we're not materializing a subobject of the temporary, keep the
4237 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00004238 QualType MaterializedType = Init->getType();
4239 if (Init == E->GetTemporaryExpr())
4240 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004241
John McCall7f416cc2015-09-08 08:05:57 +00004242 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4243
David Majnemer2dcef9e2015-08-13 23:50:15 +00004244 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
John McCall7f416cc2015-09-08 08:05:57 +00004245 return ConstantAddress(Slot, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004246
4247 // FIXME: If an externally-visible declaration extends multiple temporaries,
4248 // we need to give each temporary the same name in every translation unit (and
4249 // we also need to make the temporaries externally-visible).
4250 SmallString<256> Name;
4251 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00004252 getCXXABI().getMangleContext().mangleReferenceTemporary(
4253 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00004254
Craig Topper8a13c412014-05-21 05:09:00 +00004255 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004256 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00004257 // We might have a cached constant initializer for this temporary. Note
4258 // that this might have a different value from the value computed by
4259 // evaluating the initializer if the surrounding constant expression
4260 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00004261 Value = getContext().getMaterializedTemporaryValue(E, false);
4262 if (Value && Value->isUninit())
Craig Topper8a13c412014-05-21 05:09:00 +00004263 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004264 }
4265
Richard Smitha509f2f2013-06-14 03:07:01 +00004266 // Try evaluating it now, it might have a constant initializer.
4267 Expr::EvalResult EvalResult;
4268 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4269 !EvalResult.hasSideEffects())
4270 Value = &EvalResult.Val;
4271
Alexander Richardson6d989432017-10-15 18:48:14 +00004272 LangAS AddrSpace =
John McCallde0fe072017-08-15 21:42:52 +00004273 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4274
4275 Optional<ConstantEmitter> emitter;
Craig Topper8a13c412014-05-21 05:09:00 +00004276 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00004277 bool Constant = false;
4278 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00004279 if (Value) {
4280 // The temporary has a constant initializer, use it.
John McCallde0fe072017-08-15 21:42:52 +00004281 emitter.emplace(*this);
4282 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4283 MaterializedType);
Richard Smitha509f2f2013-06-14 03:07:01 +00004284 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4285 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004286 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00004287 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00004288 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00004289 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00004290 }
4291
4292 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00004293 llvm::GlobalValue::LinkageTypes Linkage =
4294 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004295 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4296 const VarDecl *InitVD;
4297 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4298 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4299 // Temporaries defined inside a class get linkonce_odr linkage because the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004300 // class can be defined in multiple translation units.
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004301 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4302 } else {
4303 // There is no need for this temporary to have external linkage if the
4304 // VarDecl has external linkage.
4305 Linkage = llvm::GlobalVariable::InternalLinkage;
4306 }
4307 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00004308 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004309 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00004310 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
Yaxun Liucbf647c2017-07-08 13:24:52 +00004311 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
John McCallde0fe072017-08-15 21:42:52 +00004312 if (emitter) emitter->finalize(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +00004313 setGVProperties(GV, VD);
John McCall7f416cc2015-09-08 08:05:57 +00004314 GV->setAlignment(Align.getQuantity());
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004315 if (supportsCOMDAT() && GV->isWeakForLinker())
4316 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smithe6c01442013-06-05 00:46:14 +00004317 if (VD->getTLSKind())
4318 setTLSMode(GV, *VD);
Yaxun Liucbf647c2017-07-08 13:24:52 +00004319 llvm::Constant *CV = GV;
4320 if (AddrSpace != LangAS::Default)
4321 CV = getTargetCodeGenInfo().performAddrSpaceCast(
4322 *this, GV, AddrSpace, LangAS::Default,
4323 Type->getPointerTo(
4324 getContext().getTargetAddressSpace(LangAS::Default)));
4325 MaterializedGlobalTemporaryMap[E] = CV;
4326 return ConstantAddress(CV, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004327}
4328
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004329/// EmitObjCPropertyImplementations - Emit information for synthesized
4330/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00004331void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004332 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004333 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004334 // Dynamic is just for type-checking.
4335 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4336 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4337
4338 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00004339 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004340 // we want, that just indicates if the decl came from a
4341 // property. What we want to know is if the method is defined in
4342 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004343 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004344 CodeGenFunction(*this).GenerateObjCGetter(
4345 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004346 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004347 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004348 CodeGenFunction(*this).GenerateObjCSetter(
4349 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004350 }
4351 }
4352}
4353
John McCall6a4fa522011-03-22 07:05:39 +00004354static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004355 const ObjCInterfaceDecl *iface = impl->getClassInterface();
4356 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00004357 ivar; ivar = ivar->getNextIvar())
4358 if (ivar->getType().isDestructedType())
4359 return true;
4360
4361 return false;
4362}
4363
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004364static bool AllTrivialInitializers(CodeGenModule &CGM,
4365 ObjCImplementationDecl *D) {
4366 CodeGenFunction CGF(CGM);
4367 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4368 E = D->init_end(); B != E; ++B) {
4369 CXXCtorInitializer *CtorInitExp = *B;
4370 Expr *Init = CtorInitExp->getInit();
4371 if (!CGF.isTrivialInitializer(Init))
4372 return false;
4373 }
4374 return true;
4375}
4376
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004377/// EmitObjCIvarInitializations - Emit information for ivar initialization
4378/// for an implementation.
4379void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00004380 // We might need a .cxx_destruct even if we don't have any ivar initializers.
4381 if (needsDestructMethod(D)) {
4382 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4383 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4384 ObjCMethodDecl *DTORMethod =
4385 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004386 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004387 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004388 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004389 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00004390 D->addInstanceMethod(DTORMethod);
4391 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00004392 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00004393 }
4394
4395 // If the implementation doesn't have any ivar initializers, we don't need
4396 // a .cxx_construct.
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004397 if (D->getNumIvarInitializers() == 0 ||
4398 AllTrivialInitializers(*this, D))
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004399 return;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004400
John McCall6a4fa522011-03-22 07:05:39 +00004401 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4402 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004403 // The constructor returns 'self'.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004404 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004405 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004406 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004407 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00004408 getContext().getObjCIdType(),
4409 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004410 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004411 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004412 /*isImplicitlyDeclared=*/true,
4413 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004414 ObjCMethodDecl::Required);
4415 D->addInstanceMethod(CTORMethod);
4416 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00004417 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004418}
4419
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004420// EmitLinkageSpec - Emit all declarations in a linkage spec.
4421void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00004422 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4423 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004424 ErrorUnsupported(LSD, "linkage spec");
4425 return;
4426 }
4427
Richard Smith8df390f2016-09-08 23:14:54 +00004428 EmitDeclContext(LSD);
4429}
4430
4431void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4432 for (auto *I : DC->decls()) {
4433 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4434 // are themselves considered "top-level", so EmitTopLevelDecl on an
4435 // ObjCImplDecl does not recursively visit them. We need to do that in
4436 // case they're nested inside another construct (LinkageSpecDecl /
4437 // ExportDecl) that does stop them from being considered "top-level".
Aaron Ballman629afae2014-03-07 19:56:05 +00004438 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004439 for (auto *M : OID->methods())
4440 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004441 }
Richard Smith8df390f2016-09-08 23:14:54 +00004442
Aaron Ballman629afae2014-03-07 19:56:05 +00004443 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004444 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004445}
4446
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004447/// EmitTopLevelDecl - Emit code for a single top level declaration.
4448void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00004449 // Ignore dependent declarations.
Richard Smith32b615c2018-02-01 00:28:36 +00004450 if (D->isTemplated())
Douglas Gregor70d83e22009-06-29 17:30:29 +00004451 return;
Mike Stump11289f42009-09-09 15:08:12 +00004452
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004453 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00004454 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00004455 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004456 case Decl::Function:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004457 EmitGlobal(cast<FunctionDecl>(D));
Alex Lorenzee024992014-08-04 18:41:51 +00004458 // Always provide some coverage mapping
4459 // even for the functions that aren't emitted.
4460 AddDeferredUnusedCoverageMapping(D);
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004461 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004462
Richard Smithada08882017-04-19 21:15:45 +00004463 case Decl::CXXDeductionGuide:
4464 // Function-like, but does not result in code emission.
4465 break;
4466
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004467 case Decl::Var:
Richard Smithbdb84f32016-07-22 23:36:59 +00004468 case Decl::Decomposition:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004469 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004470 EmitGlobal(cast<VarDecl>(D));
Richard Smithda383632016-08-15 01:33:41 +00004471 if (auto *DD = dyn_cast<DecompositionDecl>(D))
4472 for (auto *B : DD->bindings())
4473 if (auto *HD = B->getHoldingVar())
4474 EmitGlobal(HD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004475 break;
4476
John McCall32f44bd2011-04-12 01:01:22 +00004477 // Indirect fields from global anonymous structs and unions can be
4478 // ignored; only the actual variable requires IR gen support.
4479 case Decl::IndirectField:
4480 break;
4481
Anders Carlssonf7475242009-04-15 15:55:24 +00004482 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004483 case Decl::Namespace:
Richard Smith8df390f2016-09-08 23:14:54 +00004484 EmitDeclContext(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004485 break;
Richard Smithe1246122017-11-03 01:26:01 +00004486 case Decl::ClassTemplateSpecialization: {
4487 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4488 if (DebugInfo &&
4489 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4490 Spec->hasDefinition())
4491 DebugInfo->completeTemplateDefinition(*Spec);
4492 } LLVM_FALLTHROUGH;
Richard Smith62f19e72016-06-25 00:15:56 +00004493 case Decl::CXXRecord:
David Blaikie1ac9c982017-04-11 21:13:37 +00004494 if (DebugInfo) {
4495 if (auto *ES = D->getASTContext().getExternalSource())
4496 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4497 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4498 }
Richard Smith62f19e72016-06-25 00:15:56 +00004499 // Emit any static data members, they may be definitions.
4500 for (auto *I : cast<CXXRecordDecl>(D)->decls())
4501 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4502 EmitTopLevelDecl(I);
4503 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00004504 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00004505 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004506 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004507 case Decl::VarTemplate:
4508 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004509 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00004510 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00004511 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00004512 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00004513 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00004514 case Decl::Using: // using X; [C++]
4515 if (CGDebugInfo *DI = getModuleDebugInfo())
4516 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4517 return;
David Blaikief121b932013-05-20 22:50:41 +00004518 case Decl::NamespaceAlias:
4519 if (CGDebugInfo *DI = getModuleDebugInfo())
4520 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4521 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00004522 case Decl::UsingDirective: // using namespace X; [C++]
4523 if (CGDebugInfo *DI = getModuleDebugInfo())
4524 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4525 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00004526 case Decl::CXXConstructor:
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00004527 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00004528 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004529 case Decl::CXXDestructor:
Reid Klecknere7de47e2013-07-22 13:51:44 +00004530 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004531 break;
Anders Carlsson87835432009-06-11 21:22:55 +00004532
4533 case Decl::StaticAssert:
4534 // Nothing to do.
4535 break;
4536
Anders Carlssonf7475242009-04-15 15:55:24 +00004537 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00004538
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004539 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00004540 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00004541 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00004542 break;
4543
Douglas Gregorf6102672012-01-01 21:23:57 +00004544 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004545 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00004546 if (Proto->isThisDeclarationADefinition())
4547 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004548 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00004549 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004550
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004551 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004552 // Categories have properties but don't support synthesize so we
4553 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00004554 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004555 break;
4556
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004557 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004558 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004559 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004560 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00004561 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00004562 // Emit global variable debug information.
4563 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00004564 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00004565 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4566 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004567 break;
Mike Stump11289f42009-09-09 15:08:12 +00004568 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004569 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004570 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004571 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004572 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004573 CodeGenFunction(*this).GenerateObjCMethod(OMD);
4574 break;
4575 }
Mike Stump11289f42009-09-09 15:08:12 +00004576 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00004577 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004578 break;
4579
Nico Weber66220292016-03-02 17:28:48 +00004580 case Decl::PragmaComment: {
4581 const auto *PCD = cast<PragmaCommentDecl>(D);
4582 switch (PCD->getCommentKind()) {
4583 case PCK_Unknown:
4584 llvm_unreachable("unexpected pragma comment kind");
4585 case PCK_Linker:
4586 AppendLinkerOptions(PCD->getArg());
4587 break;
4588 case PCK_Lib:
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00004589 if (getTarget().getTriple().isOSBinFormatELF() &&
4590 !getTarget().getTriple().isPS4())
4591 AddELFLibDirective(PCD->getArg());
4592 else
4593 AddDependentLib(PCD->getArg());
Nico Weber66220292016-03-02 17:28:48 +00004594 break;
4595 case PCK_Compiler:
4596 case PCK_ExeStr:
4597 case PCK_User:
4598 break; // We ignore all of these.
4599 }
4600 break;
4601 }
4602
Nico Webercbbaeb12016-03-02 19:28:54 +00004603 case Decl::PragmaDetectMismatch: {
4604 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4605 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4606 break;
4607 }
4608
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004609 case Decl::LinkageSpec:
4610 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004611 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004612
4613 case Decl::FileScopeAsm: {
Artem Belevich0488d1e2015-04-27 18:52:00 +00004614 // File-scope asm is ignored during device-side CUDA compilation.
4615 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4616 break;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004617 // File-scope asm is ignored during device-side OpenMP compilation.
4618 if (LangOpts.OpenMPIsDevice)
4619 break;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004620 auto *AD = cast<FileScopeAsmDecl>(D);
Joerg Sonnenbergerdfd511e2015-03-13 00:54:30 +00004621 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004622 break;
4623 }
Mike Stump11289f42009-09-09 15:08:12 +00004624
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004625 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004626 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004627
Richard Smithdc1f0422016-07-20 19:10:16 +00004628 // If we've already imported this module, we're done.
4629 if (!ImportedModules.insert(Import->getImportedModule()))
Richard Smithc52efa72015-08-19 02:30:28 +00004630 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004631
Richard Smithdc1f0422016-07-20 19:10:16 +00004632 // Emit debug information for direct imports.
4633 if (!Import->getImportedOwningModule()) {
4634 if (CGDebugInfo *DI = getModuleDebugInfo())
4635 DI->EmitImportDecl(*Import);
4636 }
4637
Manman Ren3b5dbf22016-10-14 18:55:44 +00004638 // Find all of the submodules and emit the module initializers.
4639 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4640 SmallVector<clang::Module *, 16> Stack;
4641 Visited.insert(Import->getImportedModule());
4642 Stack.push_back(Import->getImportedModule());
4643
4644 while (!Stack.empty()) {
4645 clang::Module *Mod = Stack.pop_back_val();
4646 if (!EmittedModuleInitializers.insert(Mod).second)
4647 continue;
4648
4649 for (auto *D : Context.getModuleInitializers(Mod))
4650 EmitTopLevelDecl(D);
4651
4652 // Visit the submodules of this module.
4653 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4654 SubEnd = Mod->submodule_end();
4655 Sub != SubEnd; ++Sub) {
4656 // Skip explicit children; they need to be explicitly imported to emit
4657 // the initializers.
4658 if ((*Sub)->IsExplicit)
4659 continue;
4660
4661 if (Visited.insert(*Sub).second)
4662 Stack.push_back(*Sub);
4663 }
4664 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004665 break;
David Blaikie0e716b42014-03-03 23:48:23 +00004666 }
4667
Richard Smith8df390f2016-09-08 23:14:54 +00004668 case Decl::Export:
4669 EmitDeclContext(cast<ExportDecl>(D));
4670 break;
4671
Alexey Bataev97720002014-11-11 04:05:39 +00004672 case Decl::OMPThreadPrivate:
4673 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4674 break;
4675
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004676 case Decl::OMPDeclareReduction:
4677 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4678 break;
4679
Mike Stump11289f42009-09-09 15:08:12 +00004680 default:
Mike Stump18bb9282009-05-16 07:57:57 +00004681 // Make sure we handled everything we should, every other kind is a
4682 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4683 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004684 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Richard Smitha634ff22014-12-01 18:59:10 +00004685 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004686 }
4687}
John McCall09ae0322010-07-06 23:57:41 +00004688
Alex Lorenzee024992014-08-04 18:41:51 +00004689void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4690 // Do we need to generate coverage mapping?
4691 if (!CodeGenOpts.CoverageMapping)
4692 return;
4693 switch (D->getKind()) {
4694 case Decl::CXXConversion:
4695 case Decl::CXXMethod:
4696 case Decl::Function:
4697 case Decl::ObjCMethod:
4698 case Decl::CXXConstructor:
4699 case Decl::CXXDestructor: {
Justin Bogner203f0922015-07-28 00:41:51 +00004700 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
Alex Lorenzee024992014-08-04 18:41:51 +00004701 return;
Vedant Kumar0acf3432017-09-22 18:23:04 +00004702 SourceManager &SM = getContext().getSourceManager();
4703 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
4704 return;
Alex Lorenzee024992014-08-04 18:41:51 +00004705 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4706 if (I == DeferredEmptyCoverageMappingDecls.end())
4707 DeferredEmptyCoverageMappingDecls[D] = true;
4708 break;
4709 }
4710 default:
4711 break;
4712 };
4713}
4714
4715void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4716 // Do we need to generate coverage mapping?
4717 if (!CodeGenOpts.CoverageMapping)
4718 return;
4719 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4720 if (Fn->isTemplateInstantiation())
4721 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4722 }
4723 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4724 if (I == DeferredEmptyCoverageMappingDecls.end())
4725 DeferredEmptyCoverageMappingDecls[D] = false;
4726 else
4727 I->second = false;
4728}
4729
4730void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
Eli Friedman8516b7f2017-12-19 01:54:09 +00004731 // We call takeVector() here to avoid use-after-free.
4732 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
4733 // we deserialize function bodies to emit coverage info for them, and that
4734 // deserializes more declarations. How should we handle that case?
4735 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
Eli Friedmandbcfade2017-12-13 00:14:17 +00004736 if (!Entry.second)
Alex Lorenzee024992014-08-04 18:41:51 +00004737 continue;
Eli Friedmandbcfade2017-12-13 00:14:17 +00004738 const Decl *D = Entry.first;
Alex Lorenzee024992014-08-04 18:41:51 +00004739 switch (D->getKind()) {
4740 case Decl::CXXConversion:
4741 case Decl::CXXMethod:
4742 case Decl::Function:
4743 case Decl::ObjCMethod: {
4744 CodeGenPGO PGO(*this);
4745 GlobalDecl GD(cast<FunctionDecl>(D));
4746 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4747 getFunctionLinkage(GD));
4748 break;
4749 }
4750 case Decl::CXXConstructor: {
4751 CodeGenPGO PGO(*this);
4752 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4753 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4754 getFunctionLinkage(GD));
4755 break;
4756 }
4757 case Decl::CXXDestructor: {
4758 CodeGenPGO PGO(*this);
4759 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4760 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4761 getFunctionLinkage(GD));
4762 break;
4763 }
4764 default:
4765 break;
4766 };
4767 }
4768}
4769
John McCall09ae0322010-07-06 23:57:41 +00004770/// Turns the given pointer into a constant.
4771static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4772 const void *Ptr) {
4773 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00004774 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00004775 return llvm::ConstantInt::get(i64, PtrInt);
4776}
4777
4778static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4779 llvm::NamedMDNode *&GlobalMetadata,
4780 GlobalDecl D,
4781 llvm::GlobalValue *Addr) {
4782 if (!GlobalMetadata)
4783 GlobalMetadata =
4784 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4785
4786 // TODO: should we report variant information for ctors/dtors?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004787 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4788 llvm::ConstantAsMetadata::get(GetPointerConstant(
4789 CGM.getLLVMContext(), D.getDecl()))};
Jay Foadea324f12011-04-21 19:59:12 +00004790 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00004791}
4792
Richard Smithdf931ce2013-04-06 05:00:46 +00004793/// For each function which is declared within an extern "C" region and marked
4794/// as 'used', but has internal linkage, create an alias from the unmangled
4795/// name to the mangled name if possible. People expect to be able to refer
4796/// to such functions with an unmangled name from inline assembly within the
4797/// same translation unit.
4798void CodeGenModule::EmitStaticExternCAliases() {
Yaxun Liub0eee292018-03-29 14:50:00 +00004799 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
Justin Lebarcd2f6bb2016-01-25 22:36:37 +00004800 return;
Yaron Kerenb54db522015-06-11 12:33:25 +00004801 for (auto &I : StaticExternCValues) {
4802 IdentifierInfo *Name = I.first;
4803 llvm::GlobalValue *Val = I.second;
Richard Smith85465e62013-04-06 07:07:44 +00004804 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola27c60b52014-06-03 02:42:01 +00004805 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith85465e62013-04-06 07:07:44 +00004806 }
Richard Smithdf931ce2013-04-06 05:00:46 +00004807}
4808
Alp Tokerfb8d02b2014-06-05 22:10:59 +00004809bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4810 GlobalDecl &Result) const {
4811 auto Res = Manglings.find(MangledName);
4812 if (Res == Manglings.end())
4813 return false;
4814 Result = Res->getValue();
4815 return true;
4816}
4817
John McCall09ae0322010-07-06 23:57:41 +00004818/// Emits metadata nodes associating all the global values in the
4819/// current module with the Decls they came from. This is useful for
4820/// projects using IR gen as a subroutine.
4821///
4822/// Since there's currently no way to associate an MDNode directly
4823/// with an llvm::GlobalValue, we create a global named metadata
4824/// with the name 'clang.global.decl.ptrs'.
4825void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00004826 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00004827
Robert Lytton5b88f78f2014-07-03 09:30:29 +00004828 for (auto &I : MangledDeclNames) {
4829 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
Keno Fischer0e2d4222015-11-05 23:18:44 +00004830 // Some mangled names don't necessarily have an associated GlobalValue
4831 // in this module, e.g. if we mangled it for DebugInfo.
4832 if (Addr)
4833 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall09ae0322010-07-06 23:57:41 +00004834 }
4835}
4836
4837/// Emits metadata nodes for all the local variables in the current
4838/// function.
4839void CodeGenFunction::EmitDeclMetadata() {
4840 if (LocalDeclMap.empty()) return;
4841
4842 llvm::LLVMContext &Context = getLLVMContext();
4843
4844 // Find the unique metadata ID for this name.
4845 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4846
Craig Topper8a13c412014-05-21 05:09:00 +00004847 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00004848
Robert Lytton5b88f78f2014-07-03 09:30:29 +00004849 for (auto &I : LocalDeclMap) {
4850 const Decl *D = I.first;
John McCall7f416cc2015-09-08 08:05:57 +00004851 llvm::Value *Addr = I.second.getPointer();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004852 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00004853 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004854 Alloca->setMetadata(
4855 DeclPtrKind, llvm::MDNode::get(
4856 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004857 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00004858 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4859 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4860 }
4861 }
4862}
Daniel Dunbar900546d2010-07-16 00:00:15 +00004863
Rafael Espindola3bfa4682013-10-16 19:28:50 +00004864void CodeGenModule::EmitVersionIdentMetadata() {
4865 llvm::NamedMDNode *IdentMetadata =
4866 TheModule.getOrInsertNamedMetadata("llvm.ident");
4867 std::string Version = getClangFullVersion();
4868 llvm::LLVMContext &Ctx = TheModule.getContext();
4869
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004870 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola3bfa4682013-10-16 19:28:50 +00004871 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4872}
4873
Robert Lytton57765d52014-07-03 09:30:33 +00004874void CodeGenModule::EmitTargetMetadata() {
Richard Smith1ba0a072014-08-01 20:39:36 +00004875 // Warning, new MangledDeclNames may be appended within this loop.
4876 // We rely on MapVector insertions adding new elements to the end
4877 // of the container.
4878 // FIXME: Move this loop into the one target that needs it, and only
4879 // loop over those declarations for which we couldn't emit the target
4880 // metadata when we emitted the declaration.
4881 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
Richard Smith570706d2014-08-01 22:17:28 +00004882 auto Val = *(MangledDeclNames.begin() + I);
Richard Smith1ba0a072014-08-01 20:39:36 +00004883 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4884 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Robert Lytton57765d52014-07-03 09:30:33 +00004885 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4886 }
4887}
4888
Nick Lewycky85c011d2011-05-05 00:08:20 +00004889void CodeGenModule::EmitCoverageFile() {
Nick Lewycky97e49ac2016-08-31 23:04:32 +00004890 if (getCodeGenOpts().CoverageDataFile.empty() &&
4891 getCodeGenOpts().CoverageNotesFile.empty())
4892 return;
4893
4894 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4895 if (!CUNode)
4896 return;
4897
4898 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4899 llvm::LLVMContext &Ctx = TheModule.getContext();
4900 auto *CoverageDataFile =
4901 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4902 auto *CoverageNotesFile =
4903 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4904 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4905 llvm::MDNode *CU = CUNode->getOperand(i);
4906 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4907 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky480cb992011-05-04 20:46:58 +00004908 }
4909}
Nico Webercf4ff5862012-10-11 10:13:44 +00004910
Nico Weber17d3a2c2014-09-08 16:26:36 +00004911llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Webercf4ff5862012-10-11 10:13:44 +00004912 // Sema has checked that all uuid strings are of the form
4913 // "12345678-1234-1234-1234-1234567890ab".
4914 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00004915 for (unsigned i = 0; i < 36; ++i) {
4916 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4917 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00004918 }
Nico Webercf4ff5862012-10-11 10:13:44 +00004919
Nico Weberdfa274e2014-09-08 16:11:15 +00004920 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemerbbecd092013-08-15 19:59:14 +00004921 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00004922
David Majnemerbbecd092013-08-15 19:59:14 +00004923 llvm::Constant *Field3[8];
4924 for (unsigned Idx = 0; Idx < 8; ++Idx)
4925 Field3[Idx] = llvm::ConstantInt::get(
4926 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4927
4928 llvm::Constant *Fields[4] = {
4929 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4930 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4931 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4932 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4933 };
4934
4935 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00004936}
David Majnemere2cb8d12014-07-07 06:20:47 +00004937
4938llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4939 bool ForEH) {
4940 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4941 // FIXME: should we even be calling this method if RTTI is disabled
4942 // and it's not for EH?
Yaxun Liu6328f9a2018-06-05 15:11:02 +00004943 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
David Majnemere2cb8d12014-07-07 06:20:47 +00004944 return llvm::Constant::getNullValue(Int8PtrTy);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004945
David Majnemere2cb8d12014-07-07 06:20:47 +00004946 if (ForEH && Ty->isObjCObjectPointerType() &&
4947 LangOpts.ObjCRuntime.isGNUFamily())
4948 return ObjCRuntime->GetEHType(Ty);
4949
David Majnemer443250f2015-03-17 20:35:00 +00004950 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
David Majnemere2cb8d12014-07-07 06:20:47 +00004951}
4952
Alexey Bataev97720002014-11-11 04:05:39 +00004953void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004954 // Do not emit threadprivates in simd-only mode.
4955 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
4956 return;
Alexey Bataev97720002014-11-11 04:05:39 +00004957 for (auto RefExpr : D->varlists()) {
4958 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4959 bool PerformInit =
4960 VD->getAnyInitializer() &&
4961 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4962 /*ForRef=*/false);
John McCall7f416cc2015-09-08 08:05:57 +00004963
4964 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
Alexey Bataev3eff5f42015-02-25 08:32:46 +00004965 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00004966 VD, Addr, RefExpr->getLocStart(), PerformInit))
Alexey Bataev97720002014-11-11 04:05:39 +00004967 CXXGlobalInits.push_back(InitFunction);
4968 }
4969}
Peter Collingbourne86d34a72015-06-17 19:08:05 +00004970
Peter Collingbournee44acad2018-06-26 02:15:47 +00004971llvm::Metadata *
4972CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
4973 StringRef Suffix) {
4974 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00004975 if (InternalId)
4976 return InternalId;
4977
4978 if (isExternallyVisible(T->getLinkage())) {
4979 std::string OutName;
4980 llvm::raw_string_ostream Out(OutName);
4981 getCXXABI().getMangleContext().mangleTypeName(T, Out);
Peter Collingbournee44acad2018-06-26 02:15:47 +00004982 Out << Suffix;
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00004983
4984 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4985 } else {
4986 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4987 llvm::ArrayRef<llvm::Metadata *>());
4988 }
4989
4990 return InternalId;
4991}
4992
Peter Collingbournee44acad2018-06-26 02:15:47 +00004993llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4994 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
4995}
4996
4997llvm::Metadata *
4998CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
4999 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5000}
5001
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005002// Generalize pointer types to a void pointer with the qualifiers of the
5003// originally pointed-to type, e.g. 'const char *' and 'char * const *'
5004// generalize to 'const void *' while 'char *' and 'const char **' generalize to
5005// 'void *'.
5006static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5007 if (!Ty->isPointerType())
5008 return Ty;
5009
5010 return Ctx.getPointerType(
5011 QualType(Ctx.VoidTy).withCVRQualifiers(
5012 Ty->getPointeeType().getCVRQualifiers()));
5013}
5014
5015// Apply type generalization to a FunctionType's return and argument types
5016static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5017 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5018 SmallVector<QualType, 8> GeneralizedParams;
5019 for (auto &Param : FnType->param_types())
5020 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5021
5022 return Ctx.getFunctionType(
5023 GeneralizeType(Ctx, FnType->getReturnType()),
5024 GeneralizedParams, FnType->getExtProtoInfo());
5025 }
5026
5027 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5028 return Ctx.getFunctionNoProtoType(
5029 GeneralizeType(Ctx, FnType->getReturnType()));
5030
5031 llvm_unreachable("Encountered unknown FunctionType");
5032}
5033
5034llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
Peter Collingbournee44acad2018-06-26 02:15:47 +00005035 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5036 GeneralizedMetadataIdMap, ".generalized");
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005037}
5038
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005039/// Returns whether this module needs the "all-vtables" type identifier.
5040bool CodeGenModule::NeedAllVtablesTypeId() const {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005041 // Returns true if at least one of vtable-based CFI checkers is enabled and
5042 // is not in the trapping mode.
5043 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5044 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5045 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5046 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5047 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5048 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5049 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5050 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5051}
5052
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005053void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5054 CharUnits Offset,
5055 const CXXRecordDecl *RD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005056 llvm::Metadata *MD =
5057 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005058 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005059
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005060 if (CodeGenOpts.SanitizeCfiCrossDso)
5061 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5062 VTable->addTypeMetadata(Offset.getQuantity(),
5063 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005064
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005065 if (NeedAllVtablesTypeId()) {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005066 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005067 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005068 }
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005069}
Eric Christopher2b90a642015-11-11 23:05:08 +00005070
Gabor Buella1a83d062018-06-07 08:48:36 +00005071TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5072 assert(TD != nullptr);
5073 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5074
5075 ParsedAttr.Features.erase(
5076 llvm::remove_if(ParsedAttr.Features,
5077 [&](const std::string &Feat) {
5078 return !Target.isValidFeatureName(
5079 StringRef{Feat}.substr(1));
5080 }),
5081 ParsedAttr.Features.end());
5082 return ParsedAttr;
5083}
5084
5085
Eric Christopher2b90a642015-11-11 23:05:08 +00005086// Fills in the supplied string map with the set of target features for the
5087// passed in function.
5088void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
5089 const FunctionDecl *FD) {
5090 StringRef TargetCPU = Target.getTargetOpts().CPU;
5091 if (const auto *TD = FD->getAttr<TargetAttr>()) {
Gabor Buella1a83d062018-06-07 08:48:36 +00005092 TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
Erich Keanecf8807c2017-10-27 18:32:23 +00005093
Eric Christopher2b90a642015-11-11 23:05:08 +00005094 // Make a copy of the features as passed on the command line into the
5095 // beginning of the additional features from the function to override.
Erich Keaneb0d44232017-07-18 20:41:02 +00005096 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
Eric Christopher2b90a642015-11-11 23:05:08 +00005097 Target.getTargetOpts().FeaturesAsWritten.begin(),
5098 Target.getTargetOpts().FeaturesAsWritten.end());
5099
Erich Keanecf8807c2017-10-27 18:32:23 +00005100 if (ParsedAttr.Architecture != "" &&
5101 Target.isValidCPUName(ParsedAttr.Architecture))
5102 TargetCPU = ParsedAttr.Architecture;
Eric Christopher2b90a642015-11-11 23:05:08 +00005103
5104 // Now populate the feature map, first with the TargetCPU which is either
5105 // the default or a new one from the target attribute string. Then we'll use
5106 // the passed in features (FeaturesAsWritten) along with the new ones from
5107 // the attribute.
Erich Keaneb0d44232017-07-18 20:41:02 +00005108 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5109 ParsedAttr.Features);
Eric Christopher2b90a642015-11-11 23:05:08 +00005110 } else {
5111 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5112 Target.getTargetOpts().Features);
5113 }
5114}
Peter Collingbournedc134532016-01-16 00:31:22 +00005115
5116llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5117 if (!SanStats)
5118 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5119
5120 return *SanStats;
5121}
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005122llvm::Value *
5123CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5124 CodeGenFunction &CGF) {
John McCallde0fe072017-08-15 21:42:52 +00005125 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00005126 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005127 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5128 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5129 "__translate_sampler_initializer"),
5130 {C});
5131}