blob: 50b653c70ff96b06d901e879e45cf07f18324fed [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) {
407 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
408 AddGlobalCtor(CudaCtorFunction);
409 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
410 AddGlobalDtor(CudaDtorFunction);
411 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000412 if (OpenMPRuntime) {
Samuel Antaoee8fb302016-01-06 13:42:12 +0000413 if (llvm::Function *OpenMPRegistrationFunction =
George Rokos29d0f002017-05-27 03:03:13 +0000414 OpenMPRuntime->emitRegistrationFunction()) {
415 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
416 OpenMPRegistrationFunction : nullptr;
417 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
418 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000419 OpenMPRuntime->clear();
420 }
Easwaran Raman695890c2015-12-17 19:14:27 +0000421 if (PGOReader) {
Easwaran Raman81608122016-03-24 21:32:25 +0000422 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
Easwaran Raman695890c2015-12-17 19:14:27 +0000423 if (PGOStats.hasDiagnostics())
424 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
425 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000426 EmitCtorList(GlobalCtors, "llvm.global_ctors");
427 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000428 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000429 EmitStaticExternCAliases();
Alex Lorenzee024992014-08-04 18:41:51 +0000430 EmitDeferredUnusedCoverageMappings();
431 if (CoverageMapping)
432 CoverageMapping->emit();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000433 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000434 CodeGenFunction(*this).EmitCfiCheckFail();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000435 CodeGenFunction(*this).EmitCfiCheckStub();
436 }
Alex Lorenza8fbef42017-03-23 11:14:27 +0000437 emitAtAvailableLinkGuard();
Rafael Espindola060062a2014-03-06 22:15:10 +0000438 emitLLVMUsed();
Peter Collingbournedc134532016-01-16 00:31:22 +0000439 if (SanStats)
440 SanStats->finish();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000441
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000442 if (CodeGenOpts.Autolink &&
443 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000444 EmitModuleLinkOptions();
445 }
Nirav Dave8497ef42017-03-18 00:43:39 +0000446
Nirav Dave741dea02017-03-30 13:41:44 +0000447 // Record mregparm value now so it is visible through rest of codegen.
448 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
449 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
450 CodeGenOpts.NumRegisterParameters);
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000451
Reid Kleckner124955a2015-08-05 18:51:13 +0000452 if (CodeGenOpts.DwarfVersion) {
Manman Ren9691f7f2013-06-19 01:46:49 +0000453 // We actually want the latest version when there are conflicts.
454 // We can change from Warning to Latest if such mode is supported.
455 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
456 CodeGenOpts.DwarfVersion);
Reid Kleckner124955a2015-08-05 18:51:13 +0000457 }
458 if (CodeGenOpts.EmitCodeView) {
459 // Indicate that we want CodeView in the metadata.
460 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
461 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000462 if (CodeGenOpts.ControlFlowGuard) {
463 // We want function ID tables for Control Flow Guard.
464 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
465 }
Piotr Padlewski9d0ecf22015-09-15 21:46:50 +0000466 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
467 // We don't support LTO with 2 with different StrictVTablePointers
468 // FIXME: we could support it by stripping all the information introduced
469 // by StrictVTablePointers.
470
471 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
472
473 llvm::Metadata *Ops[2] = {
474 llvm::MDString::get(VMContext, "StrictVTablePointers"),
475 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
476 llvm::Type::getInt32Ty(VMContext), 1))};
477
478 getModule().addModuleFlag(llvm::Module::Require,
479 "StrictVTablePointersRequirement",
480 llvm::MDNode::get(VMContext, Ops));
481 }
Manman Ren4b7f23d2013-11-22 19:42:45 +0000482 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000483 // We support a single version in the linked module. The LLVM
484 // parser will drop debug info with a different version number
485 // (and warn about it, too).
486 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000487 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000488
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000489 // We need to record the widths of enums and wchar_t, so that we can generate
Matthias Brauna4519532017-05-20 01:29:55 +0000490 // the correct build attributes in the ARM backend. wchar_size is also used by
491 // TargetLibraryInfo.
Matthias Braunbffc1bb2017-09-26 02:37:23 +0000492 uint64_t WCharWidth =
493 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
Matthias Brauna4519532017-05-20 01:29:55 +0000494 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
495
Justin Bogner9bb7f152014-06-23 20:03:28 +0000496 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000497 if ( Arch == llvm::Triple::arm
498 || Arch == llvm::Triple::armeb
499 || Arch == llvm::Triple::thumb
500 || Arch == llvm::Triple::thumbeb) {
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000501 // The minimum width of an enum in bytes
502 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
503 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
504 }
505
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000506 if (CodeGenOpts.SanitizeCfiCrossDso) {
507 // Indicate that we want cross-DSO control flow integrity checks.
508 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
509 }
510
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +0000511 if (CodeGenOpts.CFProtectionReturn &&
512 Target.checkCFProtectionReturnSupported(getDiags())) {
513 // Indicate that we want to instrument return control flow protection.
514 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
515 1);
516 }
517
518 if (CodeGenOpts.CFProtectionBranch &&
519 Target.checkCFProtectionBranchSupported(getDiags())) {
520 // Indicate that we want to instrument branch control flow protection.
521 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
522 1);
523 }
524
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000525 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
Justin Lebard3a44f62016-04-05 18:26:20 +0000526 // Indicate whether __nvvm_reflect should be configured to flush denormal
527 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
528 // property.)
529 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
530 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
531 }
532
Alexey Bader364a1162017-06-20 14:30:18 +0000533 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
534 if (LangOpts.OpenCL) {
535 EmitOpenCLMetadata();
536 // Emit SPIR version.
537 if (getTriple().getArch() == llvm::Triple::spir ||
538 getTriple().getArch() == llvm::Triple::spir64) {
539 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
540 // opencl.spir.version named metadata.
541 llvm::Metadata *SPIRVerElts[] = {
542 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
543 Int32Ty, LangOpts.OpenCLVersion / 100)),
544 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
545 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
546 llvm::NamedMDNode *SPIRVerMD =
547 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
548 llvm::LLVMContext &Ctx = TheModule.getContext();
549 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
550 }
551 }
552
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000553 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
Sriraman Tallam70e70e62016-04-28 22:34:00 +0000554 assert(PLevel < 3 && "Invalid PIC Level");
555 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
Rafael Espindolac9d336e2016-06-23 15:07:32 +0000556 if (Context.getLangOpts().PIE)
557 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000558 }
559
Sriraman Tallam80af0052018-02-23 21:27:33 +0000560 if (CodeGenOpts.NoPLT)
561 getModule().setRtLibUseGOT();
562
John McCall0bdb1fd2010-09-16 06:16:50 +0000563 SimplifyPersonality();
564
John McCall09ae0322010-07-06 23:57:41 +0000565 if (getCodeGenOpts().EmitDeclMetadata)
566 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000567
568 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000569 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000570
571 if (DebugInfo)
572 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000573
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +0000574 if (getCodeGenOpts().EmitVersionIdentMetadata)
575 EmitVersionIdentMetadata();
Robert Lytton57765d52014-07-03 09:30:33 +0000576
577 EmitTargetMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000578}
579
Alexey Bader364a1162017-06-20 14:30:18 +0000580void CodeGenModule::EmitOpenCLMetadata() {
581 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
582 // opencl.ocl.version named metadata node.
583 llvm::Metadata *OCLVerElts[] = {
584 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
585 Int32Ty, LangOpts.OpenCLVersion / 100)),
586 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
587 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
588 llvm::NamedMDNode *OCLVerMD =
589 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
590 llvm::LLVMContext &Ctx = TheModule.getContext();
591 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
592}
593
Devang Patel945b8ae2011-03-23 16:29:39 +0000594void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
595 // Make sure that this type is translated.
596 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000597}
598
David Majnemer929025d2016-01-26 19:30:26 +0000599void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
600 // Make sure that this type is translated.
601 Types.RefreshTypeCacheForClass(RD);
602}
603
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000604llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
Dan Gohman947c9af2010-10-14 23:06:10 +0000605 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000606 return nullptr;
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000607 return TBAA->getTypeInfo(QTy);
Dan Gohman947c9af2010-10-14 23:06:10 +0000608}
609
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000610TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
Ivan A. Kosarev124a2182018-02-20 12:33:04 +0000611 if (!TBAA)
612 return TBAAAccessInfo();
613 return TBAA->getAccessInfo(AccessType);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000614}
615
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000616TBAAAccessInfo
617CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000618 if (!TBAA)
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000619 return TBAAAccessInfo();
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000620 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000621}
622
Dan Gohman22695fc2012-09-28 21:58:29 +0000623llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
624 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000625 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000626 return TBAA->getTBAAStructInfo(QTy);
627}
628
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000629llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
630 if (!TBAA)
631 return nullptr;
632 return TBAA->getBaseTypeInfo(QTy);
633}
634
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000635llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
Manman Renc451e572013-04-04 21:53:22 +0000636 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000637 return nullptr;
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000638 return TBAA->getAccessTagInfo(Info);
Manman Renc451e572013-04-04 21:53:22 +0000639}
640
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000641TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
642 TBAAAccessInfo TargetInfo) {
643 if (!TBAA)
644 return TBAAAccessInfo();
645 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
646}
647
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +0000648TBAAAccessInfo
649CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
650 TBAAAccessInfo InfoB) {
651 if (!TBAA)
652 return TBAAAccessInfo();
653 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
654}
655
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000656TBAAAccessInfo
657CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
658 TBAAAccessInfo SrcInfo) {
659 if (!TBAA)
660 return TBAAAccessInfo();
661 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
662}
663
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000664void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000665 TBAAAccessInfo TBAAInfo) {
666 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
667 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
Dan Gohman947c9af2010-10-14 23:06:10 +0000668}
669
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000670void CodeGenModule::DecorateInstructionWithInvariantGroup(
671 llvm::Instruction *I, const CXXRecordDecl *RD) {
Piotr Padlewski34046bd2017-04-24 12:58:43 +0000672 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
673 llvm::MDNode::get(getLLVMContext(), {}));
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000674}
675
Alp Toker29cb66b2014-01-26 06:17:37 +0000676void CodeGenModule::Error(SourceLocation loc, StringRef message) {
677 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
678 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000679}
680
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000681/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000682/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000683void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000684 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000685 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000686 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000687 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
688 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000689}
Chris Lattner41af8182007-12-02 06:27:33 +0000690
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000691/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000692/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000693void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000694 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000695 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000696 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000697 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000698}
699
John McCall23c29fe2011-06-24 21:55:10 +0000700llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
701 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
702}
703
Mike Stump11289f42009-09-09 15:08:12 +0000704void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000705 const NamedDecl *D) const {
Rafael Espindola123ce972018-01-24 18:58:32 +0000706 if (GV->hasDLLImportStorageClass())
707 return;
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000708 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000709 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000710 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000711 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000712 }
Rafael Espindola3f727a82018-03-14 18:14:46 +0000713 if (!D)
714 return;
John McCallc273f242010-10-30 11:50:40 +0000715 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000716 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000717 if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
Rafael Espindola4a5da442013-02-27 02:56:45 +0000718 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000719}
720
Rafael Espindola699f5d62018-02-07 22:15:33 +0000721static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
Rafael Espindola3dd49812018-02-23 00:22:15 +0000722 llvm::GlobalValue *GV) {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000723 if (GV->hasLocalLinkage())
724 return true;
725
726 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
727 return true;
728
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000729 // DLLImport explicitly marks the GV as external.
730 if (GV->hasDLLImportStorageClass())
731 return false;
732
Rafael Espindola699f5d62018-02-07 22:15:33 +0000733 const llvm::Triple &TT = CGM.getTriple();
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000734 // Every other GV is local on COFF.
735 // Make an exception for windows OS in the triple: Some firmware builds use
736 // *-win32-macho triples. This (accidentally?) produced windows relocations
737 // without GOT tables in older clang versions; Keep this behaviour.
738 // FIXME: even thread local variables?
739 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
740 return true;
741
742 // Only handle COFF and ELF for now.
Rafael Espindola699f5d62018-02-07 22:15:33 +0000743 if (!TT.isOSBinFormatELF())
744 return false;
745
746 // If this is not an executable, don't assume anything is local.
747 const auto &CGOpts = CGM.getCodeGenOpts();
748 llvm::Reloc::Model RM = CGOpts.RelocationModel;
749 const auto &LOpts = CGM.getLangOpts();
750 if (RM != llvm::Reloc::Static && !LOpts.PIE)
751 return false;
752
753 // A definition cannot be preempted from an executable.
754 if (!GV->isDeclarationForLinker())
755 return true;
756
757 // Most PIC code sequences that assume that a symbol is local cannot produce a
758 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
759 // depended, it seems worth it to handle it here.
760 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
761 return false;
762
763 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
764 llvm::Triple::ArchType Arch = TT.getArch();
765 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
766 Arch == llvm::Triple::ppc64le)
767 return false;
768
769 // If we can use copy relocations we can assume it is local.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000770 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
771 if (!Var->isThreadLocal() &&
Rafael Espindola75e57362018-02-07 23:04:06 +0000772 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
773 return true;
Rafael Espindola699f5d62018-02-07 22:15:33 +0000774
775 // If we can use a plt entry as the symbol address we can assume it
776 // is local.
777 // FIXME: This should work for PIE, but the gold linker doesn't support it.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000778 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
Rafael Espindola699f5d62018-02-07 22:15:33 +0000779 return true;
780
781 // Otherwise don't assue it is local.
782 return false;
783}
784
Rafael Espindola3dd49812018-02-23 00:22:15 +0000785void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000786 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
Rafael Espindola699f5d62018-02-07 22:15:33 +0000787}
788
Rafael Espindolab7350042018-03-01 00:35:47 +0000789void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
790 GlobalDecl GD) const {
791 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
Reid Klecknerae9b0702018-03-16 19:40:50 +0000792 // C++ destructors have a few C++ ABI specific special cases.
Rafael Espindolab7350042018-03-01 00:35:47 +0000793 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
Reid Klecknerae9b0702018-03-16 19:40:50 +0000794 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
795 return;
Rafael Espindolab7350042018-03-01 00:35:47 +0000796 }
797 setDLLImportDLLExport(GV, D);
798}
799
800void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
801 const NamedDecl *D) const {
Rafael Espindola3f727a82018-03-14 18:14:46 +0000802 if (D && D->isExternallyVisible()) {
Rafael Espindolab7350042018-03-01 00:35:47 +0000803 if (D->hasAttr<DLLImportAttr>())
804 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
805 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
806 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
807 }
808}
809
810void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
811 GlobalDecl GD) const {
812 setDLLImportDLLExport(GV, GD);
813 setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
814}
815
Rafael Espindola699f5d62018-02-07 22:15:33 +0000816void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
817 const NamedDecl *D) const {
Rafael Espindolab7350042018-03-01 00:35:47 +0000818 setDLLImportDLLExport(GV, D);
819 setGlobalVisibilityAndLocal(GV, D);
820}
821
822void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
823 const NamedDecl *D) const {
Rafael Espindola699f5d62018-02-07 22:15:33 +0000824 setGlobalVisibility(GV, D);
Rafael Espindola3dd49812018-02-23 00:22:15 +0000825 setDSOLocal(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +0000826}
827
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000828static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
829 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
830 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
831 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
832 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
833 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
834}
835
836static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
837 CodeGenOptions::TLSModel M) {
838 switch (M) {
839 case CodeGenOptions::GeneralDynamicTLSModel:
840 return llvm::GlobalVariable::GeneralDynamicTLSModel;
841 case CodeGenOptions::LocalDynamicTLSModel:
842 return llvm::GlobalVariable::LocalDynamicTLSModel;
843 case CodeGenOptions::InitialExecTLSModel:
844 return llvm::GlobalVariable::InitialExecTLSModel;
845 case CodeGenOptions::LocalExecTLSModel:
846 return llvm::GlobalVariable::LocalExecTLSModel;
847 }
848 llvm_unreachable("Invalid TLS model!");
849}
850
David Majnemerbb525f7c2014-10-15 22:38:23 +0000851void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000852 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000853
David Majnemerbb525f7c2014-10-15 22:38:23 +0000854 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000855 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000856
857 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000858 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000859 TLM = GetLLVMTLSModel(Attr->getModel());
860 }
861
862 GV->setThreadLocalMode(TLM);
863}
864
Erich Keane281d20b2018-01-08 21:34:17 +0000865static void AppendTargetMangling(const CodeGenModule &CGM,
866 const TargetAttr *Attr, raw_ostream &Out) {
867 if (Attr->isDefaultVersion())
868 return;
869
870 Out << '.';
871 const auto &Target = CGM.getTarget();
872 TargetAttr::ParsedTargetAttr Info =
873 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
George Burgess IV19131152018-01-17 04:46:04 +0000874 // Multiversioning doesn't allow "no-${feature}", so we can
875 // only have "+" prefixes here.
876 assert(LHS.startswith("+") && RHS.startswith("+") &&
877 "Features should always have a prefix.");
878 return Target.multiVersionSortPriority(LHS.substr(1)) >
879 Target.multiVersionSortPriority(RHS.substr(1));
Erich Keane281d20b2018-01-08 21:34:17 +0000880 });
881
882 bool IsFirst = true;
883
884 if (!Info.Architecture.empty()) {
885 IsFirst = false;
886 Out << "arch_" << Info.Architecture;
887 }
888
889 for (StringRef Feat : Info.Features) {
890 if (!IsFirst)
891 Out << '_';
892 IsFirst = false;
893 Out << Feat.substr(1);
894 }
895}
896
897static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
898 const NamedDecl *ND,
899 bool OmitTargetMangling = false) {
900 SmallString<256> Buffer;
901 llvm::raw_svector_ostream Out(Buffer);
902 MangleContext &MC = CGM.getCXXABI().getMangleContext();
903 if (MC.shouldMangleDeclName(ND)) {
904 llvm::raw_svector_ostream Out(Buffer);
905 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
906 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
907 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
908 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
909 else
910 MC.mangleName(ND, Out);
911 } else {
912 IdentifierInfo *II = ND->getIdentifier();
913 assert(II && "Attempt to mangle unnamed decl.");
914 const auto *FD = dyn_cast<FunctionDecl>(ND);
915
916 if (FD &&
917 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
918 llvm::raw_svector_ostream Out(Buffer);
919 Out << "__regcall3__" << II->getName();
920 } else {
921 Out << II->getName();
922 }
923 }
924
925 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
926 if (FD->isMultiVersion() && !OmitTargetMangling)
927 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
928 return Out.str();
929}
930
931void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
932 const FunctionDecl *FD) {
933 if (!FD->isMultiVersion())
934 return;
935
936 // Get the name of what this would be without the 'target' attribute. This
937 // allows us to lookup the version that was emitted when this wasn't a
938 // multiversion function.
939 std::string NonTargetName =
940 getMangledNameImpl(*this, GD, FD, /*OmitTargetMangling=*/true);
941 GlobalDecl OtherGD;
942 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
943 assert(OtherGD.getCanonicalDecl()
944 .getDecl()
945 ->getAsFunction()
946 ->isMultiVersion() &&
947 "Other GD should now be a multiversioned function");
948 // OtherFD is the version of this function that was mangled BEFORE
949 // becoming a MultiVersion function. It potentially needs to be updated.
950 const FunctionDecl *OtherFD =
951 OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
952 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
953 // This is so that if the initial version was already the 'default'
954 // version, we don't try to update it.
955 if (OtherName != NonTargetName) {
Erich Keanebc40c5c2018-01-09 01:09:12 +0000956 // Remove instead of erase, since others may have stored the StringRef
957 // to this.
958 const auto ExistingRecord = Manglings.find(NonTargetName);
959 if (ExistingRecord != std::end(Manglings))
960 Manglings.remove(&(*ExistingRecord));
Erich Keane281d20b2018-01-08 21:34:17 +0000961 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
962 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
963 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
964 Entry->setName(OtherName);
965 }
966 }
967}
968
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000969StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
David Majnemerd2385c02016-01-08 20:48:26 +0000970 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
971
972 // Some ABIs don't have constructor variants. Make sure that base and
973 // complete constructors get mangled the same.
974 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
975 if (!getTarget().getCXXABI().hasConstructorVariants()) {
976 CXXCtorType OrigCtorType = GD.getCtorType();
977 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
978 if (OrigCtorType == Ctor_Base)
979 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
980 }
981 }
982
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +0000983 auto FoundName = MangledDeclNames.find(CanonicalGD);
984 if (FoundName != MangledDeclNames.end())
985 return FoundName->second;
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000986
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000987
Richard Smith6d0e97a2014-08-02 00:50:16 +0000988 // Keep the first result in the case of a mangling collision.
Erich Keane281d20b2018-01-08 21:34:17 +0000989 const auto *ND = cast<NamedDecl>(GD.getDecl());
990 auto Result =
991 Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +0000992 return MangledDeclNames[CanonicalGD] = Result.first->first();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000993}
994
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000995StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
996 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000997 MangleContext &MangleCtx = getCXXABI().getMangleContext();
998 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +0000999
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001000 SmallString<256> Buffer;
1001 llvm::raw_svector_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +00001002 if (!D)
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001003 MangleCtx.mangleGlobalBlock(BD,
Fariborz Jahanian63628032012-06-26 16:06:38 +00001004 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001005 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001006 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001007 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001008 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001009 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001010 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001011
Richard Smith6d0e97a2014-08-02 00:50:16 +00001012 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1013 return Result.first->first();
Anders Carlsson635186a2010-06-09 02:36:32 +00001014}
1015
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001016llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +00001017 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +00001018}
1019
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001020/// AddGlobalCtor - Add a function to the list that will be called before
1021/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001022void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1023 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +00001024 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001025 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001026}
1027
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001028/// AddGlobalDtor - Add a function to the list that will be called
1029/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001030void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Akira Hatanaka617e2612018-04-17 18:41:52 +00001031 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1032 DtorsUsingAtExit[Priority].push_back(Dtor);
1033 return;
1034 }
1035
Daniel Dunbardec798b2009-01-13 02:25:00 +00001036 // FIXME: Type coercion of void()* types.
Craig Topper4b566922014-06-09 02:04:02 +00001037 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001038}
1039
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001040void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001041 if (Fns.empty()) return;
1042
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001043 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +00001044 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001045 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001046
Reid Kleckner563f0e82014-05-23 21:13:45 +00001047 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1048 llvm::StructType *CtorStructTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00001049 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001050
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001051 // Construct the constructor and destructor arrays.
John McCall23c9dc62016-11-28 22:18:27 +00001052 ConstantInitBuilder builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001053 auto ctors = builder.beginArray(CtorStructTy);
Yaron Kerenb54db522015-06-11 12:33:25 +00001054 for (const auto &I : Fns) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001055 auto ctor = ctors.beginStruct(CtorStructTy);
1056 ctor.addInt(Int32Ty, I.Priority);
1057 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1058 if (I.AssociatedData)
1059 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1060 else
1061 ctor.addNullPointer(VoidPtrTy);
John McCallf1788632016-11-28 22:18:30 +00001062 ctor.finishAndAddTo(ctors);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001063 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001064
John McCall18081af2016-11-19 20:12:25 +00001065 auto list =
1066 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1067 /*constant*/ false,
1068 llvm::GlobalValue::AppendingLinkage);
1069
1070 // The LTO linker doesn't seem to like it when we set an alignment
1071 // on appending variables. Take it off as a workaround.
1072 list->setAlignment(0);
1073
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001074 Fns.clear();
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001075}
1076
John McCalld4324142010-02-19 01:32:20 +00001077llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001078CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001079 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +00001080
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001081 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +00001082
Reid Klecknerae9b0702018-03-16 19:40:50 +00001083 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1084 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
Reid Klecknera283e482017-12-21 19:44:23 +00001085
Richard Smith5179eb72016-06-28 19:03:57 +00001086 if (isa<CXXConstructorDecl>(D) &&
1087 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1088 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1089 // Our approach to inheriting constructors is fundamentally different from
1090 // that used by the MS ABI, so keep our inheriting constructor thunks
1091 // internal rather than trying to pick an unambiguous mangling for them.
1092 return llvm::GlobalValue::InternalLinkage;
1093 }
1094
Hans Wennborg275efb92014-05-28 01:52:23 +00001095 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +00001096}
Nuno Lopesb6f79532008-06-08 15:45:52 +00001097
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001098llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001099 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1100 if (!MDS) return nullptr;
1101
Benjamin Kramer630cf8c2016-11-23 11:20:27 +00001102 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001103}
1104
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001105void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +00001106 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001107 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001108 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +00001109 llvm::AttributeList PAL;
1110 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
1111 F->setAttributes(PAL);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001112 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +00001113}
1114
John McCall9b0a7ce2011-10-02 01:16:38 +00001115/// Determines whether the language options require us to model
1116/// unwind exceptions. We treat -fexceptions as mandating this
1117/// except under the fragile ObjC ABI with only ObjC exceptions
1118/// enabled. This means, for example, that C with -fexceptions
1119/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001120static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +00001121 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001122 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +00001123
1124 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001125 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +00001126
1127 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001128 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +00001129 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +00001130 }
1131
1132 return true;
1133}
1134
Daniel Dunbar38932572009-04-14 08:05:55 +00001135void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1136 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001137 llvm::AttrBuilder B;
1138
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001139 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001140 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001141
David Blaikiebbafb8a2012-03-11 07:00:24 +00001142 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001143 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +00001144
Manoj Gupta4fbf84c2018-05-09 21:41:18 +00001145 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1146 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1147 B.addAttribute(llvm::Attribute::StackProtect);
1148 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1149 B.addAttribute(llvm::Attribute::StackProtectStrong);
1150 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1151 B.addAttribute(llvm::Attribute::StackProtectReq);
1152 }
Akira Hatanaka200500d2015-10-08 19:30:57 +00001153
1154 if (!D) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001155 // If we don't have a declaration to control inlining, the function isn't
1156 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1157 // disabled, mark the function as noinline.
1158 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1159 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1160 B.addAttribute(llvm::Attribute::NoInline);
1161
Reid Kleckneree4930b2017-05-02 22:07:37 +00001162 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Akira Hatanaka200500d2015-10-08 19:30:57 +00001163 return;
1164 }
1165
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001166 // Track whether we need to add the optnone LLVM attribute,
1167 // starting with the default for this optimization level.
1168 bool ShouldAddOptNone =
1169 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1170 // We can't add optnone in the following cases, it won't pass the verifier.
1171 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1172 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1173 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1174
1175 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001176 B.addAttribute(llvm::Attribute::OptimizeNone);
1177
1178 // OptimizeNone implies noinline; we should not be inlining such functions.
1179 B.addAttribute(llvm::Attribute::NoInline);
1180 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1181 "OptimizeNone and AlwaysInline on same function!");
1182
1183 // We still need to handle naked functions even though optnone subsumes
1184 // much of their semantics.
1185 if (D->hasAttr<NakedAttr>())
1186 B.addAttribute(llvm::Attribute::Naked);
1187
1188 // OptimizeNone wins over OptimizeForSize and MinSize.
1189 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1190 F->removeFnAttr(llvm::Attribute::MinSize);
1191 } else if (D->hasAttr<NakedAttr>()) {
Eli Friedmanc55efe42011-08-22 23:55:33 +00001192 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001193 B.addAttribute(llvm::Attribute::Naked);
1194 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001195 } else if (D->hasAttr<NoDuplicateAttr>()) {
1196 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001197 } else if (D->hasAttr<NoInlineAttr>()) {
1198 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +00001199 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Chandler Carruthfcd33142016-12-23 01:24:49 +00001200 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001201 // (noinline wins over always_inline, and we can't specify both in IR)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001202 B.addAttribute(llvm::Attribute::AlwaysInline);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001203 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1204 // If we're not inlining, then force everything that isn't always_inline to
1205 // carry an explicit noinline attribute.
1206 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1207 B.addAttribute(llvm::Attribute::NoInline);
1208 } else {
1209 // Otherwise, propagate the inline hint attribute and potentially use its
1210 // absence to mark things as noinline.
1211 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1212 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
1213 return Redecl->isInlineSpecified();
1214 })) {
1215 B.addAttribute(llvm::Attribute::InlineHint);
1216 } else if (CodeGenOpts.getInlining() ==
1217 CodeGenOptions::OnlyHintInlining &&
1218 !FD->isInlined() &&
1219 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1220 B.addAttribute(llvm::Attribute::NoInline);
1221 }
1222 }
Eli Friedmanc55efe42011-08-22 23:55:33 +00001223 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +00001224
Chandler Carruthfcd33142016-12-23 01:24:49 +00001225 // Add other optimization related attributes if we are optimizing this
1226 // function.
1227 if (!D->hasAttr<OptimizeNoneAttr>()) {
1228 if (D->hasAttr<ColdAttr>()) {
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001229 if (!ShouldAddOptNone)
1230 B.addAttribute(llvm::Attribute::OptimizeForSize);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001231 B.addAttribute(llvm::Attribute::Cold);
1232 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001233
Chandler Carruthfcd33142016-12-23 01:24:49 +00001234 if (D->hasAttr<MinSizeAttr>())
1235 B.addAttribute(llvm::Attribute::MinSize);
1236 }
Richard Smithb555a762012-09-28 22:46:07 +00001237
Reid Kleckneree4930b2017-05-02 22:07:37 +00001238 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001239
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001240 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1241 if (alignment)
1242 F->setAlignment(alignment);
1243
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00001244 if (!D->hasAttr<AlignedAttr>())
1245 if (LangOpts.FunctionAlignment)
1246 F->setAlignment(1 << LangOpts.FunctionAlignment);
1247
Dan Gohmanc2853072015-09-03 22:51:53 +00001248 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1249 // reserve a bit for differentiating between virtual and non-virtual member
1250 // functions. If the current target's C++ ABI requires this and this is a
1251 // member function, set its alignment accordingly.
1252 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1253 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1254 F->setAlignment(2);
1255 }
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001256
1257 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1258 if (CodeGenOpts.SanitizeCfiCrossDso)
1259 if (auto *FD = dyn_cast<FunctionDecl>(D))
1260 CreateFunctionTypeMetadata(FD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001261}
1262
Rafael Espindola75c649c2018-03-01 00:06:55 +00001263void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1264 const Decl *D = GD.getDecl();
Rafael Espindolab7350042018-03-01 00:35:47 +00001265 if (dyn_cast_or_null<NamedDecl>(D))
1266 setGVProperties(GV, GD);
John McCall457a04e2010-10-22 21:05:15 +00001267 else
1268 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +00001269
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001270 if (D && D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +00001271 addUsedGlobal(GV);
Rafael Espindola502f65a2014-05-05 20:21:03 +00001272}
1273
Erich Keane93e58662018-02-12 17:01:41 +00001274bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
1275 llvm::AttrBuilder &Attrs) {
1276 // Add target-cpu and target-features attributes to functions. If
1277 // we have a decl for the function and it has a target attribute then
1278 // parse that and add it to the feature set.
1279 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1280 std::vector<std::string> Features;
1281 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
1282 FD = FD ? FD->getMostRecentDecl() : FD;
1283 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1284 bool AddedAttr = false;
1285 if (TD) {
1286 llvm::StringMap<bool> FeatureMap;
1287 getFunctionFeatureMap(FeatureMap, FD);
1288
1289 // Produce the canonical string for this set of features.
1290 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1291 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1292
1293 // Now add the target-cpu and target-features to the function.
1294 // While we populated the feature map above, we still need to
1295 // get and parse the target attribute so we can get the cpu for
1296 // the function.
1297 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1298 if (ParsedAttr.Architecture != "" &&
1299 getTarget().isValidCPUName(ParsedAttr.Architecture))
1300 TargetCPU = ParsedAttr.Architecture;
1301 } else {
1302 // Otherwise just add the existing target cpu and target features to the
1303 // function.
1304 Features = getTarget().getTargetOpts().Features;
1305 }
1306
1307 if (TargetCPU != "") {
1308 Attrs.addAttribute("target-cpu", TargetCPU);
1309 AddedAttr = true;
1310 }
1311 if (!Features.empty()) {
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001312 llvm::sort(Features.begin(), Features.end());
Erich Keane93e58662018-02-12 17:01:41 +00001313 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1314 AddedAttr = true;
1315 }
1316
1317 return AddedAttr;
1318}
1319
Rafael Espindola285271c2018-02-28 23:54:23 +00001320void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
Rafael Espindolaee076a22014-05-13 18:45:53 +00001321 llvm::GlobalObject *GO) {
Rafael Espindola285271c2018-02-28 23:54:23 +00001322 const Decl *D = GD.getDecl();
Rafael Espindola75c649c2018-03-01 00:06:55 +00001323 SetCommonAttributes(GD, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +00001324
Javed Absar2a67c9e2017-06-05 10:11:57 +00001325 if (D) {
1326 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1327 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1328 GV->addAttribute("bss-section", SA->getName());
1329 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1330 GV->addAttribute("data-section", SA->getName());
1331 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1332 GV->addAttribute("rodata-section", SA->getName());
1333 }
1334
1335 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1336 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
Erich Keane30994d22018-02-08 20:04:22 +00001337 if (!D->getAttr<SectionAttr>())
1338 F->addFnAttr("implicit-section-name", SA->getName());
Erich Keane93e58662018-02-12 17:01:41 +00001339
1340 llvm::AttrBuilder Attrs;
1341 if (GetCPUAndFeaturesAttributes(D, Attrs)) {
1342 // We know that GetCPUAndFeaturesAttributes will always have the
1343 // newest set, since it has the newest possible FunctionDecl, so the
1344 // new ones should replace the old.
1345 F->removeFnAttr("target-cpu");
1346 F->removeFnAttr("target-features");
1347 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1348 }
Javed Absar2a67c9e2017-06-05 10:11:57 +00001349 }
1350
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001351 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1352 GO->setSection(SA->getName());
Javed Absar2a67c9e2017-06-05 10:11:57 +00001353 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001354
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001355 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +00001356}
1357
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001358void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001359 llvm::Function *F,
1360 const CGFunctionInfo &FI) {
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001361 const Decl *D = GD.getDecl();
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001362 SetLLVMFunctionAttributes(D, FI, F);
1363 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +00001364
1365 F->setLinkage(llvm::Function::InternalLinkage);
1366
Rafael Espindola285271c2018-02-28 23:54:23 +00001367 setNonAliasAttributes(GD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001368}
1369
Rafael Espindolab7350042018-03-01 00:35:47 +00001370static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
David Majnemerf6acb762014-04-25 17:07:16 +00001371 // Set linkage and visibility in case we never see a definition.
1372 LinkageInfo LV = ND->getLinkageAndVisibility();
Rafael Espindolab7350042018-03-01 00:35:47 +00001373 // Don't set internal linkage on declarations.
1374 // "extern_weak" is overloaded in LLVM; we probably should have
1375 // separate linkage types for this.
1376 if (isExternallyVisible(LV.getLinkage()) &&
1377 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1378 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
David Majnemerf6acb762014-04-25 17:07:16 +00001379}
1380
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001381void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1382 llvm::Function *F) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001383 // Only if we are checking indirect calls.
1384 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1385 return;
1386
1387 // Non-static class methods are handled via vtable pointer checks elsewhere.
1388 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1389 return;
1390
1391 // Additionally, if building with cross-DSO support...
1392 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001393 // Skip available_externally functions. They won't be codegen'ed in the
1394 // current module anyway.
1395 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1396 return;
1397 }
1398
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001399 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001400 F->addTypeMetadata(0, MD);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00001401 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001402
1403 // Emit a hash-based bit set entry for cross-DSO calls.
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001404 if (CodeGenOpts.SanitizeCfiCrossDso)
1405 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1406 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001407}
1408
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001409void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1410 bool IsIncompleteFunction,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001411 bool IsThunk) {
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001412
Pete Cooper2f1637a2015-05-20 17:17:45 +00001413 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001414 // If this is an intrinsic function, set the function's attributes
1415 // to the intrinsic's attributes.
Pete Cooper2f1637a2015-05-20 17:17:45 +00001416 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001417 return;
1418 }
1419
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001420 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +00001421
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001422 if (!IsIncompleteFunction) {
John McCalla729c622012-02-17 03:33:10 +00001423 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001424 // Setup target-specific attributes.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001425 if (F->isDeclaration())
1426 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001427 }
Mike Stump11289f42009-09-09 15:08:12 +00001428
Bob Wilsonfc6297f2014-04-01 01:38:16 +00001429 // Add the Returned attribute for "this", except for iOS 5 and earlier
1430 // where substantial code, including the libstdc++ dylib, was compiled with
1431 // GCC and does not actually return "this".
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001432 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00001433 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001434 assert(!F->arg_empty() &&
1435 F->arg_begin()->getType()
1436 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1437 "unexpected this return");
1438 F->addAttribute(1, llvm::Attribute::Returned);
1439 }
1440
Daniel Dunbar38932572009-04-14 08:05:55 +00001441 // Only a few attributes are set on declarations; these may later be
1442 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +00001443
Jake Ehrlichba874ad2017-11-29 00:54:20 +00001444 setLinkageForGV(F, FD);
Rafael Espindola699f5d62018-02-07 22:15:33 +00001445 setGVProperties(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +00001446
Javed Absar2a67c9e2017-06-05 10:11:57 +00001447 if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1448 F->addFnAttr("implicit-section-name");
1449 }
1450
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001451 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +00001452 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +00001453
Richard Smith351241c2016-04-07 21:46:12 +00001454 if (FD->isReplaceableGlobalAllocationFunction()) {
1455 // A replaceable global allocation function does not act like a builtin by
1456 // default, only if it is invoked by a new-expression or delete-expression.
Reid Klecknerde864822017-03-21 16:57:30 +00001457 F->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001458 llvm::Attribute::NoBuiltin);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001459
Richard Smith351241c2016-04-07 21:46:12 +00001460 // A sane operator new returns a non-aliasing pointer.
1461 // FIXME: Also add NonNull attribute to the return value
1462 // for the non-nothrow forms?
1463 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1464 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1465 (Kind == OO_New || Kind == OO_Array_New))
Reid Klecknerde864822017-03-21 16:57:30 +00001466 F->addAttribute(llvm::AttributeList::ReturnIndex,
Richard Smith351241c2016-04-07 21:46:12 +00001467 llvm::Attribute::NoAlias);
1468 }
1469
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001470 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001471 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001472 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1473 if (MD->isVirtual())
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001474 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001475
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001476 // Don't emit entries for function declarations in the cross-DSO mode. This
1477 // is handled with better precision by the receiving DSO.
1478 if (!CodeGenOpts.SanitizeCfiCrossDso)
1479 CreateFunctionTypeMetadata(FD, F);
Alexey Bataevb952e632017-12-15 16:28:31 +00001480
1481 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1482 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001483}
1484
Rafael Espindola060062a2014-03-06 22:15:10 +00001485void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +00001486 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001487 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001488 LLVMUsed.emplace_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001489}
1490
Rafael Espindola060062a2014-03-06 22:15:10 +00001491void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1492 assert(!GV->isDeclaration() &&
1493 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001494 LLVMCompilerUsed.emplace_back(GV);
Rafael Espindola060062a2014-03-06 22:15:10 +00001495}
1496
1497static void emitUsed(CodeGenModule &CGM, StringRef Name,
Sanjoy Dase369bd92017-05-01 17:08:00 +00001498 std::vector<llvm::WeakTrackingVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001499 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +00001500 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001501 return;
1502
Rafael Espindola060062a2014-03-06 22:15:10 +00001503 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +00001504 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +00001505 UsedArray.resize(List.size());
1506 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001507 UsedArray[i] =
Justin Holewinskif37f3d32015-02-02 21:05:49 +00001508 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1509 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +00001510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001512 if (UsedArray.empty())
1513 return;
Rafael Espindola060062a2014-03-06 22:15:10 +00001514 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +00001515
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001516 auto *GV = new llvm::GlobalVariable(
1517 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1518 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001519
1520 GV->setSection("llvm.metadata");
1521}
1522
Rafael Espindola060062a2014-03-06 22:15:10 +00001523void CodeGenModule::emitLLVMUsed() {
1524 emitUsed(*this, "llvm.used", LLVMUsed);
1525 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1526}
1527
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001528void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001529 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001530 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1531}
1532
Aaron Ballman5d041be2013-06-04 02:07:14 +00001533void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1534 llvm::SmallString<32> Opt;
1535 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001536 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballman5d041be2013-06-04 02:07:14 +00001537 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1538}
1539
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00001540void CodeGenModule::AddELFLibDirective(StringRef Lib) {
1541 auto &C = getLLVMContext();
1542 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1543 C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1544}
1545
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001546void CodeGenModule::AddDependentLib(StringRef Lib) {
1547 llvm::SmallString<24> Opt;
1548 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001549 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001550 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1551}
1552
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001553/// Add link options implied by the given module, including modules
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001554/// it depends on, using a postorder walk.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001555static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
Peter Collingbourne89061b22017-06-12 20:10:48 +00001556 SmallVectorImpl<llvm::MDNode *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001557 llvm::SmallPtrSet<Module *, 16> &Visited) {
1558 // Import this module's parent.
David Blaikie82e95a32014-11-19 07:49:47 +00001559 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001560 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001561 }
1562
1563 // Import this module's dependencies.
1564 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001565 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001566 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001567 }
1568
1569 // Add linker options to link against the libraries/frameworks
1570 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001571 llvm::LLVMContext &Context = CGM.getLLVMContext();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00001572
1573 // For modules that use export_as for linking, use that module
1574 // name instead.
1575 if (Mod->UseExportAsModuleLinkName)
1576 return;
1577
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001578 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001579 // Link against a framework. Frameworks are currently Darwin only, so we
1580 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001581 if (Mod->LinkLibraries[I-1].IsFramework) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001582 llvm::Metadata *Args[2] = {
1583 llvm::MDString::get(Context, "-framework"),
1584 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001585
1586 Metadata.push_back(llvm::MDNode::get(Context, Args));
1587 continue;
1588 }
1589
1590 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001591 llvm::SmallString<24> Opt;
1592 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1593 Mod->LinkLibraries[I-1].Library, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001594 auto *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001595 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1596 }
1597}
1598
1599void CodeGenModule::EmitModuleLinkOptions() {
1600 // Collect the set of all of the modules we want to visit to emit link
1601 // options, which is essentially the imported modules and all of their
1602 // non-explicit child modules.
1603 llvm::SetVector<clang::Module *> LinkModules;
1604 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1605 SmallVector<clang::Module *, 16> Stack;
1606
1607 // Seed the stack with imported modules.
Manman Ren9803ee82017-01-11 18:47:38 +00001608 for (Module *M : ImportedModules) {
1609 // Do not add any link flags when an implementation TU of a module imports
1610 // a header of that same module.
1611 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1612 !getLangOpts().isCompilingModule())
1613 continue;
Yaron Kerenb54db522015-06-11 12:33:25 +00001614 if (Visited.insert(M).second)
1615 Stack.push_back(M);
Manman Ren9803ee82017-01-11 18:47:38 +00001616 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001617
1618 // Find all of the modules to import, making a little effort to prune
1619 // non-leaf modules.
1620 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001621 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001622
1623 bool AnyChildren = false;
1624
1625 // Visit the submodules of this module.
1626 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1627 SubEnd = Mod->submodule_end();
1628 Sub != SubEnd; ++Sub) {
1629 // Skip explicit children; they need to be explicitly imported to be
1630 // linked against.
1631 if ((*Sub)->IsExplicit)
1632 continue;
1633
David Blaikie82e95a32014-11-19 07:49:47 +00001634 if (Visited.insert(*Sub).second) {
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001635 Stack.push_back(*Sub);
1636 AnyChildren = true;
1637 }
1638 }
1639
1640 // We didn't find any children, so add this module to the list of
1641 // modules to link against.
1642 if (!AnyChildren) {
1643 LinkModules.insert(Mod);
1644 }
1645 }
1646
1647 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001648 // order. We don't do anything to try to order import link flags with respect
1649 // to linker options inserted by things like #pragma comment().
Peter Collingbourne89061b22017-06-12 20:10:48 +00001650 SmallVector<llvm::MDNode *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001651 Visited.clear();
Yaron Kerenb54db522015-06-11 12:33:25 +00001652 for (Module *M : LinkModules)
1653 if (Visited.insert(M).second)
1654 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
Daniel Dunbar69e47462013-01-17 01:35:06 +00001655 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001656 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001657
Daniel Dunbar69e47462013-01-17 01:35:06 +00001658 // Add the linker options metadata flag.
Peter Collingbourne89061b22017-06-12 20:10:48 +00001659 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1660 for (auto *MD : LinkerOptionsMetadata)
1661 NMD->addOperand(MD);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001662}
1663
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001664void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +00001665 // Emit code for any potentially referenced deferred decls. Since a
1666 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001667 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001668
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001669 if (!DeferredVTables.empty()) {
1670 EmitDeferredVTables();
John McCall6bd2a892013-01-25 22:31:03 +00001671
Eric Christopherd160c502016-01-29 01:35:53 +00001672 // Emitting a vtable doesn't directly cause more vtables to
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001673 // become deferred, although it can cause functions to be
Eric Christopherd160c502016-01-29 01:35:53 +00001674 // emitted that then need those vtables.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001675 assert(DeferredVTables.empty());
1676 }
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001677
Eric Christopherd160c502016-01-29 01:35:53 +00001678 // Stop if we're out of both deferred vtables and deferred declarations.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001679 if (DeferredDeclsToEmit.empty())
1680 return;
John McCall6bd2a892013-01-25 22:31:03 +00001681
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001682 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1683 // work, it will not interfere with this.
Sanjoy Das70a60512017-05-01 06:12:13 +00001684 std::vector<GlobalDecl> CurDeclsToEmit;
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001685 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1686
Sanjoy Das70a60512017-05-01 06:12:13 +00001687 for (GlobalDecl &D : CurDeclsToEmit) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00001688 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1689 // to get GlobalValue with exactly the type we need, not something that
1690 // might had been created for another decl with the same mangled name but
1691 // different type.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001692 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
John McCalld195d4c2016-11-30 23:25:13 +00001693 GetAddrOfGlobal(D, ForDefinition));
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001694
1695 // In case of different address spaces, we may still get a cast, even with
1696 // IsForDefinition equal to true. Query mangled names table to get
1697 // GlobalValue.
1698 if (!GV)
1699 GV = GetGlobalValue(getMangledName(D));
1700
1701 // Make sure GetGlobalValue returned non-null.
1702 assert(GV);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001703
John McCallc2af9392010-05-27 01:45:30 +00001704 // Check to see if we've already emitted this. This is necessary
1705 // for a couple of reasons: first, decls can end up in the
1706 // deferred-decls queue multiple times, and second, decls can end
1707 // up with definitions in unusual ways (e.g. by an extern inline
1708 // function acquiring a strong function redefinition). Just
1709 // ignore these cases.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001710 if (!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001711 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001712
Chris Lattner45470942009-03-21 09:44:56 +00001713 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001714 EmitGlobalDefinition(D, GV);
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001715
1716 // If we found out that we need to emit more decls, do that recursively.
1717 // This has the advantage that the decls are emitted in a DFS and related
1718 // ones are close together, which is convenient for testing.
1719 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1720 EmitDeferred();
1721 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1722 }
Chris Lattner45470942009-03-21 09:44:56 +00001723 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001724}
Chris Lattner09153c02007-06-22 18:48:09 +00001725
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001726void CodeGenModule::EmitVTablesOpportunistically() {
1727 // Try to emit external vtables as available_externally if they have emitted
1728 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1729 // is not allowed to create new references to things that need to be emitted
1730 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1731
Piotr Padlewski05547742017-06-01 09:24:36 +00001732 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1733 && "Only emit opportunistic vtables with optimizations");
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001734
1735 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1736 assert(getVTables().isVTableExternal(RD) &&
1737 "This queue should only contain external vtables");
1738 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1739 VTables.GenerateClassData(RD);
1740 }
1741 OpportunisticVTables.clear();
1742}
1743
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001744void CodeGenModule::EmitGlobalAnnotations() {
1745 if (Annotations.empty())
1746 return;
1747
1748 // Create a new global variable for the ConstantStruct in the Module.
1749 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1750 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001751 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1752 llvm::GlobalValue::AppendingLinkage,
1753 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001754 gv->setSection(AnnotationSection);
1755}
1756
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001757llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001758 llvm::Constant *&AStr = AnnotationStrings[Str];
1759 if (AStr)
1760 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001761
1762 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001763 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001764 auto *gv =
1765 new llvm::GlobalVariable(getModule(), s->getType(), true,
1766 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001767 gv->setSection(AnnotationSection);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001768 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Benjamin Kramereed80612013-11-10 16:55:11 +00001769 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001770 return gv;
1771}
1772
1773llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1774 SourceManager &SM = getContext().getSourceManager();
1775 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1776 if (PLoc.isValid())
1777 return EmitAnnotationString(PLoc.getFilename());
1778 return EmitAnnotationString(SM.getBufferName(Loc));
1779}
1780
1781llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1782 SourceManager &SM = getContext().getSourceManager();
1783 PresumedLoc PLoc = SM.getPresumedLoc(L);
1784 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1785 SM.getExpansionLineNumber(L);
1786 return llvm::ConstantInt::get(Int32Ty, LineNo);
1787}
1788
Mike Stump11289f42009-09-09 15:08:12 +00001789llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001790 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001791 SourceLocation L) {
1792 // Get the globals for file name, annotation, and the line number.
1793 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1794 *UnitGV = EmitAnnotationUnit(L),
1795 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001796
Daniel Dunbar346892a2009-04-14 22:41:13 +00001797 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001798 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001799 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1800 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1801 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1802 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001803 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001804 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001805}
1806
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001807void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1808 llvm::GlobalValue *GV) {
1809 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1810 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001811 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1812 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001813}
1814
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001815bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1816 llvm::Function *Fn,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001817 SourceLocation Loc) const {
1818 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1819 // Blacklist by function name.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001820 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001821 return true;
1822 // Blacklist by location.
Yaron Kerened1fe5d2015-10-03 05:15:57 +00001823 if (Loc.isValid())
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001824 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001825 // If location is unknown, this may be a compiler-generated function. Assume
1826 // it's located in the main file.
1827 auto &SM = Context.getSourceManager();
1828 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001829 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001830 }
1831 return false;
1832}
1833
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001834bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1835 SourceLocation Loc, QualType Ty,
1836 StringRef Category) const {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001837 // For now globals can be blacklisted only in ASan and KASan.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001838 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +00001839 (SanitizerKind::Address | SanitizerKind::KernelAddress |
1840 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001841 if (!EnabledAsanMask)
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001842 return false;
1843 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001844 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001845 return true;
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001846 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001847 return true;
1848 // Check global type.
1849 if (!Ty.isNull()) {
1850 // Drill down the array types: if global variable of a fixed type is
1851 // blacklisted, we also don't instrument arrays of them.
1852 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1853 Ty = AT->getElementType();
1854 Ty = Ty.getCanonicalType().getUnqualifiedType();
1855 // We allow to blacklist only record types (classes, structs etc.)
1856 if (Ty->isRecordType()) {
1857 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001858 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001859 return true;
1860 }
1861 }
1862 return false;
1863}
1864
Dean Michael Berris835832d2017-03-30 00:29:36 +00001865bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1866 StringRef Category) const {
1867 if (!LangOpts.XRayInstrument)
1868 return false;
Dean Michael Berris488f7c22018-04-13 02:31:58 +00001869
Dean Michael Berris835832d2017-03-30 00:29:36 +00001870 const auto &XRayFilter = getContext().getXRayFilter();
1871 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
Dean Michael Berris488f7c22018-04-13 02:31:58 +00001872 auto Attr = ImbueAttr::NONE;
Dean Michael Berris835832d2017-03-30 00:29:36 +00001873 if (Loc.isValid())
1874 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1875 if (Attr == ImbueAttr::NONE)
1876 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1877 switch (Attr) {
1878 case ImbueAttr::NONE:
1879 return false;
1880 case ImbueAttr::ALWAYS:
1881 Fn->addFnAttr("function-instrument", "xray-always");
1882 break;
Dean Michael Berris170429e2017-05-24 05:46:36 +00001883 case ImbueAttr::ALWAYS_ARG1:
1884 Fn->addFnAttr("function-instrument", "xray-always");
1885 Fn->addFnAttr("xray-log-args", "1");
1886 break;
Dean Michael Berris835832d2017-03-30 00:29:36 +00001887 case ImbueAttr::NEVER:
1888 Fn->addFnAttr("function-instrument", "xray-never");
1889 break;
1890 }
1891 return true;
1892}
1893
Hans Wennborg43a0f992015-01-10 01:19:48 +00001894bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001895 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001896 if (LangOpts.EmitAllDecls)
Hans Wennborg43a0f992015-01-10 01:19:48 +00001897 return true;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001898
Hans Wennborg43a0f992015-01-10 01:19:48 +00001899 return getContext().DeclMustBeEmitted(Global);
1900}
1901
1902bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1903 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1904 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1905 // Implicit template instantiations may change linkage if they are later
1906 // explicitly instantiated, so they should not be emitted eagerly.
1907 return false;
Richard Smithd9b90092016-07-02 01:32:16 +00001908 if (const auto *VD = dyn_cast<VarDecl>(Global))
1909 if (Context.getInlineVariableDefinitionKind(VD) ==
1910 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1911 // A definition of an inline constexpr static data member may change
1912 // linkage later if it's redeclared outside the class.
1913 return false;
Samuel Antaof8b50122015-07-13 22:54:53 +00001914 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1915 // codegen for global variables, because they may be marked as threadprivate.
1916 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1917 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1918 return false;
Hans Wennborg43a0f992015-01-10 01:19:48 +00001919
1920 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001921}
1922
John McCall7f416cc2015-09-08 08:05:57 +00001923ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
Nico Webercf4ff5862012-10-11 10:13:44 +00001924 const CXXUuidofExpr* E) {
1925 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1926 // well-formed.
David Majnemer2041b462016-03-28 03:19:50 +00001927 StringRef Uuid = E->getUuidStr();
David Majnemercf963ce2013-08-09 08:35:59 +00001928 std::string Name = "_GUID_" + Uuid.lower();
1929 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00001930
David Majnemer65687602016-03-27 04:46:14 +00001931 // The UUID descriptor should be pointer aligned.
1932 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
John McCall7f416cc2015-09-08 08:05:57 +00001933
Nico Webercf4ff5862012-10-11 10:13:44 +00001934 // Look for an existing global.
1935 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
John McCall7f416cc2015-09-08 08:05:57 +00001936 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00001937
Nico Weber17d3a2c2014-09-08 16:26:36 +00001938 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Webercf4ff5862012-10-11 10:13:44 +00001939 assert(Init && "failed to initialize as constant");
1940
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001941 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00001942 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00001943 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001944 if (supportsCOMDAT())
1945 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolaca08d242018-03-20 15:42:58 +00001946 setDSOLocal(GV);
John McCall7f416cc2015-09-08 08:05:57 +00001947 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00001948}
1949
John McCall7f416cc2015-09-08 08:05:57 +00001950ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001951 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1952 assert(AA && "No alias?");
1953
John McCall7f416cc2015-09-08 08:05:57 +00001954 CharUnits Alignment = getContext().getDeclAlign(VD);
Chris Lattner2192fe52011-07-18 04:24:23 +00001955 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001956
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001957 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00001958 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001959 if (Entry) {
1960 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
John McCall7f416cc2015-09-08 08:05:57 +00001961 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1962 return ConstantAddress(Ptr, Alignment);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001963 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001964
1965 llvm::Constant *Aliasee;
1966 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00001967 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1968 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00001969 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001970 else
John McCall7ec50432010-03-19 23:29:14 +00001971 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00001972 llvm::PointerType::getUnqual(DeclTy),
1973 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001974
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001975 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001976 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1977 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001978
John McCall7f416cc2015-09-08 08:05:57 +00001979 return ConstantAddress(Aliasee, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001980}
1981
Chris Lattnere0be0df2009-05-12 21:21:08 +00001982void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001983 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001984
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001985 // Weak references don't produce any output by themselves.
1986 if (Global->hasAttr<WeakRefAttr>())
1987 return;
1988
Chris Lattner54041692009-03-22 21:47:11 +00001989 // If this is an alias definition (which otherwise looks like a declaration)
1990 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001991 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00001992 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001993
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001994 // IFunc like an alias whose value is resolved at runtime by calling resolver.
1995 if (Global->hasAttr<IFuncAttr>())
1996 return emitIFuncDefinition(GD);
1997
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001998 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001999 if (LangOpts.CUDA) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00002000 if (LangOpts.CUDAIsDevice) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002001 if (!Global->hasAttr<CUDADeviceAttr>() &&
2002 !Global->hasAttr<CUDAGlobalAttr>() &&
2003 !Global->hasAttr<CUDAConstantAttr>() &&
2004 !Global->hasAttr<CUDASharedAttr>())
2005 return;
2006 } else {
Artem Belevich42e19492016-03-02 18:28:50 +00002007 // We need to emit host-side 'shadows' for all global
2008 // device-side variables because the CUDA runtime needs their
2009 // size and host-side address in order to provide access to
2010 // their device-side incarnations.
2011
2012 // So device-only functions are the only things we skip.
2013 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2014 Global->hasAttr<CUDADeviceAttr>())
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002015 return;
Artem Belevich42e19492016-03-02 18:28:50 +00002016
2017 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2018 "Expected Variable or Function");
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002019 }
2020 }
2021
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002022 if (LangOpts.OpenMP) {
2023 // If this is OpenMP device, check if it is legal to emit this global
2024 // normally.
2025 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2026 return;
2027 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2028 if (MustBeEmitted(Global))
2029 EmitOMPDeclareReduction(DRD);
2030 return;
2031 }
2032 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002033
Chris Lattner45470942009-03-21 09:44:56 +00002034 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002035 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002036 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002037 if (!FD->doesThisDeclarationHaveABody()) {
2038 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2039 return;
2040
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002041 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00002042
2043 // Compute the function info and LLVM type.
2044 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2045 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2046
2047 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2048 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002049 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002050 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00002051 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002052 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002053 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
Artem Belevich42e19492016-03-02 18:28:50 +00002054 // We need to emit device-side global CUDA variables even if a
2055 // variable does not have a definition -- we still need to define
2056 // host-side shadow for it.
2057 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2058 !VD->hasDefinition() &&
2059 (VD->hasAttr<CUDAConstantAttr>() ||
2060 VD->hasAttr<CUDADeviceAttr>());
2061 if (!MustEmitForCuda &&
2062 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
Richard Smithd9b90092016-07-02 01:32:16 +00002063 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2064 // If this declaration may have caused an inline variable definition to
2065 // change linkage, make sure that it's emitted.
2066 if (Context.getInlineVariableDefinitionKind(VD) ==
2067 ASTContext::InlineVariableDefinitionKind::Strong)
2068 GetAddrOfGlobalVar(VD);
Douglas Gregorbeecd582009-04-21 17:11:58 +00002069 return;
Richard Smithd9b90092016-07-02 01:32:16 +00002070 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002071 }
2072
Hans Wennborg43a0f992015-01-10 01:19:48 +00002073 // Defer code generation to first use when possible, e.g. if this is an inline
2074 // function. If the global must always be emitted, do it eagerly if possible
2075 // to benefit from cache locality.
2076 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002077 // Emit the definition if it can't be deferred.
2078 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002079 return;
2080 }
John McCall70013b62010-07-15 23:40:35 +00002081
2082 // If we're deferring emission of a C++ variable with an
2083 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002084 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00002085 cast<VarDecl>(Global)->hasInit()) {
2086 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00002087 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00002088 }
Hans Wennborg43a0f992015-01-10 01:19:48 +00002089
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002090 StringRef MangledName = getMangledName(GD);
Sanjoy Das70a60512017-05-01 06:12:13 +00002091 if (GetGlobalValue(MangledName) != nullptr) {
Hans Wennborg43a0f992015-01-10 01:19:48 +00002092 // The value has already been used and should therefore be emitted.
Sanjoy Das70a60512017-05-01 06:12:13 +00002093 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002094 } else if (MustBeEmitted(Global)) {
2095 // The value must be emitted, but cannot be emitted eagerly.
2096 assert(!MayBeEmittedEagerly(Global));
Sanjoy Das70a60512017-05-01 06:12:13 +00002097 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002098 } else {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002099 // Otherwise, remember that we saw a deferred decl with this name. The
2100 // first use of the mangled name will cause it to move into
2101 // DeferredDeclsToEmit.
2102 DeferredDecls[MangledName] = GD;
2103 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002104}
2105
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002106// Check if T is a class type with a destructor that's not dllimport.
2107static bool HasNonDllImportDtor(QualType T) {
2108 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2109 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2110 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2111 return true;
2112
2113 return false;
2114}
2115
Rafael Espindolac5941352011-10-26 20:41:06 +00002116namespace {
2117 struct FunctionIsDirectlyRecursive :
2118 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2119 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002120 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00002121 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002122 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2123 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002124 }
2125 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2126
2127 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002128 const FunctionDecl *FD = E->getDirectCallee();
2129 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00002130 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002131 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2132 if (Attr && Name == Attr->getLabel()) {
2133 Result = true;
2134 return false;
2135 }
2136 unsigned BuiltinID = FD->getBuiltinID();
David Majnemer41011f62015-06-25 23:50:40 +00002137 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
Rafael Espindolac5941352011-10-26 20:41:06 +00002138 return true;
Eric Christopher02d5d862015-08-06 01:01:12 +00002139 StringRef BuiltinName = BI.getName(BuiltinID);
Nick Lewycky9ed5b152012-01-18 03:41:19 +00002140 if (BuiltinName.startswith("__builtin_") &&
2141 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002142 Result = true;
2143 return false;
2144 }
2145 return true;
2146 }
2147 };
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002148
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002149 // Make sure we're not referencing non-imported vars or functions.
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002150 struct DLLImportFunctionVisitor
2151 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2152 bool SafeToInline = true;
2153
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002154 bool shouldVisitImplicitCode() const { return true; }
2155
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002156 bool VisitVarDecl(VarDecl *VD) {
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002157 if (VD->getTLSKind()) {
2158 // A thread-local variable cannot be imported.
2159 SafeToInline = false;
2160 return SafeToInline;
2161 }
2162
2163 // A variable definition might imply a destructor call.
2164 if (VD->isThisDeclarationADefinition())
2165 SafeToInline = !HasNonDllImportDtor(VD->getType());
2166
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002167 return SafeToInline;
2168 }
2169
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002170 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2171 if (const auto *D = E->getTemporary()->getDestructor())
2172 SafeToInline = D->hasAttr<DLLImportAttr>();
2173 return SafeToInline;
2174 }
2175
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002176 bool VisitDeclRefExpr(DeclRefExpr *E) {
2177 ValueDecl *VD = E->getDecl();
2178 if (isa<FunctionDecl>(VD))
2179 SafeToInline = VD->hasAttr<DLLImportAttr>();
2180 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2181 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2182 return SafeToInline;
2183 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002184
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002185 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2186 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2187 return SafeToInline;
2188 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002189
Hans Wennborg251c2042017-01-23 23:57:50 +00002190 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2191 CXXMethodDecl *M = E->getMethodDecl();
2192 if (!M) {
2193 // Call through a pointer to member function. This is safe to inline.
2194 SafeToInline = true;
2195 } else {
2196 SafeToInline = M->hasAttr<DLLImportAttr>();
2197 }
2198 return SafeToInline;
2199 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002200
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002201 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2202 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2203 return SafeToInline;
2204 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002205
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002206 bool VisitCXXNewExpr(CXXNewExpr *E) {
2207 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2208 return SafeToInline;
2209 }
2210 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002211}
Rafael Espindolac5941352011-10-26 20:41:06 +00002212
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002213// isTriviallyRecursive - Check if this function calls another
2214// decl that, because of the asm attribute or the other decl being a builtin,
2215// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00002216bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002217CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2218 StringRef Name;
2219 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00002220 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002221 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2222 if (!Attr)
2223 return false;
2224 Name = Attr->getLabel();
2225 } else {
2226 Name = FD->getName();
2227 }
Rafael Espindolac5941352011-10-26 20:41:06 +00002228
David Majnemer64b0bdf2015-06-30 04:41:18 +00002229 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002230 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00002231 return Walker.Result;
2232}
2233
Hans Wennborg93f75472016-09-13 21:08:20 +00002234bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002235 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00002236 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002237 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00002238 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00002239 return false;
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002240
2241 if (F->hasAttr<DLLImportAttr>()) {
2242 // Check whether it would be safe to inline this dllimport function.
2243 DLLImportFunctionVisitor Visitor;
2244 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2245 if (!Visitor.SafeToInline)
2246 return false;
Hans Wennborg93f75472016-09-13 21:08:20 +00002247
2248 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2249 // Implicit destructor invocations aren't captured in the AST, so the
2250 // check above can't see them. Check for them manually here.
2251 for (const Decl *Member : Dtor->getParent()->decls())
2252 if (isa<FieldDecl>(Member))
2253 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2254 return false;
2255 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2256 if (HasNonDllImportDtor(B.getType()))
2257 return false;
2258 }
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002259 }
2260
Rafael Espindolac5941352011-10-26 20:41:06 +00002261 // PR9614. Avoid cases where the source code is lying to us. An available
2262 // externally function should have an equivalent function somewhere else,
2263 // but a function that calls itself is clearly not equivalent to the real
2264 // implementation.
2265 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002266 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00002267}
2268
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002269bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2270 return CodeGenOpts.OptimizationLevel > 0;
2271}
2272
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002273void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002274 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002275
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002276 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00002277 Context.getSourceManager(),
2278 "Generating code for declaration");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002279
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002280 if (isa<FunctionDecl>(D)) {
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002281 // At -O0, don't generate IR for functions with available_externally
Douglas Gregora700f682010-07-13 06:02:28 +00002282 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002283 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00002284 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00002285
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002286 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +00002287 // Make sure to emit the definition(s) before we emit the thunks.
2288 // This is necessary for the generation of certain thunks.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002289 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002290 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002291 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002292 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Eli Friedman49a94b12011-05-06 17:27:27 +00002293 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002294 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002295
Douglas Gregora700f682010-07-13 06:02:28 +00002296 if (Method->isVirtual())
2297 getVTables().EmitThunks(GD);
2298
Eli Friedman49a94b12011-05-06 17:27:27 +00002299 return;
Douglas Gregora700f682010-07-13 06:02:28 +00002300 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00002301
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002302 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00002303 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002304
2305 if (const auto *VD = dyn_cast<VarDecl>(D))
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002306 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002307
David Blaikie83d382b2011-09-23 05:06:16 +00002308 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00002309}
2310
Andrey Bokhankocab58582015-08-31 13:20:44 +00002311static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2312 llvm::Function *NewFn);
2313
Erich Keane281d20b2018-01-08 21:34:17 +00002314void CodeGenModule::emitMultiVersionFunctions() {
2315 for (GlobalDecl GD : MultiVersionFuncs) {
2316 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2317 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2318 getContext().forEachMultiversionedFunctionVersion(
2319 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2320 GlobalDecl CurGD{
2321 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2322 StringRef MangledName = getMangledName(CurGD);
2323 llvm::Constant *Func = GetGlobalValue(MangledName);
2324 if (!Func) {
2325 if (CurFD->isDefined()) {
2326 EmitGlobalFunctionDefinition(CurGD, nullptr);
2327 Func = GetGlobalValue(MangledName);
2328 } else {
2329 const CGFunctionInfo &FI =
2330 getTypes().arrangeGlobalDeclaration(GD);
2331 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2332 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2333 /*DontDefer=*/false, ForDefinition);
2334 }
2335 assert(Func && "This should have just been created");
2336 }
2337 Options.emplace_back(getTarget(), cast<llvm::Function>(Func),
2338 CurFD->getAttr<TargetAttr>()->parse());
2339 });
2340
2341 llvm::Function *ResolverFunc = cast<llvm::Function>(
2342 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
Erich Keane0a6fde42018-01-16 19:49:52 +00002343 if (supportsCOMDAT())
2344 ResolverFunc->setComdat(
2345 getModule().getOrInsertComdat(ResolverFunc->getName()));
Erich Keane281d20b2018-01-08 21:34:17 +00002346 std::stable_sort(
2347 Options.begin(), Options.end(),
2348 std::greater<CodeGenFunction::MultiVersionResolverOption>());
2349 CodeGenFunction CGF(*this);
2350 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2351 }
2352}
2353
2354/// If an ifunc for the specified mangled name is not in the module, create and
2355/// return an llvm IFunc Function with the specified type.
2356llvm::Constant *
2357CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
2358 StringRef MangledName,
2359 const FunctionDecl *FD) {
2360 std::string IFuncName = (MangledName + ".ifunc").str();
2361 if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
2362 return IFuncGV;
2363
2364 // Since this is the first time we've created this IFunc, make sure
2365 // that we put this multiversioned function into the list to be
2366 // replaced later.
2367 MultiVersionFuncs.push_back(GD);
2368
2369 std::string ResolverName = (MangledName + ".resolver").str();
2370 llvm::Type *ResolverType = llvm::FunctionType::get(
2371 llvm::PointerType::get(DeclTy,
2372 Context.getTargetAddressSpace(FD->getType())),
2373 false);
2374 llvm::Constant *Resolver =
2375 GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2376 /*ForVTable=*/false);
2377 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2378 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2379 GIF->setName(IFuncName);
2380 SetCommonAttributes(FD, GIF);
2381
2382 return GIF;
2383}
2384
Chris Lattnerd4808922009-03-22 21:03:39 +00002385/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2386/// module, create and return an llvm Function with the specified type. If there
2387/// is something in the module with the specified name, return it potentially
2388/// bitcasted to the right type.
2389///
2390/// If D is non-null, it specifies a decl that correspond to this. This is used
2391/// to set the attributes on the function when it is first created.
Reid Klecknerde864822017-03-21 16:57:30 +00002392llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2393 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2394 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2395 ForDefinition_t IsForDefinition) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002396 const Decl *D = GD.getDecl();
2397
Erich Keane281d20b2018-01-08 21:34:17 +00002398 // Any attempts to use a MultiVersion function should result in retrieving
2399 // the iFunc instead. Name Mangling will handle the rest of the changes.
2400 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002401 // For the device mark the function as one that should be emitted.
2402 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
Alexey Bataev6d944102018-05-02 15:45:28 +00002403 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002404 !DontDefer && !IsForDefinition) {
2405 const FunctionDecl *FDDef = FD->getDefinition();
2406 GlobalDecl GDDef;
2407 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2408 GDDef = GlobalDecl(CD, GD.getCtorType());
2409 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2410 GDDef = GlobalDecl(DD, GD.getDtorType());
2411 else
2412 GDDef = GlobalDecl(FDDef);
2413 addDeferredDeclToEmit(GDDef);
2414 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002415
Erich Keane281d20b2018-01-08 21:34:17 +00002416 if (FD->isMultiVersion() && FD->getAttr<TargetAttr>()->isDefaultVersion()) {
2417 UpdateMultiVersionNames(GD, FD);
2418 if (!IsForDefinition)
2419 return GetOrCreateMultiVersionIFunc(GD, Ty, MangledName, FD);
2420 }
2421 }
2422
Chris Lattnera85d68e2009-03-21 09:25:43 +00002423 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002424 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002425 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002426 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002427 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002428 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002429 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002430 }
2431
Hans Wennborg0a20f542014-08-29 00:16:06 +00002432 // Handle dropped DLL attributes.
Rafael Espindolac9643d82018-03-29 16:45:18 +00002433 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
Hans Wennborg0a20f542014-08-29 00:16:06 +00002434 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
Rafael Espindolac9643d82018-03-29 16:45:18 +00002435 setDSOLocal(Entry);
2436 }
Hans Wennborg0a20f542014-08-29 00:16:06 +00002437
Andrey Bokhankocab58582015-08-31 13:20:44 +00002438 // If there are two attempts to define the same mangled name, issue an
2439 // error.
2440 if (IsForDefinition && !Entry->isDeclaration()) {
2441 GlobalDecl OtherGD;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002442 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2443 // to make sure that we issue an error only once.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002444 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2445 (GD.getCanonicalDecl().getDecl() !=
2446 OtherGD.getCanonicalDecl().getDecl()) &&
2447 DiagnosedConflictingDefinitions.insert(GD).second) {
2448 getDiags().Report(D->getLocation(),
2449 diag::err_duplicate_mangled_name);
2450 getDiags().Report(OtherGD.getDecl()->getLocation(),
2451 diag::note_previous_definition);
2452 }
2453 }
2454
2455 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2456 (Entry->getType()->getElementType() == Ty)) {
Chris Lattnera85d68e2009-03-21 09:25:43 +00002457 return Entry;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002458 }
Mike Stump11289f42009-09-09 15:08:12 +00002459
Chris Lattnera85d68e2009-03-21 09:25:43 +00002460 // Make sure the result is of the correct type.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002461 // (If function is requested for a definition, we always need to create a new
2462 // function, not just return a bitcast.)
2463 if (!IsForDefinition)
2464 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00002465 }
Mike Stump11289f42009-09-09 15:08:12 +00002466
Eli Friedmancc522d92009-11-09 05:07:37 +00002467 // This function doesn't have a complete type (for example, the return
2468 // type is an incomplete struct). Use a fake type instead, and make
2469 // sure not to try to set attributes.
2470 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00002471
Chris Lattner2192fe52011-07-18 04:24:23 +00002472 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00002473 if (isa<llvm::FunctionType>(Ty)) {
2474 FTy = cast<llvm::FunctionType>(Ty);
2475 } else {
John McCall9dc0db22011-05-15 01:53:33 +00002476 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00002477 IsIncompleteFunction = true;
2478 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002479
2480 llvm::Function *F =
2481 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2482 Entry ? StringRef() : MangledName, &getModule());
2483
2484 // If we already created a function with the same mangled name (but different
2485 // type) before, take its name and add it to the list of functions to be
2486 // replaced with F at the end of CodeGen.
2487 //
2488 // This happens if there is a prototype for a function (e.g. "int f()") and
2489 // then a definition of a different type (e.g. "int f(int x)").
2490 if (Entry) {
2491 F->takeName(Entry);
2492
2493 // This might be an implementation of a function without a prototype, in
2494 // which case, try to do special replacement of calls which match the new
2495 // prototype. The really key thing here is that we also potentially drop
2496 // arguments from the call site so as to make a direct call, which makes the
2497 // inliner happier and suppresses a number of optimizer warnings (!) about
2498 // dropping arguments.
2499 if (!Entry->use_empty()) {
2500 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2501 Entry->removeDeadConstantUsers();
2502 }
2503
2504 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2505 F, Entry->getType()->getElementType()->getPointerTo());
2506 addGlobalValReplacement(Entry, BC);
2507 }
2508
John McCall7ec50432010-03-19 23:29:14 +00002509 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002510 if (D)
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002511 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Reid Klecknerde864822017-03-21 16:57:30 +00002512 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2513 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
Reid Kleckneree4930b2017-05-02 22:07:37 +00002514 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Bill Wendling9a677922013-01-23 00:21:06 +00002515 }
Eli Friedmancc522d92009-11-09 05:07:37 +00002516
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002517 if (!DontDefer) {
2518 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2519 // each other bottoming out with the base dtor. Therefore we emit non-base
2520 // dtors on usage, even if there is no dtor definition in the TU.
2521 if (D && isa<CXXDestructorDecl>(D) &&
2522 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2523 GD.getDtorType()))
Sanjoy Das70a60512017-05-01 06:12:13 +00002524 addDeferredDeclToEmit(GD);
John McCall357d0f32010-12-15 04:00:32 +00002525
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002526 // This is the first use or definition of a mangled name. If there is a
2527 // deferred decl with this name, remember that we need to emit it at the end
2528 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002529 auto DDI = DeferredDecls.find(MangledName);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002530 if (DDI != DeferredDecls.end()) {
2531 // Move the potentially referenced deferred decl to the
2532 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2533 // don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002534 addDeferredDeclToEmit(DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002535 DeferredDecls.erase(DDI);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002536
2537 // Otherwise, there are cases we have to worry about where we're
2538 // using a declaration for which we must emit a definition but where
2539 // we might not find a top-level definition:
2540 // - member functions defined inline in their classes
2541 // - friend functions defined inline in some class
2542 // - special member functions with implicit definitions
2543 // If we ever change our AST traversal to walk into class methods,
2544 // this will be unnecessary.
2545 //
2546 // We also don't emit a definition for a function if it's going to be an
Richard Smith46bb5812014-08-01 01:56:39 +00002547 // entry in a vtable, unless it's already marked as used.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002548 } else if (getLangOpts().CPlusPlus && D) {
2549 // Look for a declaration that's lexically in a record.
Richard Smith46bb5812014-08-01 01:56:39 +00002550 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2551 FD = FD->getPreviousDecl()) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002552 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Richard Smith46bb5812014-08-01 01:56:39 +00002553 if (FD->doesThisDeclarationHaveABody()) {
Sanjoy Das70a60512017-05-01 06:12:13 +00002554 addDeferredDeclToEmit(GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002555 break;
2556 }
John McCall357d0f32010-12-15 04:00:32 +00002557 }
Richard Smith46bb5812014-08-01 01:56:39 +00002558 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002559 }
Chris Lattner45470942009-03-21 09:44:56 +00002560 }
Mike Stump11289f42009-09-09 15:08:12 +00002561
John McCalld06fb862010-04-28 00:00:30 +00002562 // Make sure the result is of the requested type.
2563 if (!IsIncompleteFunction) {
2564 assert(F->getType()->getElementType() == Ty);
2565 return F;
2566 }
2567
Chris Lattnera5f58b02011-07-09 17:41:47 +00002568 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00002569 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002570}
2571
Chris Lattnerd4808922009-03-22 21:03:39 +00002572/// GetAddrOfFunction - Return the address of the given function. If Ty is
2573/// non-null, then this function will use the specified type if it has to
2574/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00002575llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00002576 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002577 bool ForVTable,
Andrey Bokhankocab58582015-08-31 13:20:44 +00002578 bool DontDefer,
John McCalld195d4c2016-11-30 23:25:13 +00002579 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002580 // If there was no specific requested type, just convert it now.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002581 if (!Ty) {
2582 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2583 auto CanonTy = Context.getCanonicalType(FD->getType());
2584 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2585 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002586
Reid Kleckner28103252018-03-16 22:20:57 +00002587 // Devirtualized destructor calls may come through here instead of via
2588 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2589 // of the complete destructor when necessary.
2590 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
2591 if (getTarget().getCXXABI().isMicrosoft() &&
2592 GD.getDtorType() == Dtor_Complete &&
2593 DD->getParent()->getNumVBases() == 0)
2594 GD = GlobalDecl(DD, Dtor_Base);
2595 }
2596
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002597 StringRef MangledName = getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002598 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +00002599 /*IsThunk=*/false, llvm::AttributeList(),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002600 IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002601}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002602
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002603static const FunctionDecl *
2604GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2605 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2606 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2607
2608 IdentifierInfo &CII = C.Idents.get(Name);
2609 for (const auto &Result : DC->lookup(&CII))
2610 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2611 return FD;
2612
2613 if (!C.getLangOpts().CPlusPlus)
2614 return nullptr;
2615
2616 // Demangle the premangled name from getTerminateFn()
2617 IdentifierInfo &CXXII =
Reid Klecknerfb931542018-03-16 20:36:49 +00002618 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002619 ? C.Idents.get("terminate")
2620 : C.Idents.get(Name);
2621
2622 for (const auto &N : {"__cxxabiv1", "std"}) {
2623 IdentifierInfo &NS = C.Idents.get(N);
2624 for (const auto &Result : DC->lookup(&NS)) {
2625 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2626 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2627 for (const auto &Result : LSD->lookup(&NS))
2628 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2629 break;
2630
2631 if (ND)
2632 for (const auto &Result : ND->lookup(&CXXII))
2633 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2634 return FD;
2635 }
2636 }
2637
2638 return nullptr;
2639}
2640
Chris Lattnerd4808922009-03-22 21:03:39 +00002641/// CreateRuntimeFunction - Create a new runtime function with the specified
2642/// type and name.
2643llvm::Constant *
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002644CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
Reid Klecknerde864822017-03-21 16:57:30 +00002645 llvm::AttributeList ExtraAttrs,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002646 bool Local) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002647 llvm::Constant *C =
2648 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002649 /*DontDefer=*/false, /*IsThunk=*/false,
2650 ExtraAttrs);
2651
2652 if (auto *F = dyn_cast<llvm::Function>(C)) {
2653 if (F->empty()) {
John McCall882987f2013-02-28 19:01:20 +00002654 F->setCallingConv(getRuntimeCC());
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002655
2656 if (!Local && getTriple().isOSBinFormatCOFF() &&
Martell Maloneb22e6002017-11-04 02:15:49 +00002657 !getCodeGenOpts().LTOVisibilityPublicStd &&
2658 !getTriple().isWindowsGNUEnvironment()) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002659 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2660 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2661 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2662 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2663 }
2664 }
Rafael Espindola3c9be622018-03-20 20:27:30 +00002665 setDSOLocal(F);
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002666 }
2667 }
2668
John McCall882987f2013-02-28 19:01:20 +00002669 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00002670}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002671
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002672/// CreateBuiltinFunction - Create a new builtin function with the specified
2673/// type and name.
2674llvm::Constant *
Reid Klecknerde864822017-03-21 16:57:30 +00002675CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2676 llvm::AttributeList ExtraAttrs) {
Rafael Espindola1193c372018-03-22 18:03:13 +00002677 return CreateRuntimeFunction(FTy, Name, ExtraAttrs, true);
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002678}
2679
Richard Smithe070fd22012-02-17 06:48:11 +00002680/// isTypeConstant - Determine whether an object of this type can be emitted
2681/// as a constant.
2682///
2683/// If ExcludeCtor is true, the duration when the object's constructor runs
2684/// will not be considered. The caller will need to verify that the object is
2685/// not written to during its construction.
2686bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2687 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00002688 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00002689
David Blaikiebbafb8a2012-03-11 07:00:24 +00002690 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00002691 if (const CXXRecordDecl *Record
2692 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2693 return ExcludeCtor && !Record->hasMutableFields() &&
2694 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00002695 }
Richard Smithe070fd22012-02-17 06:48:11 +00002696
Eli Friedmanb095e152009-12-11 21:23:03 +00002697 return true;
2698}
2699
Chris Lattnerd4808922009-03-22 21:03:39 +00002700/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2701/// create and return an llvm GlobalVariable with the specified type. If there
2702/// is something in the module with the specified name, return it potentially
2703/// bitcasted to the right type.
2704///
2705/// If D is non-null, it specifies a decl that correspond to this. This is used
2706/// to set the attributes on the global when it is first created.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002707///
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002708/// If IsForDefinition is true, it is guaranteed that an actual global with
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002709/// type Ty will be returned, not conversion of a variable with the same
2710/// mangled name but some other type.
John McCall7ec50432010-03-19 23:29:14 +00002711llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002712CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00002713 llvm::PointerType *Ty,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002714 const VarDecl *D,
John McCalld195d4c2016-11-30 23:25:13 +00002715 ForDefinition_t IsForDefinition) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00002716 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002717 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00002718 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002719 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002720 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002721 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002722 }
2723
Hans Wennborg0a20f542014-08-29 00:16:06 +00002724 // Handle dropped DLL attributes.
2725 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2726 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2727
Alexey Bataev03f270c2018-03-30 18:31:07 +00002728 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
2729 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
2730
Chris Lattnerd4808922009-03-22 21:03:39 +00002731 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00002732 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00002733
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002734 // If there are two attempts to define the same mangled name, issue an
2735 // error.
2736 if (IsForDefinition && !Entry->isDeclaration()) {
2737 GlobalDecl OtherGD;
2738 const VarDecl *OtherD;
2739
2740 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2741 // to make sure that we issue an error only once.
Artem Belevich2c323a02016-05-19 18:00:18 +00002742 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002743 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2744 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2745 OtherD->hasInit() &&
2746 DiagnosedConflictingDefinitions.insert(D).second) {
2747 getDiags().Report(D->getLocation(),
2748 diag::err_duplicate_mangled_name);
2749 getDiags().Report(OtherGD.getDecl()->getLocation(),
2750 diag::note_previous_definition);
2751 }
2752 }
2753
Chris Lattner3bfce182009-03-21 08:03:33 +00002754 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00002755 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2756 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2757
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002758 // (If global is requested for a definition, we always need to create a new
2759 // global, not just return a bitcast.)
2760 if (!IsForDefinition)
2761 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00002762 }
Mike Stump11289f42009-09-09 15:08:12 +00002763
Yaxun Liucbf647c2017-07-08 13:24:52 +00002764 auto AddrSpace = GetGlobalVarAddressSpace(D);
2765 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2766
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002767 auto *GV = new llvm::GlobalVariable(
2768 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002769 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Yaxun Liucbf647c2017-07-08 13:24:52 +00002770 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00002771
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002772 // If we already created a global with the same mangled name (but different
2773 // type) before, take its name and remove it from its parent.
2774 if (Entry) {
2775 GV->takeName(Entry);
2776
2777 if (!Entry->use_empty()) {
2778 llvm::Constant *NewPtrForOldDecl =
2779 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2780 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2781 }
2782
2783 Entry->eraseFromParent();
2784 }
2785
Chris Lattner45470942009-03-21 09:44:56 +00002786 // This is the first use or definition of a mangled name. If there is a
2787 // deferred decl with this name, remember that we need to emit it at the end
2788 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002789 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00002790 if (DDI != DeferredDecls.end()) {
2791 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2792 // list, and remove it from DeferredDecls (since we don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002793 addDeferredDeclToEmit(DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00002794 DeferredDecls.erase(DDI);
2795 }
Mike Stump11289f42009-09-09 15:08:12 +00002796
Chris Lattner3bfce182009-03-21 08:03:33 +00002797 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00002798 if (D) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00002799 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
2800 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
2801
Mike Stump18bb9282009-05-16 07:57:57 +00002802 // FIXME: This code is overly simple and should be merged with other global
2803 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00002804 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00002805
Ulrich Weigand46084382015-04-21 17:27:59 +00002806 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2807
Jake Ehrlichba874ad2017-11-29 00:54:20 +00002808 setLinkageForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00002809
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002810 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00002811 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00002812 CXXThreadLocals.push_back(D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +00002813 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002814 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00002815
Rafael Espindola3dd49812018-02-23 00:22:15 +00002816 setGVProperties(GV, D);
2817
Hans Wennborgfeedf852013-11-21 00:15:56 +00002818 // If required by the ABI, treat declarations of static data members with
2819 // inline initializers as definitions.
Hans Wennborg56fc62b2014-07-17 20:25:23 +00002820 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Hans Wennborgfeedf852013-11-21 00:15:56 +00002821 EmitGlobalVarDefinition(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +00002822 }
Robert Lyttonf80d6882014-05-02 09:33:30 +00002823
Erich Keane99fdfb62017-09-26 23:42:34 +00002824 // Emit section information for extern variables.
2825 if (D->hasExternalStorage()) {
2826 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
2827 GV->setSection(SA->getName());
2828 }
2829
Robert Lyttonf80d6882014-05-02 09:33:30 +00002830 // Handle XCore specific ABI requirements.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00002831 if (getTriple().getArch() == llvm::Triple::xcore &&
Robert Lyttonf80d6882014-05-02 09:33:30 +00002832 D->getLanguageLinkage() == CLanguageLinkage &&
2833 D->getType().isConstant(Context) &&
2834 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2835 GV->setSection(".cp.rodata");
Mehdi Amini7cb1b302017-09-05 03:58:35 +00002836
2837 // Check if we a have a const declaration with an initializer, we may be
2838 // able to emit it as available_externally to expose it's value to the
2839 // optimizer.
2840 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
2841 D->getType().isConstQualified() && !GV->hasInitializer() &&
2842 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
2843 const auto *Record =
2844 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
2845 bool HasMutableFields = Record && Record->hasMutableFields();
2846 if (!HasMutableFields) {
2847 const VarDecl *InitDecl;
2848 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2849 if (InitExpr) {
2850 ConstantEmitter emitter(*this);
2851 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
2852 if (Init) {
2853 auto *InitType = Init->getType();
2854 if (GV->getType()->getElementType() != InitType) {
2855 // The type of the initializer does not match the definition.
2856 // This happens when an initializer has a different type from
2857 // the type of the global (because of padding at the end of a
2858 // structure for instance).
2859 GV->setName(StringRef());
2860 // Make a new global with the correct type, this is now guaranteed
2861 // to work.
2862 auto *NewGV = cast<llvm::GlobalVariable>(
2863 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
2864
2865 // Erase the old global, since it is no longer used.
George Burgess IV00f70bd2018-03-01 05:43:23 +00002866 GV->eraseFromParent();
Mehdi Amini7cb1b302017-09-05 03:58:35 +00002867 GV = NewGV;
2868 } else {
2869 GV->setInitializer(Init);
2870 GV->setConstant(true);
2871 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
2872 }
2873 emitter.finalize(GV);
2874 }
2875 }
2876 }
2877 }
Chris Lattnerd4808922009-03-22 21:03:39 +00002878 }
Mike Stump11289f42009-09-09 15:08:12 +00002879
Alexander Richardson6d989432017-10-15 18:48:14 +00002880 LangAS ExpectedAS =
Yaxun Liucbf647c2017-07-08 13:24:52 +00002881 D ? D->getType().getAddressSpace()
Alexander Richardson6d989432017-10-15 18:48:14 +00002882 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
Benjamin Kramer6fbfdec2017-07-08 14:14:57 +00002883 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
2884 Ty->getPointerAddressSpace());
Yaxun Liucbf647c2017-07-08 13:24:52 +00002885 if (AddrSpace != ExpectedAS)
2886 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
2887 ExpectedAS, Ty);
Matt Arsenault00e65b22013-11-15 02:19:52 +00002888
2889 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002890}
2891
Andrey Bokhankocab58582015-08-31 13:20:44 +00002892llvm::Constant *
2893CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
John McCalld195d4c2016-11-30 23:25:13 +00002894 ForDefinition_t IsForDefinition) {
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002895 const Decl *D = GD.getDecl();
2896 if (isa<CXXConstructorDecl>(D))
2897 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002898 getFromCtorType(GD.getCtorType()),
2899 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2900 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002901 else if (isa<CXXDestructorDecl>(D))
2902 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002903 getFromDtorType(GD.getDtorType()),
2904 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2905 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002906 else if (isa<CXXMethodDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00002907 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002908 cast<CXXMethodDecl>(D));
Andrey Bokhankocab58582015-08-31 13:20:44 +00002909 auto Ty = getTypes().GetFunctionType(*FInfo);
2910 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2911 IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002912 } else if (isa<FunctionDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00002913 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2914 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2915 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2916 IsForDefinition);
2917 } else
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002918 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002919 IsForDefinition);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002920}
Chris Lattnerd4808922009-03-22 21:03:39 +00002921
Anders Carlssonda80af32011-01-29 18:20:20 +00002922llvm::GlobalVariable *
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002923CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00002924 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00002925 llvm::GlobalValue::LinkageTypes Linkage) {
2926 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00002927 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00002928
Anders Carlssonda80af32011-01-29 18:20:20 +00002929 if (GV) {
2930 // Check if the variable has the right type.
2931 if (GV->getType()->getElementType() == Ty)
2932 return GV;
2933
2934 // Because C++ name mangling, the only way we can end up with an already
2935 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00002936 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00002937 OldGV = GV;
2938 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002939
Anders Carlssonda80af32011-01-29 18:20:20 +00002940 // Create a new variable.
2941 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00002942 Linkage, nullptr, Name);
2943
Anders Carlssonda80af32011-01-29 18:20:20 +00002944 if (OldGV) {
2945 // Replace occurrences of the old variable if needed.
2946 GV->takeName(OldGV);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002947
Anders Carlssonda80af32011-01-29 18:20:20 +00002948 if (!OldGV->use_empty()) {
2949 llvm::Constant *NewPtrForOldDecl =
2950 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2951 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2952 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002953
Anders Carlssonda80af32011-01-29 18:20:20 +00002954 OldGV->eraseFromParent();
2955 }
Rafael Espindolacb92c192015-01-15 23:18:01 +00002956
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002957 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2958 !GV->hasAvailableExternallyLinkage())
2959 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00002960
Anders Carlssonda80af32011-01-29 18:20:20 +00002961 return GV;
2962}
2963
Chris Lattnerd4808922009-03-22 21:03:39 +00002964/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2965/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00002966/// then it will be created with the specified type instead of whatever the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002967/// normal requested type would be. If IsForDefinition is true, it is guaranteed
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002968/// that an actual global with type Ty will be returned, not conversion of a
2969/// variable with the same mangled name but some other type.
Chris Lattnerd4808922009-03-22 21:03:39 +00002970llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002971 llvm::Type *Ty,
John McCalld195d4c2016-11-30 23:25:13 +00002972 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002973 assert(D->hasGlobalStorage() && "Not a global variable");
2974 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00002975 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00002976 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00002977
Chris Lattner2192fe52011-07-18 04:24:23 +00002978 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00002979 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00002980
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002981 StringRef MangledName = getMangledName(D);
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002982 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002983}
2984
2985/// CreateRuntimeVariable - Create a new runtime global variable with the
2986/// specified type and name.
2987llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00002988CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002989 StringRef Name) {
Rafael Espindola6ab4ae42018-03-21 01:30:16 +00002990 auto *Ret =
2991 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2992 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
2993 return Ret;
Chris Lattnerd4808922009-03-22 21:03:39 +00002994}
2995
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002996void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2997 assert(!D->getInit() && "Cannot emit definite definitions here!");
2998
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002999 StringRef MangledName = getMangledName(D);
3000 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3001
3002 // We already have a definition, not declaration, with the same mangled name.
3003 // Emitting of declaration is not required (and actually overwrites emitted
3004 // definition).
3005 if (GV && !GV->isDeclaration())
3006 return;
3007
3008 // If we have not seen a reference to this variable yet, place it into the
3009 // deferred declarations table to be emitted if needed later.
3010 if (!MustBeEmitted(D) && !GV) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003011 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003012 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00003013 }
3014
3015 // The tentative definition is the only definition.
Reid Kleckner953fe032015-12-05 01:52:14 +00003016 EmitGlobalVarDefinition(D);
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003017}
3018
Chris Lattner2192fe52011-07-18 04:24:23 +00003019CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00003020 return Context.toCharUnitsFromBits(
3021 getDataLayout().getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00003022}
3023
Alexander Richardson6d989432017-10-15 18:48:14 +00003024LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3025 LangAS AddrSpace = LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003026 if (LangOpts.OpenCL) {
Alexander Richardson6d989432017-10-15 18:48:14 +00003027 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003028 assert(AddrSpace == LangAS::opencl_global ||
3029 AddrSpace == LangAS::opencl_constant ||
3030 AddrSpace == LangAS::opencl_local ||
3031 AddrSpace >= LangAS::FirstTargetAddressSpace);
3032 return AddrSpace;
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003033 }
3034
Yaxun Liucbf647c2017-07-08 13:24:52 +00003035 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3036 if (D && D->hasAttr<CUDAConstantAttr>())
3037 return LangAS::cuda_constant;
3038 else if (D && D->hasAttr<CUDASharedAttr>())
3039 return LangAS::cuda_shared;
3040 else
3041 return LangAS::cuda_device;
3042 }
3043
3044 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003045}
3046
Yaxun Liudaceb1e2018-05-14 19:20:12 +00003047LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3048 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3049 if (LangOpts.OpenCL)
3050 return LangAS::opencl_constant;
3051 if (auto AS = getTarget().getConstantAddressSpace())
3052 return AS.getValue();
3053 return LangAS::Default;
3054}
3055
3056// In address space agnostic languages, string literals are in default address
3057// space in AST. However, certain targets (e.g. amdgcn) request them to be
3058// emitted in constant address space in LLVM IR. To be consistent with other
3059// parts of AST, string literal global variables in constant address space
3060// need to be casted to default address space before being put into address
3061// map and referenced by other part of CodeGen.
3062// In OpenCL, string literals are in constant address space in AST, therefore
3063// they should not be casted to default address space.
3064static llvm::Constant *
3065castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3066 llvm::GlobalVariable *GV) {
3067 llvm::Constant *Cast = GV;
3068 if (!CGM.getLangOpts().OpenCL) {
3069 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3070 if (AS != LangAS::Default)
3071 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3072 CGM, GV, AS.getValue(), LangAS::Default,
3073 GV->getValueType()->getPointerTo(
3074 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3075 }
3076 }
3077 return Cast;
3078}
3079
Richard Smithdf931ce2013-04-06 05:00:46 +00003080template<typename SomeDecl>
3081void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3082 llvm::GlobalValue *GV) {
3083 if (!getLangOpts().CPlusPlus)
3084 return;
3085
3086 // Must have 'used' attribute, or else inline assembly can't rely on
3087 // the name existing.
3088 if (!D->template hasAttr<UsedAttr>())
3089 return;
3090
3091 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00003092 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00003093 return;
3094
3095 // Must be in an extern "C" context. Entities declared directly within
3096 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003097 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00003098 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00003099 return;
3100
3101 // OK, this is an internal linkage entity inside an extern "C" linkage
3102 // specification. Make a note of that so we can give it the "expected"
3103 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00003104 std::pair<StaticExternCMap::iterator, bool> R =
3105 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00003106
3107 // If we have multiple internal linkage entities with the same name
3108 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00003109 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00003110 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00003111}
3112
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003113static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3114 if (!CGM.supportsCOMDAT())
3115 return false;
3116
3117 if (D.hasAttr<SelectAnyAttr>())
3118 return true;
3119
3120 GVALinkage Linkage;
3121 if (auto *VD = dyn_cast<VarDecl>(&D))
3122 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3123 else
3124 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3125
3126 switch (Linkage) {
3127 case GVA_Internal:
3128 case GVA_AvailableExternally:
3129 case GVA_StrongExternal:
3130 return false;
3131 case GVA_DiscardableODR:
3132 case GVA_StrongODR:
3133 return true;
3134 }
3135 llvm_unreachable("No such linkage");
3136}
3137
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003138void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3139 llvm::GlobalObject &GO) {
3140 if (!shouldBeInCOMDAT(*this, D))
3141 return;
3142 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3143}
3144
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003145/// Pass IsTentative as true if you want to create a tentative definition.
3146void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3147 bool IsTentative) {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003148 // OpenCL global variables of sampler type are translated to function calls,
3149 // therefore no need to be translated.
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003150 QualType ASTTy = D->getType();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003151 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3152 return;
3153
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00003154 // If this is OpenMP device, check if it is legal to emit this global
3155 // normally.
3156 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3157 OpenMPRuntime->emitTargetGlobalVariable(D))
3158 return;
3159
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003160 llvm::Constant *Init = nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00003161 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3162 bool NeedsGlobalCtor = false;
3163 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00003164
Richard Smithdafff942012-01-14 04:30:29 +00003165 const VarDecl *InitDecl;
3166 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003167
John McCallde0fe072017-08-15 21:42:52 +00003168 Optional<ConstantEmitter> emitter;
3169
Artem Belevich97c01c32016-02-02 22:29:48 +00003170 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3171 // as part of their declaration." Sema has already checked for
3172 // error cases, so we just need to set Init to UndefValue.
3173 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
3174 D->hasAttr<CUDASharedAttr>())
Jingyue Wu284ebe22015-08-22 05:49:28 +00003175 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
Artem Belevich97c01c32016-02-02 22:29:48 +00003176 else if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00003177 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003178 // implicitly initialized with { 0 }.
3179 //
3180 // Note that tentative definitions are only emitted at the end of
3181 // a translation unit, so they should never have incomplete
3182 // type. In addition, EmitTentativeDefinition makes sure that we
3183 // never attempt to emit a tentative definition if a real one
3184 // exists. A use may still exists, however, so we still may need
3185 // to do a RAUW.
3186 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00003187 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003188 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003189 initializedGlobalDecl = GlobalDecl(D);
John McCallde0fe072017-08-15 21:42:52 +00003190 emitter.emplace(*this);
3191 Init = emitter->tryEmitForInitializer(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003192
Fariborz Jahanian63628032012-06-26 16:06:38 +00003193 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00003194 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00003195 if (D->getType()->isReferenceType())
3196 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00003197
David Blaikiebbafb8a2012-03-11 07:00:24 +00003198 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003199 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00003200 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003201 } else {
3202 ErrorUnsupported(D, "static initializer");
3203 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3204 }
John McCall70013b62010-07-15 23:40:35 +00003205 } else {
3206 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00003207 // initializer position (just in case this entry was delayed) if we
3208 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003209 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00003210 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00003211 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003212 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003213
Chris Lattner2192fe52011-07-18 04:24:23 +00003214 llvm::Type* InitType = Init->getType();
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003215 llvm::Constant *Entry =
John McCalld195d4c2016-11-30 23:25:13 +00003216 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
Mike Stump11289f42009-09-09 15:08:12 +00003217
Chris Lattner149927c2009-03-21 09:16:30 +00003218 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003219 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00003220 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00003221 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3222 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00003223 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00003224 Entry = CE->getOperand(0);
3225 }
Mike Stump11289f42009-09-09 15:08:12 +00003226
Chris Lattner149927c2009-03-21 09:16:30 +00003227 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003228 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003229
Chris Lattner149927c2009-03-21 09:16:30 +00003230 // We have a definition after a declaration with the wrong type.
3231 // We must make a new GlobalVariable* and update everything that used OldGV
3232 // (a declaration or tentative definition) with the new GlobalVariable*
3233 // (which will be a definition).
3234 //
3235 // This happens if there is a prototype for a global (e.g.
3236 // "extern int x[];") and then a definition of a different type (e.g.
3237 // "int x[10];"). This also happens when an initializer has a different type
3238 // from the type of the global (this happens with unions).
Yaxun Liucbf647c2017-07-08 13:24:52 +00003239 if (!GV || GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003240 GV->getType()->getAddressSpace() !=
Yaxun Liucbf647c2017-07-08 13:24:52 +00003241 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
Mike Stump11289f42009-09-09 15:08:12 +00003242
John McCall7ec50432010-03-19 23:29:14 +00003243 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003244 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00003245
Chris Lattner149927c2009-03-21 09:16:30 +00003246 // Make a new global with the correct type, this is now guaranteed to work.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003247 GV = cast<llvm::GlobalVariable>(
John McCalld195d4c2016-11-30 23:25:13 +00003248 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
Chris Lattnera85d68e2009-03-21 09:25:43 +00003249
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003250 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00003251 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00003252 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00003253 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003254
3255 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00003256 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00003257 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00003258
Richard Smithdf931ce2013-04-06 05:00:46 +00003259 MaybeHandleStaticInExternC(D, GV);
3260
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003261 if (D->hasAttr<AnnotateAttr>())
3262 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00003263
Artem Belevich42e19492016-03-02 18:28:50 +00003264 // Set the llvm linkage type as appropriate.
3265 llvm::GlobalValue::LinkageTypes Linkage =
3266 getLLVMLinkageVarDefinition(D, GV->isConstant());
3267
Jingyue Wu284ebe22015-08-22 05:49:28 +00003268 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3269 // the device. [...]"
3270 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3271 // __device__, declares a variable that: [...]
3272 // Is accessible from all the threads within the grid and from the host
3273 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3274 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
Artem Belevich42e19492016-03-02 18:28:50 +00003275 if (GV && LangOpts.CUDA) {
3276 if (LangOpts.CUDAIsDevice) {
3277 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3278 GV->setExternallyInitialized(true);
3279 } else {
3280 // Host-side shadows of external declarations of device-side
3281 // global variables become internal definitions. These have to
3282 // be internal in order to prevent name conflicts with global
3283 // host variables with the same name in a different TUs.
3284 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3285 Linkage = llvm::GlobalValue::InternalLinkage;
3286
3287 // Shadow variables and their properties must be registered
3288 // with CUDA runtime.
3289 unsigned Flags = 0;
3290 if (!D->hasDefinition())
3291 Flags |= CGCUDARuntime::ExternDeviceVar;
3292 if (D->hasAttr<CUDAConstantAttr>())
3293 Flags |= CGCUDARuntime::ConstantDeviceVar;
3294 getCUDARuntime().registerDeviceVar(*GV, Flags);
3295 } else if (D->hasAttr<CUDASharedAttr>())
3296 // __shared__ variables are odd. Shadows do get created, but
3297 // they are not registered with the CUDA runtime, so they
3298 // can't really be used to access their device-side
3299 // counterparts. It's not clear yet whether it's nvcc's bug or
3300 // a feature, but we've got to do the same for compatibility.
3301 Linkage = llvm::GlobalValue::InternalLinkage;
3302 }
Jingyue Wu284ebe22015-08-22 05:49:28 +00003303 }
John McCallde0fe072017-08-15 21:42:52 +00003304
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003305 GV->setInitializer(Init);
John McCallde0fe072017-08-15 21:42:52 +00003306 if (emitter) emitter->finalize(GV);
Chris Lattnerf49573d2009-08-05 05:20:29 +00003307
3308 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00003309 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3310 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00003311
Hans Wennborg899ded92014-10-16 20:52:46 +00003312 // If it is in a read-only section, mark it 'constant'.
3313 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3314 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3315 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3316 GV->setConstant(true);
3317 }
3318
Ken Dyck160146e2010-01-27 17:10:57 +00003319 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00003320
David Majnemer35ab3282014-06-11 04:08:55 +00003321
Manman Ren68150262015-11-11 22:42:31 +00003322 // On Darwin, if the normal linkage of a C++ thread_local variable is
3323 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3324 // copies within a linkage unit; otherwise, the backing variable has
3325 // internal linkage and all accesses should just be calls to the
David Majnemer35ab3282014-06-11 04:08:55 +00003326 // Itanium-specified entry point, which has the normal linkage of the
Manman Ren68150262015-11-11 22:42:31 +00003327 // variable. This is to preserve the ability to change the implementation
3328 // behind the scenes.
David Majnemerbb525f7c2014-10-15 22:38:23 +00003329 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00003330 Context.getTargetInfo().getTriple().isOSDarwin() &&
Manman Ren68150262015-11-11 22:42:31 +00003331 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3332 !llvm::GlobalVariable::isWeakLinkage(Linkage))
David Majnemerbb525f7c2014-10-15 22:38:23 +00003333 Linkage = llvm::GlobalValue::InternalLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00003334
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003335 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00003336 if (D->hasAttr<DLLImportAttr>())
3337 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3338 else if (D->hasAttr<DLLExportAttr>())
3339 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00003340 else
3341 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00003342
Yaxun Liu402804b2016-12-15 08:09:08 +00003343 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
Chris Lattnerf49573d2009-08-05 05:20:29 +00003344 // common vars aren't constant even if declared const.
3345 GV->setConstant(false);
Yaxun Liu402804b2016-12-15 08:09:08 +00003346 // Tentative definition of global variables may be initialized with
3347 // non-zero null pointers. In this case they should have weak linkage
3348 // since common linkage must have zero initializer and must not have
3349 // explicit section therefore cannot have non-zero initial value.
3350 if (!GV->getInitializer()->isNullValue())
3351 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3352 }
Daniel Dunbard272cca2009-04-10 20:26:50 +00003353
Rafael Espindola502f65a2014-05-05 20:21:03 +00003354 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00003355
David Majnemerbb525f7c2014-10-15 22:38:23 +00003356 if (D->getTLSKind() && !GV->isThreadLocal()) {
3357 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003358 CXXThreadLocals.push_back(D);
David Majnemerbb525f7c2014-10-15 22:38:23 +00003359 setTLSMode(GV, *D);
3360 }
3361
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003362 maybeSetTrivialComdat(*D, *GV);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003363
John McCallcdf7ef52010-11-06 09:44:32 +00003364 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00003365 if (NeedsGlobalCtor || NeedsGlobalDtor)
3366 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00003367
Alexey Samsonov4b8de112014-08-01 21:35:28 +00003368 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany28a26c82012-08-21 06:53:28 +00003369
Sanjiv Gupta158143a2008-06-05 08:59:10 +00003370 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00003371 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00003372 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00003373 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003374}
Chris Lattner09153c02007-06-22 18:48:09 +00003375
David Majnemerc017d362014-08-05 00:01:13 +00003376static bool isVarDeclStrongDefinition(const ASTContext &Context,
Nico Weber608e7682015-04-15 23:04:24 +00003377 CodeGenModule &CGM, const VarDecl *D,
3378 bool NoCommon) {
David Majnemer9832a3d2014-04-10 16:53:16 +00003379 // Don't give variables common linkage if -fno-common was specified unless it
3380 // was overridden by a NoCommon attribute.
3381 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3382 return true;
3383
3384 // C11 6.9.2/2:
3385 // A declaration of an identifier for an object that has file scope without
3386 // an initializer, and without a storage-class specifier or with the
3387 // storage-class specifier static, constitutes a tentative definition.
3388 if (D->getInit() || D->hasExternalStorage())
3389 return true;
3390
3391 // A variable cannot be both common and exist in a section.
3392 if (D->hasAttr<SectionAttr>())
3393 return true;
3394
Javed Absar2a67c9e2017-06-05 10:11:57 +00003395 // A variable cannot be both common and exist in a section.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003396 // We don't try to determine which is the right section in the front-end.
Javed Absar2a67c9e2017-06-05 10:11:57 +00003397 // If no specialized section name is applicable, it will resort to default.
3398 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3399 D->hasAttr<PragmaClangDataSectionAttr>() ||
3400 D->hasAttr<PragmaClangRodataSectionAttr>())
3401 return true;
3402
David Majnemer9832a3d2014-04-10 16:53:16 +00003403 // Thread local vars aren't considered common linkage.
3404 if (D->getTLSKind())
3405 return true;
3406
3407 // Tentative definitions marked with WeakImportAttr are true definitions.
3408 if (D->hasAttr<WeakImportAttr>())
3409 return true;
3410
Nico Weber608e7682015-04-15 23:04:24 +00003411 // A variable cannot be both common and exist in a comdat.
3412 if (shouldBeInCOMDAT(CGM, *D))
3413 return true;
3414
Sanjay Patel2f9303a2016-06-30 21:02:40 +00003415 // Declarations with a required alignment do not have common linkage in MSVC
David Majnemerc017d362014-08-05 00:01:13 +00003416 // mode.
David Majnemer3f021502015-10-08 04:53:31 +00003417 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemere1a0b2e2015-02-03 08:49:32 +00003418 if (D->hasAttr<AlignedAttr>())
3419 return true;
3420 QualType VarType = D->getType();
3421 if (Context.isAlignmentRequired(VarType))
3422 return true;
3423
3424 if (const auto *RT = VarType->getAs<RecordType>()) {
3425 const RecordDecl *RD = RT->getDecl();
3426 for (const FieldDecl *FD : RD->fields()) {
3427 if (FD->isBitField())
3428 continue;
3429 if (FD->hasAttr<AlignedAttr>())
3430 return true;
3431 if (Context.isAlignmentRequired(FD->getType()))
3432 return true;
3433 }
3434 }
3435 }
David Majnemerc017d362014-08-05 00:01:13 +00003436
David Majnemer9832a3d2014-04-10 16:53:16 +00003437 return false;
3438}
3439
Hans Wennborg1a3a0742014-05-14 19:54:53 +00003440llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00003441 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003442 if (Linkage == GVA_Internal)
3443 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003444
3445 if (D->hasAttr<WeakAttr>()) {
3446 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003447 return llvm::GlobalVariable::WeakODRLinkage;
3448 else
3449 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003450 }
3451
3452 // We are guaranteed to have a strong definition somewhere else,
3453 // so we can use available_externally linkage.
3454 if (Linkage == GVA_AvailableExternally)
David Blaikie9ffe5a32017-01-30 05:00:26 +00003455 return llvm::GlobalValue::AvailableExternallyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003456
David Majnemer27d69db2014-04-28 22:17:59 +00003457 // Note that Apple's kernel linker doesn't support symbol
3458 // coalescing, so we need to avoid linkonce and weak linkages there.
3459 // Normally, this means we just map to internal, but for explicit
3460 // instantiations we'll map to external.
3461
3462 // In C++, the compiler has to emit a definition in every translation unit
3463 // that references the function. We should use linkonce_odr because
3464 // a) if all references in this translation unit are optimized away, we
3465 // don't need to codegen it. b) if the function persists, it needs to be
3466 // merged with other definitions. c) C++ has the ODR, so we know the
3467 // definition is dependable.
3468 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00003469 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00003470 : llvm::Function::InternalLinkage;
3471
3472 // An explicit instantiation of a template has weak linkage, since
3473 // explicit instantiations can occur in multiple translation units
3474 // and must all be equivalent. However, we are not allowed to
3475 // throw away these explicit instantiations.
Justin Lebar27ee1302016-06-30 18:41:33 +00003476 //
3477 // We don't currently support CUDA device code spread out across multiple TUs,
3478 // so say that CUDA templates are either external (for kernels) or internal.
3479 // This lets llvm perform aggressive inter-procedural optimizations.
3480 if (Linkage == GVA_StrongODR) {
3481 if (Context.getLangOpts().AppleKext)
3482 return llvm::Function::ExternalLinkage;
3483 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3484 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3485 : llvm::Function::InternalLinkage;
3486 return llvm::Function::WeakODRLinkage;
3487 }
David Majnemer27d69db2014-04-28 22:17:59 +00003488
David Majnemer27d69db2014-04-28 22:17:59 +00003489 // C++ doesn't have tentative definitions and thus cannot have common
3490 // linkage.
3491 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Nico Weber608e7682015-04-15 23:04:24 +00003492 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
David Majnemerc017d362014-08-05 00:01:13 +00003493 CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00003494 return llvm::GlobalVariable::CommonLinkage;
3495
David Majnemer27d69db2014-04-28 22:17:59 +00003496 // selectany symbols are externally visible, so use weak instead of
3497 // linkonce. MSVC optimizes away references to const selectany globals, so
3498 // all definitions should be the same and ODR linkage should be used.
3499 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3500 if (D->hasAttr<SelectAnyAttr>())
3501 return llvm::GlobalVariable::WeakODRLinkage;
3502
3503 // Otherwise, we have strong external linkage.
3504 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003505 return llvm::GlobalVariable::ExternalLinkage;
3506}
3507
David Majnemer27d69db2014-04-28 22:17:59 +00003508llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3509 const VarDecl *VD, bool IsConstant) {
3510 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00003511 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00003512}
3513
John McCall49954ca2012-12-12 22:21:47 +00003514/// Replace the uses of a function that was declared with a non-proto type.
3515/// We want to silently drop extra arguments from call sites
3516static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3517 llvm::Function *newFn) {
3518 // Fast path.
3519 if (old->use_empty()) return;
3520
3521 llvm::Type *newRetTy = newFn->getReturnType();
3522 SmallVector<llvm::Value*, 4> newArgs;
David Majnemer0b17d442015-12-15 21:27:59 +00003523 SmallVector<llvm::OperandBundleDef, 1> newBundles;
John McCall49954ca2012-12-12 22:21:47 +00003524
3525 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3526 ui != ue; ) {
3527 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003528 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00003529
3530 // Recognize and replace uses of bitcasts. Most calls to
3531 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003532 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00003533 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3534 replaceUsesOfNonProtoConstant(bitcast, newFn);
3535 continue;
3536 }
3537
3538 // Recognize calls to the function.
3539 llvm::CallSite callSite(user);
3540 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003541 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00003542
3543 // If the return types don't match exactly, then we can't
3544 // transform this call unless it's dead.
3545 if (callSite->getType() != newRetTy && !callSite->use_empty())
3546 continue;
3547
3548 // Get the call site's attribute list.
Reid Kleckner7f720332017-04-13 00:58:09 +00003549 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
Reid Klecknerde864822017-03-21 16:57:30 +00003550 llvm::AttributeList oldAttrs = callSite.getAttributes();
John McCall49954ca2012-12-12 22:21:47 +00003551
John McCall49954ca2012-12-12 22:21:47 +00003552 // If the function was passed too few arguments, don't transform.
3553 unsigned newNumArgs = newFn->arg_size();
3554 if (callSite.arg_size() < newNumArgs) continue;
3555
3556 // If extra arguments were passed, we silently drop them.
3557 // If any of the types mismatch, we don't transform.
3558 unsigned argNo = 0;
3559 bool dontTransform = false;
Reid Kleckner7f720332017-04-13 00:58:09 +00003560 for (llvm::Argument &A : newFn->args()) {
3561 if (callSite.getArgument(argNo)->getType() != A.getType()) {
John McCall49954ca2012-12-12 22:21:47 +00003562 dontTransform = true;
3563 break;
3564 }
3565
3566 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00003567 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
Reid Kleckner7f720332017-04-13 00:58:09 +00003568 argNo++;
John McCall49954ca2012-12-12 22:21:47 +00003569 }
3570 if (dontTransform)
3571 continue;
3572
John McCall49954ca2012-12-12 22:21:47 +00003573 // Okay, we can transform this. Create the new call instruction and copy
3574 // over the required information.
3575 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3576
David Majnemer0b17d442015-12-15 21:27:59 +00003577 // Copy over any operand bundles.
3578 callSite.getOperandBundlesAsDefs(newBundles);
3579
John McCall49954ca2012-12-12 22:21:47 +00003580 llvm::CallSite newCall;
3581 if (callSite.isCall()) {
David Majnemer0b17d442015-12-15 21:27:59 +00003582 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003583 callSite.getInstruction());
3584 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003585 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCall49954ca2012-12-12 22:21:47 +00003586 newCall = llvm::InvokeInst::Create(newFn,
3587 oldInvoke->getNormalDest(),
3588 oldInvoke->getUnwindDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003589 newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003590 callSite.getInstruction());
3591 }
3592 newArgs.clear(); // for the next iteration
3593
3594 if (!newCall->getType()->isVoidTy())
3595 newCall->takeName(callSite.getInstruction());
Reid Kleckner7f720332017-04-13 00:58:09 +00003596 newCall.setAttributes(llvm::AttributeList::get(
3597 newFn->getContext(), oldAttrs.getFnAttributes(),
3598 oldAttrs.getRetAttributes(), newArgAttrs));
John McCall49954ca2012-12-12 22:21:47 +00003599 newCall.setCallingConv(callSite.getCallingConv());
3600
3601 // Finally, remove the old call, replacing any uses with the new one.
3602 if (!callSite->use_empty())
3603 callSite->replaceAllUsesWith(newCall.getInstruction());
3604
3605 // Copy debug location attached to CI.
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00003606 if (callSite->getDebugLoc())
John McCall49954ca2012-12-12 22:21:47 +00003607 newCall->setDebugLoc(callSite->getDebugLoc());
David Majnemer0b17d442015-12-15 21:27:59 +00003608
John McCall49954ca2012-12-12 22:21:47 +00003609 callSite->eraseFromParent();
3610 }
3611}
3612
Chris Lattner36797ab2009-05-05 06:16:31 +00003613/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3614/// implement a function with no prototype, e.g. "int foo() {}". If there are
3615/// existing call uses of the old function in the module, this adjusts them to
3616/// call the new function directly.
3617///
3618/// This is not just a cleanup: the always_inline pass requires direct calls to
3619/// functions to be able to inline them. If there is a bitcast in the way, it
3620/// won't inline them. Instcombine normally deletes these calls, but it isn't
3621/// run at -O0.
3622static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3623 llvm::Function *NewFn) {
3624 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00003625 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00003626
John McCall49954ca2012-12-12 22:21:47 +00003627 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00003628}
3629
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003630void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
David Majnemer60e5bdc2016-07-11 04:28:21 +00003631 auto DK = VD->isThisDeclarationADefinition();
3632 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3633 return;
3634
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003635 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3636 // If we have a definition, this might be a deferred decl. If the
3637 // instantiation is explicit, make sure we emit it at the end.
3638 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3639 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003640
3641 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00003642}
Daniel Dunbar9c426522008-07-29 23:18:29 +00003643
Rafael Espindolacd7743b2013-12-09 16:01:03 +00003644void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3645 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003646 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00003647
John McCall46288ef2011-03-09 08:12:35 +00003648 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00003649 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3650 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00003651
Chris Lattnereb7466d2009-05-12 20:58:15 +00003652 // Get or create the prototype for the function.
Andrey Bokhankocab58582015-08-31 13:20:44 +00003653 if (!GV || (GV->getType()->getElementType() != Ty))
3654 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3655 /*DontDefer=*/true,
John McCalld195d4c2016-11-30 23:25:13 +00003656 ForDefinition));
Mike Stump11289f42009-09-09 15:08:12 +00003657
Andrey Bokhankocab58582015-08-31 13:20:44 +00003658 // Already emitted.
3659 if (!GV->isDeclaration())
Renato Golinc640ff62015-04-15 08:44:40 +00003660 return;
Mike Stump11289f42009-09-09 15:08:12 +00003661
John McCall8e7cb6d2010-11-02 21:04:24 +00003662 // We need to set linkage and visibility on the function before
3663 // generating code for it because various parts of IR generation
3664 // want to propagate this information down (e.g. to local static
3665 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003666 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00003667 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003668
Rafael Espindolae033c8c2014-05-08 15:26:12 +00003669 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Rafael Espindolab7350042018-03-01 00:35:47 +00003670 setGVProperties(Fn, GD);
John McCall8e7cb6d2010-11-02 21:04:24 +00003671
Richard Smithdf931ce2013-04-06 05:00:46 +00003672 MaybeHandleStaticInExternC(D, Fn);
3673
Yaxun Liu4306f202018-04-20 17:01:03 +00003674 if (D->hasAttr<CUDAGlobalAttr>())
3675 getTargetCodeGenInfo().setCUDAKernelCallingConvention(Fn);
3676
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003677 maybeSetTrivialComdat(*D, *Fn);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003678
John McCalla738c252011-03-09 04:27:21 +00003679 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00003680
Rafael Espindolae4e78132018-03-01 00:00:02 +00003681 setNonAliasAttributes(GD, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00003682 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00003683
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003684 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003685 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003686 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003687 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003688 if (D->hasAttr<AnnotateAttr>())
3689 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003690}
3691
John McCall7ec50432010-03-19 23:29:14 +00003692void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003693 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003694 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00003695 assert(AA && "Not an alias?");
3696
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003697 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00003698
Hal Finkel0e2b9752015-09-04 21:49:21 +00003699 if (AA->getAliasee() == MangledName) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003700 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Hal Finkel0e2b9752015-09-04 21:49:21 +00003701 return;
3702 }
3703
John McCall7ec50432010-03-19 23:29:14 +00003704 // If there is a definition in the module, then it wins over the alias.
3705 // This is dubious, but allow it to be safe. Just ignore the alias.
3706 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3707 if (Entry && !Entry->isDeclaration())
3708 return;
3709
Rafael Espindola208b5c02013-10-22 19:26:13 +00003710 Aliases.push_back(GD);
3711
Chris Lattner2192fe52011-07-18 04:24:23 +00003712 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00003713
3714 // Create a reference to the named value. This ensures that it is emitted
3715 // if a deferred decl.
3716 llvm::Constant *Aliasee;
3717 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00003718 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00003719 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00003720 else
John McCall7ec50432010-03-19 23:29:14 +00003721 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00003722 llvm::PointerType::getUnqual(DeclTy),
David Majnemerbb525f7c2014-10-15 22:38:23 +00003723 /*D=*/nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00003724
3725 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00003726 auto *GA = llvm::GlobalAlias::create(
David Blaikie2a791d72015-09-14 18:38:22 +00003727 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00003728
Chris Lattner54041692009-03-22 21:47:11 +00003729 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00003730 if (GA->getAliasee() == Entry) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003731 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Rafael Espindolab2633b92014-05-16 19:35:48 +00003732 return;
3733 }
3734
John McCall7ec50432010-03-19 23:29:14 +00003735 assert(Entry->isDeclaration());
3736
Chris Lattner54041692009-03-22 21:47:11 +00003737 // If there is a declaration in the module, then we had an extern followed
3738 // by the alias, as in:
3739 // extern int test6();
3740 // ...
3741 // int test6() __attribute__((alias("test7")));
3742 //
3743 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00003744 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003745
Owen Andersonade90fd2009-07-29 18:54:39 +00003746 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00003747 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00003748 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00003749 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00003750 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00003751 }
Mike Stump11289f42009-09-09 15:08:12 +00003752
Daniel Dunbar38932572009-04-14 08:05:55 +00003753 // Set attributes which are particular to an alias; this is a
3754 // specialization of the attributes which may be set on a global
3755 // variable/function.
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00003756 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3757 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00003758 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3759 }
3760
David Majnemerbb525f7c2014-10-15 22:38:23 +00003761 if (const auto *VD = dyn_cast<VarDecl>(D))
3762 if (VD->getTLSKind())
3763 setTLSMode(GA, *VD);
3764
Rafael Espindolab7350042018-03-01 00:35:47 +00003765 SetCommonAttributes(GD, GA);
Chris Lattner54041692009-03-22 21:47:11 +00003766}
3767
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003768void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3769 const auto *D = cast<ValueDecl>(GD.getDecl());
3770 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3771 assert(IFA && "Not an ifunc?");
3772
3773 StringRef MangledName = getMangledName(GD);
3774
3775 if (IFA->getResolver() == MangledName) {
3776 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3777 return;
3778 }
3779
3780 // Report an error if some definition overrides ifunc.
3781 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3782 if (Entry && !Entry->isDeclaration()) {
3783 GlobalDecl OtherGD;
3784 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3785 DiagnosedConflictingDefinitions.insert(GD).second) {
3786 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3787 Diags.Report(OtherGD.getDecl()->getLocation(),
3788 diag::note_previous_definition);
3789 }
3790 return;
3791 }
3792
3793 Aliases.push_back(GD);
3794
3795 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3796 llvm::Constant *Resolver =
3797 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3798 /*ForVTable=*/false);
3799 llvm::GlobalIFunc *GIF =
3800 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3801 "", Resolver, &getModule());
3802 if (Entry) {
3803 if (GIF->getResolver() == Entry) {
3804 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3805 return;
3806 }
3807 assert(Entry->isDeclaration());
3808
3809 // If there is a declaration in the module, then we had an extern followed
3810 // by the ifunc, as in:
3811 // extern int test();
3812 // ...
3813 // int test() __attribute__((ifunc("resolver")));
3814 //
3815 // Remove it and replace uses of it with the ifunc.
3816 GIF->takeName(Entry);
3817
3818 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3819 Entry->getType()));
3820 Entry->eraseFromParent();
3821 } else
3822 GIF->setName(MangledName);
3823
Rafael Espindola75c649c2018-03-01 00:06:55 +00003824 SetCommonAttributes(GD, GIF);
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003825}
3826
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003827llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00003828 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00003829 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003830 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00003831}
Chris Lattner1eec6602007-08-31 04:31:45 +00003832
David Blaikie2e804282015-04-05 22:47:07 +00003833static llvm::StringMapEntry<llvm::GlobalVariable *> &
3834GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3835 const StringLiteral *Literal, bool TargetIsLSB,
3836 bool &IsUTF16, unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003837 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003838 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00003839
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00003840 // Check for simple case.
3841 if (!Literal->containsNonAsciiOrNull()) {
3842 StringLength = NumBytes;
David Blaikie13156b62014-11-19 03:06:06 +00003843 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00003844 }
3845
Bill Wendling82b87f12012-03-30 00:26:17 +00003846 // Otherwise, convert the UTF8 literals into a string of shorts.
3847 IsUTF16 = true;
3848
Justin Lebar90910552016-09-30 00:38:45 +00003849 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3850 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3851 llvm::UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00003852
Justin Lebar90910552016-09-30 00:38:45 +00003853 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3854 ToPtr + NumBytes, llvm::strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00003855
Daniel Dunbar91ade142009-07-23 23:41:22 +00003856 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00003857 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00003858
Bill Wendling82b87f12012-03-30 00:26:17 +00003859 // Add an explicit null.
3860 *ToPtr = 0;
David Blaikie13156b62014-11-19 03:06:06 +00003861 return *Map.insert(std::make_pair(
3862 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3863 (StringLength + 1) * 2),
3864 nullptr)).first;
Daniel Dunbar64509b22009-07-23 22:52:48 +00003865}
3866
John McCall7f416cc2015-09-08 08:05:57 +00003867ConstantAddress
Daniel Dunbar64509b22009-07-23 22:52:48 +00003868CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3869 unsigned StringLength = 0;
3870 bool isUTF16 = false;
David Blaikie2e804282015-04-05 22:47:07 +00003871 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3872 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3873 getDataLayout().isLittleEndian(), isUTF16,
3874 StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00003875
David Blaikie13156b62014-11-19 03:06:06 +00003876 if (auto *C = Entry.second)
John McCall7f416cc2015-09-08 08:05:57 +00003877 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Mike Stump11289f42009-09-09 15:08:12 +00003878
Chris Lattnerece04092012-02-07 00:39:47 +00003879 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00003880 llvm::Constant *Zeros[] = { Zero, Zero };
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003881
Chris Lattneraa64ca22009-07-16 16:48:25 +00003882 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00003883 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003884 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00003885 Ty = llvm::ArrayType::get(Ty, 0);
Rafael Espindoladca06022018-03-20 15:48:00 +00003886 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(
3887 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"));
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003888
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003889 if (getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003890 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3891 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3892 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003893
3894 const VarDecl *VD = nullptr;
3895 for (const auto &Result : DC->lookup(&II))
3896 if ((VD = dyn_cast<VarDecl>(Result)))
3897 break;
3898
3899 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
Rafael Espindoladca06022018-03-20 15:48:00 +00003900 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3901 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003902 } else {
Rafael Espindoladca06022018-03-20 15:48:00 +00003903 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3904 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003905 }
3906 }
Rafael Espindoladca06022018-03-20 15:48:00 +00003907 setDSOLocal(GV);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003908
Daniel Dunbard644ad62008-08-23 18:37:06 +00003909 // Decay array -> ptr
Saleem Abdulrasool4fab7452016-09-11 01:25:15 +00003910 CFConstantStringClassRef =
3911 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003912 }
Mike Stump11289f42009-09-09 15:08:12 +00003913
Anders Carlssonc2480a52008-11-15 18:54:24 +00003914 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00003915
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003916 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00003917
John McCall23c9dc62016-11-28 22:18:27 +00003918 ConstantInitBuilder Builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003919 auto Fields = Builder.beginStruct(STy);
Douglas Gregor91f84212008-12-11 16:49:14 +00003920
Anders Carlssonb04ea612007-08-21 00:21:21 +00003921 // Class pointer.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003922 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
Mike Stump11289f42009-09-09 15:08:12 +00003923
Anders Carlssonb04ea612007-08-21 00:21:21 +00003924 // Flags.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003925 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
Anders Carlsson157c3212009-08-16 05:55:31 +00003926
Anders Carlssonb04ea612007-08-21 00:21:21 +00003927 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00003928 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00003929 if (isUTF16) {
Craig Topperc005cc02015-09-27 03:44:08 +00003930 auto Arr = llvm::makeArrayRef(
David Blaikie13156b62014-11-19 03:06:06 +00003931 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3932 Entry.first().size() / 2);
Bill Wendling82b87f12012-03-30 00:26:17 +00003933 C = llvm::ConstantDataArray::get(VMContext, Arr);
3934 } else {
David Blaikie13156b62014-11-19 03:06:06 +00003935 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling82b87f12012-03-30 00:26:17 +00003936 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00003937
Bill Wendling86131f22012-01-10 08:46:39 +00003938 // Note: -fwritable-strings doesn't make the backing store strings of
3939 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003940 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00003941 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3942 llvm::GlobalValue::PrivateLinkage, C, ".str");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003943 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigandfa806422013-05-06 16:23:57 +00003944 // Don't enforce the target's minimum global alignment, since the only use
3945 // of the string is via this class initializer.
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003946 CharUnits Align = isUTF16
3947 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3948 : getContext().getTypeAlignInChars(getContext().CharTy);
3949 GV->setAlignment(Align.getQuantity());
3950
3951 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3952 // Without it LLVM can merge the string with a non unnamed_addr one during
3953 // LTO. Doing that changes the section it ends in, which surprises ld64.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003954 if (getTriple().isOSBinFormatMachO())
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003955 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3956 : "__TEXT,__cstring,cstring_literals");
Bill Wendling82b87f12012-03-30 00:26:17 +00003957
3958 // String.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003959 llvm::Constant *Str =
David Blaikied3c127e2015-05-07 17:27:56 +00003960 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00003961
Bill Wendling82b87f12012-03-30 00:26:17 +00003962 if (isUTF16)
3963 // Cast the UTF16 string to the correct type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003964 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3965 Fields.add(Str);
Bill Wendling82b87f12012-03-30 00:26:17 +00003966
Anders Carlssonb04ea612007-08-21 00:21:21 +00003967 // String length.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003968 auto Ty = getTypes().ConvertType(getContext().LongTy);
3969 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00003970
John McCall7f416cc2015-09-08 08:05:57 +00003971 CharUnits Alignment = getPointerAlign();
3972
Anders Carlssonb04ea612007-08-21 00:21:21 +00003973 // The struct.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003974 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3975 /*isConstant=*/false,
3976 llvm::GlobalVariable::PrivateLinkage);
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003977 switch (getTriple().getObjectFormat()) {
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003978 case llvm::Triple::UnknownObjectFormat:
3979 llvm_unreachable("unknown file format");
3980 case llvm::Triple::COFF:
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003981 case llvm::Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00003982 case llvm::Triple::Wasm:
Saleem Abdulrasool0295f8c2016-07-09 01:59:51 +00003983 GV->setSection("cfstring");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003984 break;
3985 case llvm::Triple::MachO:
3986 GV->setSection("__DATA,__cfstring");
3987 break;
3988 }
David Blaikie13156b62014-11-19 03:06:06 +00003989 Entry.second = GV;
Mike Stump11289f42009-09-09 15:08:12 +00003990
John McCall7f416cc2015-09-08 08:05:57 +00003991 return ConstantAddress(GV, Alignment);
Anders Carlssonb04ea612007-08-21 00:21:21 +00003992}
Chris Lattnerfb300092007-11-28 05:34:05 +00003993
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +00003994bool CodeGenModule::getExpressionLocationsEnabled() const {
3995 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
3996}
3997
Douglas Gregor636e2002011-08-09 17:23:49 +00003998QualType CodeGenModule::getObjCFastEnumerationStateType() {
3999 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004000 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00004001 D->startDefinition();
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004002
Douglas Gregor636e2002011-08-09 17:23:49 +00004003 QualType FieldTypes[] = {
4004 Context.UnsignedLongTy,
4005 Context.getPointerType(Context.getObjCIdType()),
4006 Context.getPointerType(Context.UnsignedLongTy),
4007 Context.getConstantArrayType(Context.UnsignedLongTy,
4008 llvm::APInt(32, 5), ArrayType::Normal, 0)
4009 };
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004010
Douglas Gregor636e2002011-08-09 17:23:49 +00004011 for (size_t i = 0; i < 4; ++i) {
4012 FieldDecl *Field = FieldDecl::Create(Context,
4013 D,
4014 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004015 SourceLocation(), nullptr,
4016 FieldTypes[i], /*TInfo=*/nullptr,
4017 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00004018 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004019 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00004020 Field->setAccess(AS_public);
4021 D->addDecl(Field);
4022 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004023
Douglas Gregor636e2002011-08-09 17:23:49 +00004024 D->completeDefinition();
4025 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4026 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004027
Douglas Gregor636e2002011-08-09 17:23:49 +00004028 return ObjCFastEnumerationStateType;
4029}
4030
Eli Friedmanfcec6302011-11-01 02:23:42 +00004031llvm::Constant *
4032CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4033 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004034
Eli Friedmanfcec6302011-11-01 02:23:42 +00004035 // Don't emit it as the address of the string, emit the string data itself
4036 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00004037 if (E->getCharByteWidth() == 1) {
4038 SmallString<64> Str(E->getString());
4039
4040 // Resize the string to the right size, which is indicated by its type.
4041 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4042 Str.resize(CAT->getSize().getZExtValue());
4043 return llvm::ConstantDataArray::getString(VMContext, Str, false);
4044 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004045
4046 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00004047 llvm::Type *ElemTy = AType->getElementType();
4048 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00004049
4050 // Wide strings have either 2-byte or 4-byte elements.
4051 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4052 SmallVector<uint16_t, 32> Elements;
4053 Elements.reserve(NumElements);
4054
4055 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4056 Elements.push_back(E->getCodeUnit(i));
4057 Elements.resize(NumElements);
4058 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00004059 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004060
Chris Lattner02cb1712012-02-06 22:52:04 +00004061 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4062 SmallVector<uint32_t, 32> Elements;
4063 Elements.reserve(NumElements);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004064
Chris Lattner02cb1712012-02-06 22:52:04 +00004065 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4066 Elements.push_back(E->getCodeUnit(i));
4067 Elements.resize(NumElements);
4068 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00004069}
4070
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004071static llvm::GlobalVariable *
4072GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4073 CodeGenModule &CGM, StringRef GlobalName,
John McCall7f416cc2015-09-08 08:05:57 +00004074 CharUnits Alignment) {
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004075 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4076 CGM.getStringLiteralAddressSpace());
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004077
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004078 llvm::Module &M = CGM.getModule();
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004079 // Create a global variable for this string
4080 auto *GV = new llvm::GlobalVariable(
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004081 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4082 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +00004083 GV->setAlignment(Alignment.getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004084 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004085 if (GV->isWeakForLinker()) {
4086 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4087 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4088 }
Rafael Espindola0d40f122018-03-20 20:42:55 +00004089 CGM.setDSOLocal(GV);
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004090
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004091 return GV;
4092}
4093
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004094/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4095/// constant array for the given string literal.
John McCall7f416cc2015-09-08 08:05:57 +00004096ConstantAddress
Alexey Bataevec474782014-10-09 08:45:04 +00004097CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4098 StringRef Name) {
John McCall7f416cc2015-09-08 08:05:57 +00004099 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
James Molloye735b2b2014-05-09 16:28:56 +00004100
Richard Smith00db2f12014-07-29 21:20:12 +00004101 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4102 llvm::GlobalVariable **Entry = nullptr;
David Majnemer58e5bee2014-03-24 21:43:36 +00004103 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004104 Entry = &ConstantStringMap[C];
4105 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004106 if (Alignment.getQuantity() > GV->getAlignment())
4107 GV->setAlignment(Alignment.getQuantity());
4108 return ConstantAddress(GV, Alignment);
David Majnemer58e5bee2014-03-24 21:43:36 +00004109 }
Eli Friedman49ddc5f2009-11-16 05:55:46 +00004110 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00004111
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004112 SmallString<256> MangledNameBuffer;
4113 StringRef GlobalVariableName;
4114 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00004115
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004116 // Mangle the string literal if the ABI allows for it. However, we cannot
4117 // do this if we are compiling with ASan or -fwritable-strings because they
4118 // rely on strings having normal linkage.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004119 if (!LangOpts.WritableStrings &&
4120 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004121 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
4122 llvm::raw_svector_ostream Out(MangledNameBuffer);
4123 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
David Majnemer58e5bee2014-03-24 21:43:36 +00004124
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004125 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4126 GlobalVariableName = MangledNameBuffer;
4127 } else {
4128 LT = llvm::GlobalValue::PrivateLinkage;
Alexey Bataevec474782014-10-09 08:45:04 +00004129 GlobalVariableName = Name;
David Majnemer58e5bee2014-03-24 21:43:36 +00004130 }
4131
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004132 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4133 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004134 *Entry = GV;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00004135
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00004136 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4137 QualType());
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004138
4139 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4140 Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004141}
4142
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004143/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4144/// array for the given ObjCEncodeExpr node.
John McCall7f416cc2015-09-08 08:05:57 +00004145ConstantAddress
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004146CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4147 std::string Str;
4148 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00004149
4150 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004151}
4152
Alexey Samsonovadc90372014-06-04 20:25:57 +00004153/// GetAddrOfConstantCString - Returns a pointer to a character array containing
4154/// the literal and a terminating '\0' character.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004155/// The result has pointer to array type.
John McCall7f416cc2015-09-08 08:05:57 +00004156ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4157 const std::string &Str, const char *GlobalName) {
Alexey Samsonovadc90372014-06-04 20:25:57 +00004158 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall7f416cc2015-09-08 08:05:57 +00004159 CharUnits Alignment =
4160 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004161
Richard Smith00db2f12014-07-29 21:20:12 +00004162 llvm::Constant *C =
4163 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4164
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004165 // Don't share any string literals if strings aren't constant.
Richard Smith00db2f12014-07-29 21:20:12 +00004166 llvm::GlobalVariable **Entry = nullptr;
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004167 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004168 Entry = &ConstantStringMap[C];
4169 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004170 if (Alignment.getQuantity() > GV->getAlignment())
4171 GV->setAlignment(Alignment.getQuantity());
4172 return ConstantAddress(GV, Alignment);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004173 }
4174 }
4175
Daniel Dunbar08b216a2009-03-31 23:42:16 +00004176 // Get the default prefix if a name wasn't specified.
4177 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00004178 GlobalName = ".str";
Chris Lattnerfb300092007-11-28 05:34:05 +00004179 // Create a global variable for this.
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004180 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4181 GlobalName, Alignment);
4182 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004183 *Entry = GV;
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004184
4185 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4186 Alignment);
Chris Lattnerfb300092007-11-28 05:34:05 +00004187}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004188
John McCall7f416cc2015-09-08 08:05:57 +00004189ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00004190 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00004191 assert((E->getStorageDuration() == SD_Static ||
4192 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004193 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00004194
4195 // If we're not materializing a subobject of the temporary, keep the
4196 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00004197 QualType MaterializedType = Init->getType();
4198 if (Init == E->GetTemporaryExpr())
4199 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004200
John McCall7f416cc2015-09-08 08:05:57 +00004201 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4202
David Majnemer2dcef9e2015-08-13 23:50:15 +00004203 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
John McCall7f416cc2015-09-08 08:05:57 +00004204 return ConstantAddress(Slot, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004205
4206 // FIXME: If an externally-visible declaration extends multiple temporaries,
4207 // we need to give each temporary the same name in every translation unit (and
4208 // we also need to make the temporaries externally-visible).
4209 SmallString<256> Name;
4210 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00004211 getCXXABI().getMangleContext().mangleReferenceTemporary(
4212 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00004213
Craig Topper8a13c412014-05-21 05:09:00 +00004214 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004215 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00004216 // We might have a cached constant initializer for this temporary. Note
4217 // that this might have a different value from the value computed by
4218 // evaluating the initializer if the surrounding constant expression
4219 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00004220 Value = getContext().getMaterializedTemporaryValue(E, false);
4221 if (Value && Value->isUninit())
Craig Topper8a13c412014-05-21 05:09:00 +00004222 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004223 }
4224
Richard Smitha509f2f2013-06-14 03:07:01 +00004225 // Try evaluating it now, it might have a constant initializer.
4226 Expr::EvalResult EvalResult;
4227 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4228 !EvalResult.hasSideEffects())
4229 Value = &EvalResult.Val;
4230
Alexander Richardson6d989432017-10-15 18:48:14 +00004231 LangAS AddrSpace =
John McCallde0fe072017-08-15 21:42:52 +00004232 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4233
4234 Optional<ConstantEmitter> emitter;
Craig Topper8a13c412014-05-21 05:09:00 +00004235 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00004236 bool Constant = false;
4237 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00004238 if (Value) {
4239 // The temporary has a constant initializer, use it.
John McCallde0fe072017-08-15 21:42:52 +00004240 emitter.emplace(*this);
4241 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4242 MaterializedType);
Richard Smitha509f2f2013-06-14 03:07:01 +00004243 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4244 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004245 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00004246 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00004247 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00004248 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00004249 }
4250
4251 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00004252 llvm::GlobalValue::LinkageTypes Linkage =
4253 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004254 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4255 const VarDecl *InitVD;
4256 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4257 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4258 // Temporaries defined inside a class get linkonce_odr linkage because the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004259 // class can be defined in multiple translation units.
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004260 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4261 } else {
4262 // There is no need for this temporary to have external linkage if the
4263 // VarDecl has external linkage.
4264 Linkage = llvm::GlobalVariable::InternalLinkage;
4265 }
4266 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00004267 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004268 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00004269 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
Yaxun Liucbf647c2017-07-08 13:24:52 +00004270 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
John McCallde0fe072017-08-15 21:42:52 +00004271 if (emitter) emitter->finalize(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +00004272 setGVProperties(GV, VD);
John McCall7f416cc2015-09-08 08:05:57 +00004273 GV->setAlignment(Align.getQuantity());
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004274 if (supportsCOMDAT() && GV->isWeakForLinker())
4275 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smithe6c01442013-06-05 00:46:14 +00004276 if (VD->getTLSKind())
4277 setTLSMode(GV, *VD);
Yaxun Liucbf647c2017-07-08 13:24:52 +00004278 llvm::Constant *CV = GV;
4279 if (AddrSpace != LangAS::Default)
4280 CV = getTargetCodeGenInfo().performAddrSpaceCast(
4281 *this, GV, AddrSpace, LangAS::Default,
4282 Type->getPointerTo(
4283 getContext().getTargetAddressSpace(LangAS::Default)));
4284 MaterializedGlobalTemporaryMap[E] = CV;
4285 return ConstantAddress(CV, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004286}
4287
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004288/// EmitObjCPropertyImplementations - Emit information for synthesized
4289/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00004290void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004291 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004292 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004293 // Dynamic is just for type-checking.
4294 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4295 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4296
4297 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00004298 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004299 // we want, that just indicates if the decl came from a
4300 // property. What we want to know is if the method is defined in
4301 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004302 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004303 CodeGenFunction(*this).GenerateObjCGetter(
4304 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004305 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004306 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004307 CodeGenFunction(*this).GenerateObjCSetter(
4308 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004309 }
4310 }
4311}
4312
John McCall6a4fa522011-03-22 07:05:39 +00004313static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004314 const ObjCInterfaceDecl *iface = impl->getClassInterface();
4315 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00004316 ivar; ivar = ivar->getNextIvar())
4317 if (ivar->getType().isDestructedType())
4318 return true;
4319
4320 return false;
4321}
4322
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004323static bool AllTrivialInitializers(CodeGenModule &CGM,
4324 ObjCImplementationDecl *D) {
4325 CodeGenFunction CGF(CGM);
4326 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4327 E = D->init_end(); B != E; ++B) {
4328 CXXCtorInitializer *CtorInitExp = *B;
4329 Expr *Init = CtorInitExp->getInit();
4330 if (!CGF.isTrivialInitializer(Init))
4331 return false;
4332 }
4333 return true;
4334}
4335
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004336/// EmitObjCIvarInitializations - Emit information for ivar initialization
4337/// for an implementation.
4338void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00004339 // We might need a .cxx_destruct even if we don't have any ivar initializers.
4340 if (needsDestructMethod(D)) {
4341 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4342 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4343 ObjCMethodDecl *DTORMethod =
4344 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004345 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004346 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004347 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004348 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00004349 D->addInstanceMethod(DTORMethod);
4350 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00004351 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00004352 }
4353
4354 // If the implementation doesn't have any ivar initializers, we don't need
4355 // a .cxx_construct.
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004356 if (D->getNumIvarInitializers() == 0 ||
4357 AllTrivialInitializers(*this, D))
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004358 return;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004359
John McCall6a4fa522011-03-22 07:05:39 +00004360 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4361 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004362 // The constructor returns 'self'.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004363 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004364 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004365 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004366 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00004367 getContext().getObjCIdType(),
4368 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004369 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004370 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004371 /*isImplicitlyDeclared=*/true,
4372 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004373 ObjCMethodDecl::Required);
4374 D->addInstanceMethod(CTORMethod);
4375 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00004376 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004377}
4378
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004379// EmitLinkageSpec - Emit all declarations in a linkage spec.
4380void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00004381 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4382 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004383 ErrorUnsupported(LSD, "linkage spec");
4384 return;
4385 }
4386
Richard Smith8df390f2016-09-08 23:14:54 +00004387 EmitDeclContext(LSD);
4388}
4389
4390void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4391 for (auto *I : DC->decls()) {
4392 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4393 // are themselves considered "top-level", so EmitTopLevelDecl on an
4394 // ObjCImplDecl does not recursively visit them. We need to do that in
4395 // case they're nested inside another construct (LinkageSpecDecl /
4396 // ExportDecl) that does stop them from being considered "top-level".
Aaron Ballman629afae2014-03-07 19:56:05 +00004397 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004398 for (auto *M : OID->methods())
4399 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004400 }
Richard Smith8df390f2016-09-08 23:14:54 +00004401
Aaron Ballman629afae2014-03-07 19:56:05 +00004402 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004403 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004404}
4405
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004406/// EmitTopLevelDecl - Emit code for a single top level declaration.
4407void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00004408 // Ignore dependent declarations.
Richard Smith32b615c2018-02-01 00:28:36 +00004409 if (D->isTemplated())
Douglas Gregor70d83e22009-06-29 17:30:29 +00004410 return;
Mike Stump11289f42009-09-09 15:08:12 +00004411
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004412 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00004413 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00004414 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004415 case Decl::Function:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004416 EmitGlobal(cast<FunctionDecl>(D));
Alex Lorenzee024992014-08-04 18:41:51 +00004417 // Always provide some coverage mapping
4418 // even for the functions that aren't emitted.
4419 AddDeferredUnusedCoverageMapping(D);
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004420 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004421
Richard Smithada08882017-04-19 21:15:45 +00004422 case Decl::CXXDeductionGuide:
4423 // Function-like, but does not result in code emission.
4424 break;
4425
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004426 case Decl::Var:
Richard Smithbdb84f32016-07-22 23:36:59 +00004427 case Decl::Decomposition:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004428 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004429 EmitGlobal(cast<VarDecl>(D));
Richard Smithda383632016-08-15 01:33:41 +00004430 if (auto *DD = dyn_cast<DecompositionDecl>(D))
4431 for (auto *B : DD->bindings())
4432 if (auto *HD = B->getHoldingVar())
4433 EmitGlobal(HD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004434 break;
4435
John McCall32f44bd2011-04-12 01:01:22 +00004436 // Indirect fields from global anonymous structs and unions can be
4437 // ignored; only the actual variable requires IR gen support.
4438 case Decl::IndirectField:
4439 break;
4440
Anders Carlssonf7475242009-04-15 15:55:24 +00004441 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004442 case Decl::Namespace:
Richard Smith8df390f2016-09-08 23:14:54 +00004443 EmitDeclContext(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004444 break;
Richard Smithe1246122017-11-03 01:26:01 +00004445 case Decl::ClassTemplateSpecialization: {
4446 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4447 if (DebugInfo &&
4448 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4449 Spec->hasDefinition())
4450 DebugInfo->completeTemplateDefinition(*Spec);
4451 } LLVM_FALLTHROUGH;
Richard Smith62f19e72016-06-25 00:15:56 +00004452 case Decl::CXXRecord:
David Blaikie1ac9c982017-04-11 21:13:37 +00004453 if (DebugInfo) {
4454 if (auto *ES = D->getASTContext().getExternalSource())
4455 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4456 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4457 }
Richard Smith62f19e72016-06-25 00:15:56 +00004458 // Emit any static data members, they may be definitions.
4459 for (auto *I : cast<CXXRecordDecl>(D)->decls())
4460 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4461 EmitTopLevelDecl(I);
4462 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00004463 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00004464 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004465 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004466 case Decl::VarTemplate:
4467 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004468 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00004469 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00004470 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00004471 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00004472 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00004473 case Decl::Using: // using X; [C++]
4474 if (CGDebugInfo *DI = getModuleDebugInfo())
4475 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4476 return;
David Blaikief121b932013-05-20 22:50:41 +00004477 case Decl::NamespaceAlias:
4478 if (CGDebugInfo *DI = getModuleDebugInfo())
4479 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4480 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00004481 case Decl::UsingDirective: // using namespace X; [C++]
4482 if (CGDebugInfo *DI = getModuleDebugInfo())
4483 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4484 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00004485 case Decl::CXXConstructor:
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00004486 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00004487 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004488 case Decl::CXXDestructor:
Reid Klecknere7de47e2013-07-22 13:51:44 +00004489 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004490 break;
Anders Carlsson87835432009-06-11 21:22:55 +00004491
4492 case Decl::StaticAssert:
4493 // Nothing to do.
4494 break;
4495
Anders Carlssonf7475242009-04-15 15:55:24 +00004496 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00004497
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004498 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00004499 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00004500 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00004501 break;
4502
Douglas Gregorf6102672012-01-01 21:23:57 +00004503 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004504 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00004505 if (Proto->isThisDeclarationADefinition())
4506 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004507 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00004508 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004509
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004510 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004511 // Categories have properties but don't support synthesize so we
4512 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00004513 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004514 break;
4515
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004516 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004517 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004518 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004519 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00004520 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00004521 // Emit global variable debug information.
4522 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00004523 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00004524 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4525 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004526 break;
Mike Stump11289f42009-09-09 15:08:12 +00004527 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004528 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004529 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004530 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004531 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004532 CodeGenFunction(*this).GenerateObjCMethod(OMD);
4533 break;
4534 }
Mike Stump11289f42009-09-09 15:08:12 +00004535 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00004536 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004537 break;
4538
Nico Weber66220292016-03-02 17:28:48 +00004539 case Decl::PragmaComment: {
4540 const auto *PCD = cast<PragmaCommentDecl>(D);
4541 switch (PCD->getCommentKind()) {
4542 case PCK_Unknown:
4543 llvm_unreachable("unexpected pragma comment kind");
4544 case PCK_Linker:
4545 AppendLinkerOptions(PCD->getArg());
4546 break;
4547 case PCK_Lib:
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00004548 if (getTarget().getTriple().isOSBinFormatELF() &&
4549 !getTarget().getTriple().isPS4())
4550 AddELFLibDirective(PCD->getArg());
4551 else
4552 AddDependentLib(PCD->getArg());
Nico Weber66220292016-03-02 17:28:48 +00004553 break;
4554 case PCK_Compiler:
4555 case PCK_ExeStr:
4556 case PCK_User:
4557 break; // We ignore all of these.
4558 }
4559 break;
4560 }
4561
Nico Webercbbaeb12016-03-02 19:28:54 +00004562 case Decl::PragmaDetectMismatch: {
4563 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4564 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4565 break;
4566 }
4567
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004568 case Decl::LinkageSpec:
4569 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004570 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004571
4572 case Decl::FileScopeAsm: {
Artem Belevich0488d1e2015-04-27 18:52:00 +00004573 // File-scope asm is ignored during device-side CUDA compilation.
4574 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4575 break;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004576 // File-scope asm is ignored during device-side OpenMP compilation.
4577 if (LangOpts.OpenMPIsDevice)
4578 break;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004579 auto *AD = cast<FileScopeAsmDecl>(D);
Joerg Sonnenbergerdfd511e2015-03-13 00:54:30 +00004580 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004581 break;
4582 }
Mike Stump11289f42009-09-09 15:08:12 +00004583
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004584 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004585 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004586
Richard Smithdc1f0422016-07-20 19:10:16 +00004587 // If we've already imported this module, we're done.
4588 if (!ImportedModules.insert(Import->getImportedModule()))
Richard Smithc52efa72015-08-19 02:30:28 +00004589 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004590
Richard Smithdc1f0422016-07-20 19:10:16 +00004591 // Emit debug information for direct imports.
4592 if (!Import->getImportedOwningModule()) {
4593 if (CGDebugInfo *DI = getModuleDebugInfo())
4594 DI->EmitImportDecl(*Import);
4595 }
4596
Manman Ren3b5dbf22016-10-14 18:55:44 +00004597 // Find all of the submodules and emit the module initializers.
4598 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4599 SmallVector<clang::Module *, 16> Stack;
4600 Visited.insert(Import->getImportedModule());
4601 Stack.push_back(Import->getImportedModule());
4602
4603 while (!Stack.empty()) {
4604 clang::Module *Mod = Stack.pop_back_val();
4605 if (!EmittedModuleInitializers.insert(Mod).second)
4606 continue;
4607
4608 for (auto *D : Context.getModuleInitializers(Mod))
4609 EmitTopLevelDecl(D);
4610
4611 // Visit the submodules of this module.
4612 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4613 SubEnd = Mod->submodule_end();
4614 Sub != SubEnd; ++Sub) {
4615 // Skip explicit children; they need to be explicitly imported to emit
4616 // the initializers.
4617 if ((*Sub)->IsExplicit)
4618 continue;
4619
4620 if (Visited.insert(*Sub).second)
4621 Stack.push_back(*Sub);
4622 }
4623 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004624 break;
David Blaikie0e716b42014-03-03 23:48:23 +00004625 }
4626
Richard Smith8df390f2016-09-08 23:14:54 +00004627 case Decl::Export:
4628 EmitDeclContext(cast<ExportDecl>(D));
4629 break;
4630
Alexey Bataev97720002014-11-11 04:05:39 +00004631 case Decl::OMPThreadPrivate:
4632 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4633 break;
4634
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004635 case Decl::OMPDeclareReduction:
4636 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4637 break;
4638
Mike Stump11289f42009-09-09 15:08:12 +00004639 default:
Mike Stump18bb9282009-05-16 07:57:57 +00004640 // Make sure we handled everything we should, every other kind is a
4641 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4642 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004643 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Richard Smitha634ff22014-12-01 18:59:10 +00004644 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004645 }
4646}
John McCall09ae0322010-07-06 23:57:41 +00004647
Alex Lorenzee024992014-08-04 18:41:51 +00004648void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4649 // Do we need to generate coverage mapping?
4650 if (!CodeGenOpts.CoverageMapping)
4651 return;
4652 switch (D->getKind()) {
4653 case Decl::CXXConversion:
4654 case Decl::CXXMethod:
4655 case Decl::Function:
4656 case Decl::ObjCMethod:
4657 case Decl::CXXConstructor:
4658 case Decl::CXXDestructor: {
Justin Bogner203f0922015-07-28 00:41:51 +00004659 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
Alex Lorenzee024992014-08-04 18:41:51 +00004660 return;
Vedant Kumar0acf3432017-09-22 18:23:04 +00004661 SourceManager &SM = getContext().getSourceManager();
4662 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
4663 return;
Alex Lorenzee024992014-08-04 18:41:51 +00004664 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4665 if (I == DeferredEmptyCoverageMappingDecls.end())
4666 DeferredEmptyCoverageMappingDecls[D] = true;
4667 break;
4668 }
4669 default:
4670 break;
4671 };
4672}
4673
4674void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4675 // Do we need to generate coverage mapping?
4676 if (!CodeGenOpts.CoverageMapping)
4677 return;
4678 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4679 if (Fn->isTemplateInstantiation())
4680 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4681 }
4682 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4683 if (I == DeferredEmptyCoverageMappingDecls.end())
4684 DeferredEmptyCoverageMappingDecls[D] = false;
4685 else
4686 I->second = false;
4687}
4688
4689void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
Eli Friedman8516b7f2017-12-19 01:54:09 +00004690 // We call takeVector() here to avoid use-after-free.
4691 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
4692 // we deserialize function bodies to emit coverage info for them, and that
4693 // deserializes more declarations. How should we handle that case?
4694 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
Eli Friedmandbcfade2017-12-13 00:14:17 +00004695 if (!Entry.second)
Alex Lorenzee024992014-08-04 18:41:51 +00004696 continue;
Eli Friedmandbcfade2017-12-13 00:14:17 +00004697 const Decl *D = Entry.first;
Alex Lorenzee024992014-08-04 18:41:51 +00004698 switch (D->getKind()) {
4699 case Decl::CXXConversion:
4700 case Decl::CXXMethod:
4701 case Decl::Function:
4702 case Decl::ObjCMethod: {
4703 CodeGenPGO PGO(*this);
4704 GlobalDecl GD(cast<FunctionDecl>(D));
4705 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4706 getFunctionLinkage(GD));
4707 break;
4708 }
4709 case Decl::CXXConstructor: {
4710 CodeGenPGO PGO(*this);
4711 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4712 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4713 getFunctionLinkage(GD));
4714 break;
4715 }
4716 case Decl::CXXDestructor: {
4717 CodeGenPGO PGO(*this);
4718 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4719 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4720 getFunctionLinkage(GD));
4721 break;
4722 }
4723 default:
4724 break;
4725 };
4726 }
4727}
4728
John McCall09ae0322010-07-06 23:57:41 +00004729/// Turns the given pointer into a constant.
4730static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4731 const void *Ptr) {
4732 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00004733 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00004734 return llvm::ConstantInt::get(i64, PtrInt);
4735}
4736
4737static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4738 llvm::NamedMDNode *&GlobalMetadata,
4739 GlobalDecl D,
4740 llvm::GlobalValue *Addr) {
4741 if (!GlobalMetadata)
4742 GlobalMetadata =
4743 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4744
4745 // TODO: should we report variant information for ctors/dtors?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004746 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4747 llvm::ConstantAsMetadata::get(GetPointerConstant(
4748 CGM.getLLVMContext(), D.getDecl()))};
Jay Foadea324f12011-04-21 19:59:12 +00004749 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00004750}
4751
Richard Smithdf931ce2013-04-06 05:00:46 +00004752/// For each function which is declared within an extern "C" region and marked
4753/// as 'used', but has internal linkage, create an alias from the unmangled
4754/// name to the mangled name if possible. People expect to be able to refer
4755/// to such functions with an unmangled name from inline assembly within the
4756/// same translation unit.
4757void CodeGenModule::EmitStaticExternCAliases() {
Yaxun Liub0eee292018-03-29 14:50:00 +00004758 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
Justin Lebarcd2f6bb2016-01-25 22:36:37 +00004759 return;
Yaron Kerenb54db522015-06-11 12:33:25 +00004760 for (auto &I : StaticExternCValues) {
4761 IdentifierInfo *Name = I.first;
4762 llvm::GlobalValue *Val = I.second;
Richard Smith85465e62013-04-06 07:07:44 +00004763 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola27c60b52014-06-03 02:42:01 +00004764 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith85465e62013-04-06 07:07:44 +00004765 }
Richard Smithdf931ce2013-04-06 05:00:46 +00004766}
4767
Alp Tokerfb8d02b2014-06-05 22:10:59 +00004768bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4769 GlobalDecl &Result) const {
4770 auto Res = Manglings.find(MangledName);
4771 if (Res == Manglings.end())
4772 return false;
4773 Result = Res->getValue();
4774 return true;
4775}
4776
John McCall09ae0322010-07-06 23:57:41 +00004777/// Emits metadata nodes associating all the global values in the
4778/// current module with the Decls they came from. This is useful for
4779/// projects using IR gen as a subroutine.
4780///
4781/// Since there's currently no way to associate an MDNode directly
4782/// with an llvm::GlobalValue, we create a global named metadata
4783/// with the name 'clang.global.decl.ptrs'.
4784void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00004785 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00004786
Robert Lytton5b88f78f2014-07-03 09:30:29 +00004787 for (auto &I : MangledDeclNames) {
4788 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
Keno Fischer0e2d4222015-11-05 23:18:44 +00004789 // Some mangled names don't necessarily have an associated GlobalValue
4790 // in this module, e.g. if we mangled it for DebugInfo.
4791 if (Addr)
4792 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall09ae0322010-07-06 23:57:41 +00004793 }
4794}
4795
4796/// Emits metadata nodes for all the local variables in the current
4797/// function.
4798void CodeGenFunction::EmitDeclMetadata() {
4799 if (LocalDeclMap.empty()) return;
4800
4801 llvm::LLVMContext &Context = getLLVMContext();
4802
4803 // Find the unique metadata ID for this name.
4804 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4805
Craig Topper8a13c412014-05-21 05:09:00 +00004806 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00004807
Robert Lytton5b88f78f2014-07-03 09:30:29 +00004808 for (auto &I : LocalDeclMap) {
4809 const Decl *D = I.first;
John McCall7f416cc2015-09-08 08:05:57 +00004810 llvm::Value *Addr = I.second.getPointer();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004811 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00004812 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004813 Alloca->setMetadata(
4814 DeclPtrKind, llvm::MDNode::get(
4815 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004816 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00004817 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4818 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4819 }
4820 }
4821}
Daniel Dunbar900546d2010-07-16 00:00:15 +00004822
Rafael Espindola3bfa4682013-10-16 19:28:50 +00004823void CodeGenModule::EmitVersionIdentMetadata() {
4824 llvm::NamedMDNode *IdentMetadata =
4825 TheModule.getOrInsertNamedMetadata("llvm.ident");
4826 std::string Version = getClangFullVersion();
4827 llvm::LLVMContext &Ctx = TheModule.getContext();
4828
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004829 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola3bfa4682013-10-16 19:28:50 +00004830 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4831}
4832
Robert Lytton57765d52014-07-03 09:30:33 +00004833void CodeGenModule::EmitTargetMetadata() {
Richard Smith1ba0a072014-08-01 20:39:36 +00004834 // Warning, new MangledDeclNames may be appended within this loop.
4835 // We rely on MapVector insertions adding new elements to the end
4836 // of the container.
4837 // FIXME: Move this loop into the one target that needs it, and only
4838 // loop over those declarations for which we couldn't emit the target
4839 // metadata when we emitted the declaration.
4840 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
Richard Smith570706d2014-08-01 22:17:28 +00004841 auto Val = *(MangledDeclNames.begin() + I);
Richard Smith1ba0a072014-08-01 20:39:36 +00004842 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4843 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Robert Lytton57765d52014-07-03 09:30:33 +00004844 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4845 }
4846}
4847
Nick Lewycky85c011d2011-05-05 00:08:20 +00004848void CodeGenModule::EmitCoverageFile() {
Nick Lewycky97e49ac2016-08-31 23:04:32 +00004849 if (getCodeGenOpts().CoverageDataFile.empty() &&
4850 getCodeGenOpts().CoverageNotesFile.empty())
4851 return;
4852
4853 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4854 if (!CUNode)
4855 return;
4856
4857 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4858 llvm::LLVMContext &Ctx = TheModule.getContext();
4859 auto *CoverageDataFile =
4860 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4861 auto *CoverageNotesFile =
4862 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4863 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4864 llvm::MDNode *CU = CUNode->getOperand(i);
4865 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4866 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky480cb992011-05-04 20:46:58 +00004867 }
4868}
Nico Webercf4ff5862012-10-11 10:13:44 +00004869
Nico Weber17d3a2c2014-09-08 16:26:36 +00004870llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Webercf4ff5862012-10-11 10:13:44 +00004871 // Sema has checked that all uuid strings are of the form
4872 // "12345678-1234-1234-1234-1234567890ab".
4873 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00004874 for (unsigned i = 0; i < 36; ++i) {
4875 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4876 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00004877 }
Nico Webercf4ff5862012-10-11 10:13:44 +00004878
Nico Weberdfa274e2014-09-08 16:11:15 +00004879 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemerbbecd092013-08-15 19:59:14 +00004880 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00004881
David Majnemerbbecd092013-08-15 19:59:14 +00004882 llvm::Constant *Field3[8];
4883 for (unsigned Idx = 0; Idx < 8; ++Idx)
4884 Field3[Idx] = llvm::ConstantInt::get(
4885 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4886
4887 llvm::Constant *Fields[4] = {
4888 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4889 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4890 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4891 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4892 };
4893
4894 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00004895}
David Majnemere2cb8d12014-07-07 06:20:47 +00004896
4897llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4898 bool ForEH) {
4899 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4900 // FIXME: should we even be calling this method if RTTI is disabled
4901 // and it's not for EH?
4902 if (!ForEH && !getLangOpts().RTTI)
4903 return llvm::Constant::getNullValue(Int8PtrTy);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004904
David Majnemere2cb8d12014-07-07 06:20:47 +00004905 if (ForEH && Ty->isObjCObjectPointerType() &&
4906 LangOpts.ObjCRuntime.isGNUFamily())
4907 return ObjCRuntime->GetEHType(Ty);
4908
David Majnemer443250f2015-03-17 20:35:00 +00004909 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
David Majnemere2cb8d12014-07-07 06:20:47 +00004910}
4911
Alexey Bataev97720002014-11-11 04:05:39 +00004912void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004913 // Do not emit threadprivates in simd-only mode.
4914 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
4915 return;
Alexey Bataev97720002014-11-11 04:05:39 +00004916 for (auto RefExpr : D->varlists()) {
4917 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4918 bool PerformInit =
4919 VD->getAnyInitializer() &&
4920 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4921 /*ForRef=*/false);
John McCall7f416cc2015-09-08 08:05:57 +00004922
4923 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
Alexey Bataev3eff5f42015-02-25 08:32:46 +00004924 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00004925 VD, Addr, RefExpr->getLocStart(), PerformInit))
Alexey Bataev97720002014-11-11 04:05:39 +00004926 CXXGlobalInits.push_back(InitFunction);
4927 }
4928}
Peter Collingbourne86d34a72015-06-17 19:08:05 +00004929
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00004930llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4931 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4932 if (InternalId)
4933 return InternalId;
4934
4935 if (isExternallyVisible(T->getLinkage())) {
4936 std::string OutName;
4937 llvm::raw_string_ostream Out(OutName);
4938 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4939
4940 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4941 } else {
4942 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4943 llvm::ArrayRef<llvm::Metadata *>());
4944 }
4945
4946 return InternalId;
4947}
4948
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00004949// Generalize pointer types to a void pointer with the qualifiers of the
4950// originally pointed-to type, e.g. 'const char *' and 'char * const *'
4951// generalize to 'const void *' while 'char *' and 'const char **' generalize to
4952// 'void *'.
4953static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
4954 if (!Ty->isPointerType())
4955 return Ty;
4956
4957 return Ctx.getPointerType(
4958 QualType(Ctx.VoidTy).withCVRQualifiers(
4959 Ty->getPointeeType().getCVRQualifiers()));
4960}
4961
4962// Apply type generalization to a FunctionType's return and argument types
4963static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
4964 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
4965 SmallVector<QualType, 8> GeneralizedParams;
4966 for (auto &Param : FnType->param_types())
4967 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
4968
4969 return Ctx.getFunctionType(
4970 GeneralizeType(Ctx, FnType->getReturnType()),
4971 GeneralizedParams, FnType->getExtProtoInfo());
4972 }
4973
4974 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
4975 return Ctx.getFunctionNoProtoType(
4976 GeneralizeType(Ctx, FnType->getReturnType()));
4977
4978 llvm_unreachable("Encountered unknown FunctionType");
4979}
4980
4981llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
4982 T = GeneralizeFunctionType(getContext(), T);
4983
4984 llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()];
4985 if (InternalId)
4986 return InternalId;
4987
4988 if (isExternallyVisible(T->getLinkage())) {
4989 std::string OutName;
4990 llvm::raw_string_ostream Out(OutName);
4991 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4992 Out << ".generalized";
4993
4994 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4995 } else {
4996 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4997 llvm::ArrayRef<llvm::Metadata *>());
4998 }
4999
5000 return InternalId;
5001}
5002
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005003/// Returns whether this module needs the "all-vtables" type identifier.
5004bool CodeGenModule::NeedAllVtablesTypeId() const {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005005 // Returns true if at least one of vtable-based CFI checkers is enabled and
5006 // is not in the trapping mode.
5007 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5008 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5009 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5010 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5011 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5012 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5013 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5014 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5015}
5016
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005017void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5018 CharUnits Offset,
5019 const CXXRecordDecl *RD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005020 llvm::Metadata *MD =
5021 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005022 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005023
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005024 if (CodeGenOpts.SanitizeCfiCrossDso)
5025 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5026 VTable->addTypeMetadata(Offset.getQuantity(),
5027 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005028
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005029 if (NeedAllVtablesTypeId()) {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005030 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005031 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005032 }
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005033}
Eric Christopher2b90a642015-11-11 23:05:08 +00005034
5035// Fills in the supplied string map with the set of target features for the
5036// passed in function.
5037void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
5038 const FunctionDecl *FD) {
5039 StringRef TargetCPU = Target.getTargetOpts().CPU;
5040 if (const auto *TD = FD->getAttr<TargetAttr>()) {
5041 // If we have a TargetAttr build up the feature map based on that.
5042 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5043
Erich Keanecf8807c2017-10-27 18:32:23 +00005044 ParsedAttr.Features.erase(
5045 llvm::remove_if(ParsedAttr.Features,
5046 [&](const std::string &Feat) {
5047 return !Target.isValidFeatureName(
5048 StringRef{Feat}.substr(1));
5049 }),
5050 ParsedAttr.Features.end());
5051
Eric Christopher2b90a642015-11-11 23:05:08 +00005052 // Make a copy of the features as passed on the command line into the
5053 // beginning of the additional features from the function to override.
Erich Keaneb0d44232017-07-18 20:41:02 +00005054 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
Eric Christopher2b90a642015-11-11 23:05:08 +00005055 Target.getTargetOpts().FeaturesAsWritten.begin(),
5056 Target.getTargetOpts().FeaturesAsWritten.end());
5057
Erich Keanecf8807c2017-10-27 18:32:23 +00005058 if (ParsedAttr.Architecture != "" &&
5059 Target.isValidCPUName(ParsedAttr.Architecture))
5060 TargetCPU = ParsedAttr.Architecture;
Eric Christopher2b90a642015-11-11 23:05:08 +00005061
5062 // Now populate the feature map, first with the TargetCPU which is either
5063 // the default or a new one from the target attribute string. Then we'll use
5064 // the passed in features (FeaturesAsWritten) along with the new ones from
5065 // the attribute.
Erich Keaneb0d44232017-07-18 20:41:02 +00005066 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5067 ParsedAttr.Features);
Eric Christopher2b90a642015-11-11 23:05:08 +00005068 } else {
5069 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5070 Target.getTargetOpts().Features);
5071 }
5072}
Peter Collingbournedc134532016-01-16 00:31:22 +00005073
5074llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5075 if (!SanStats)
5076 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5077
5078 return *SanStats;
5079}
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005080llvm::Value *
5081CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5082 CodeGenFunction &CGF) {
John McCallde0fe072017-08-15 21:42:52 +00005083 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00005084 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005085 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5086 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5087 "__translate_sampler_initializer"),
5088 {C});
5089}