blob: ab0ac67d8e8d40330097332d3f756ce54f83b91f [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"
Richard Trieu63688182018-12-11 03:18:39 +000039#include "clang/Basic/CodeGenOptions.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000040#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000041#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000042#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000043#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000044#include "clang/Basic/Version.h"
John McCall5ad74072017-03-02 20:04:19 +000045#include "clang/CodeGen/ConstantInitBuilder.h"
Richard Trieu5337c742018-12-06 06:12:20 +000046#include "clang/Frontend/FrontendDiagnostic.h"
Caroline Tice62279732018-09-21 18:34:59 +000047#include "llvm/ADT/StringSwitch.h"
John McCallbeec5a02010-03-06 00:35:14 +000048#include "llvm/ADT/Triple.h"
Matthias Brauna4519532017-05-20 01:29:55 +000049#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000050#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000051#include "llvm/IR/CallingConv.h"
52#include "llvm/IR/DataLayout.h"
53#include "llvm/IR/Intrinsics.h"
54#include "llvm/IR/LLVMContext.h"
55#include "llvm/IR/Module.h"
Justin Bogner837a6f62014-04-18 21:52:00 +000056#include "llvm/ProfileData/InstrProfReader.h"
Caroline Tice62279732018-09-21 18:34:59 +000057#include "llvm/Support/CodeGen.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000058#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000059#include "llvm/Support/ErrorHandling.h"
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +000060#include "llvm/Support/MD5.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000061
Chris Lattnerbed31442007-05-28 01:07:47 +000062using namespace clang;
63using namespace CodeGen;
64
Vedant Kumar0acf3432017-09-22 18:23:04 +000065static llvm::cl::opt<bool> LimitedCoverage(
Zachary Turner8065f0b2017-12-01 00:53:10 +000066 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
Vedant Kumar0acf3432017-09-22 18:23:04 +000067 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
68 llvm::cl::init(false));
69
Julien Lerouge5a6b6982011-09-09 22:41:49 +000070static const char AnnotationSection[] = "llvm.metadata";
71
Alp Toker82862252013-12-28 21:58:40 +000072static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000073 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000074 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000075 case TargetCXXABI::GenericARM:
76 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000077 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +000078 case TargetCXXABI::WatchOS:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000079 case TargetCXXABI::GenericMIPS:
John McCall57625922013-01-25 23:36:14 +000080 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +000081 case TargetCXXABI::WebAssembly:
Alp Toker82862252013-12-28 21:58:40 +000082 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000083 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000084 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000085 }
86
87 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000088}
89
Adrian Prantle74f5252015-06-30 02:26:03 +000090CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
91 const PreprocessorOptions &PPO,
92 const CodeGenOptions &CGO, llvm::Module &M,
Alex Lorenzee024992014-08-04 18:41:51 +000093 DiagnosticsEngine &diags,
94 CoverageSourceInfo *CoverageInfo)
Adrian Prantle74f5252015-06-30 02:26:03 +000095 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
96 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
Mehdi Aminica3cf9e2015-07-24 16:04:29 +000097 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
Reid Kleckner9305fd12016-04-13 23:37:17 +000098 VMContext(M.getContext()), Types(*this), VTables(*this),
Peter Collingbourne3afb2662016-04-28 17:09:37 +000099 SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietzf54319c2013-01-18 11:30:38 +0000100
Chris Lattnerece04092012-02-07 00:39:47 +0000101 // Initialize the type cache.
102 llvm::LLVMContext &LLVMContext = M.getContext();
103 VoidTy = llvm::Type::getVoidTy(LLVMContext);
104 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
105 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
106 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
107 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
Abderrazek Zaafranif58a1322017-12-21 19:20:01 +0000108 HalfTy = llvm::Type::getHalfTy(LLVMContext);
Chris Lattnerece04092012-02-07 00:39:47 +0000109 FloatTy = llvm::Type::getFloatTy(LLVMContext);
110 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
111 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
112 PointerAlignInBytes =
John McCall7f416cc2015-09-08 08:05:57 +0000113 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
Yaxun Liu26f75662016-08-19 05:17:25 +0000114 SizeSizeInBytes =
115 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +0000116 IntAlignInBytes =
117 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
Chris Lattnerece04092012-02-07 00:39:47 +0000118 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
Yaxun Liu26f75662016-08-19 05:17:25 +0000119 IntPtrTy = llvm::IntegerType::get(LLVMContext,
120 C.getTargetInfo().getMaxPointerWidth());
Chris Lattnerece04092012-02-07 00:39:47 +0000121 Int8PtrTy = Int8Ty->getPointerTo(0);
122 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000123 AllocaInt8PtrTy = Int8Ty->getPointerTo(
124 M.getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000125 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
Chris Lattnerece04092012-02-07 00:39:47 +0000126
John McCall882987f2013-02-28 19:01:20 +0000127 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
128
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000129 if (LangOpts.ObjC)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000130 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000131 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000132 createOpenCLRuntime();
Alexey Bataev9959db52014-05-06 10:08:46 +0000133 if (LangOpts.OpenMP)
134 createOpenMPRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000135 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000136 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000137
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000138 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000139 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000140 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000141 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
Reid Kleckner9305fd12016-04-13 23:37:17 +0000142 getCXXABI().getMangleContext()));
Dan Gohman947c9af2010-10-14 23:06:10 +0000143
Nick Lewycky207bce32011-04-21 23:44:07 +0000144 // If debug info or coverage generation is enabled, create the CGDebugInfo
145 // object.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000146 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
147 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000148 DebugInfo.reset(new CGDebugInfo(*this));
John McCallad7c5c12011-02-08 08:22:06 +0000149
150 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000151
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000152 if (C.getLangOpts().ObjC)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000153 ObjCData.reset(new ObjCEntrypoints());
Justin Bogneref512b92014-01-06 22:27:43 +0000154
Rong Xu9c6f1532016-03-02 20:59:36 +0000155 if (CodeGenOpts.hasProfileClangUse()) {
156 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
Richard Smith8654ae52018-10-10 23:13:35 +0000157 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000158 if (auto E = ReaderOrErr.takeError()) {
Justin Bogner837a6f62014-04-18 21:52:00 +0000159 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
Diego Novillo5aecacb2015-06-25 22:56:00 +0000160 "Could not read profile %0: %1");
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000161 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
162 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
163 << EI.message();
164 });
Nico Weber176efac2015-04-06 04:16:48 +0000165 } else
166 PGOReader = std::move(ReaderOrErr.get());
Justin Bogner837a6f62014-04-18 21:52:00 +0000167 }
Alex Lorenzee024992014-08-04 18:41:51 +0000168
169 // If coverage mapping generation is enabled, create the
170 // CoverageMappingModuleGen object.
171 if (CodeGenOpts.CoverageMapping)
172 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattnera087ff92008-03-01 08:45:05 +0000173}
174
Reid Kleckner9305fd12016-04-13 23:37:17 +0000175CodeGenModule::~CodeGenModule() {}
Ted Kremenek2c674f62008-08-05 18:50:11 +0000176
David Chisnall481e3a82010-01-23 02:40:42 +0000177void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000178 // This is just isGNUFamily(), but we want to force implementors of
179 // new ABIs to decide how best to do this.
180 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000181 case ObjCRuntime::GNUstep:
182 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000183 case ObjCRuntime::ObjFW:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000184 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000185 return;
186
187 case ObjCRuntime::FragileMacOSX:
188 case ObjCRuntime::MacOSX:
189 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000190 case ObjCRuntime::WatchOS:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000191 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000192 return;
193 }
194 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000195}
196
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000197void CodeGenModule::createOpenCLRuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000198 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000199}
200
Alexey Bataev9959db52014-05-06 10:08:46 +0000201void CodeGenModule::createOpenMPRuntime() {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000202 // Select a specialized code generation class based on the target, if any.
203 // If it does not exist use the default implementation.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000204 switch (getTriple().getArch()) {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000205 case llvm::Triple::nvptx:
206 case llvm::Triple::nvptx64:
207 assert(getLangOpts().OpenMPIsDevice &&
208 "OpenMP NVPTX is only prepared to deal with device code.");
Reid Kleckner9305fd12016-04-13 23:37:17 +0000209 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000210 break;
211 default:
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000212 if (LangOpts.OpenMPSimd)
213 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
214 else
215 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000216 break;
217 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000218}
219
Peter Collingbournefe883422011-10-06 18:29:37 +0000220void CodeGenModule::createCUDARuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000221 CUDARuntime.reset(CreateNVCUDARuntime(*this));
Peter Collingbournefe883422011-10-06 18:29:37 +0000222}
223
Rafael Espindola1e4df922014-09-16 15:18:21 +0000224void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
225 Replacements[Name] = C;
226}
227
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000228void CodeGenModule::applyReplacements() {
Yaron Kerenb54db522015-06-11 12:33:25 +0000229 for (auto &I : Replacements) {
230 StringRef MangledName = I.first();
231 llvm::Constant *Replacement = I.second;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000232 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
233 if (!Entry)
234 continue;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000235 auto *OldF = cast<llvm::Function>(Entry);
236 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000237 if (!NewF) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000238 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
Rafael Espindola0fcad882014-05-16 22:20:18 +0000239 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Reid Klecknerb78257d2014-02-03 18:54:51 +0000240 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000241 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Reid Klecknerb78257d2014-02-03 18:54:51 +0000242 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
243 CE->getOpcode() == llvm::Instruction::GetElementPtr);
244 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
245 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000246 }
247
248 // Replace old with new, but keep the old order.
249 OldF->replaceAllUsesWith(Replacement);
250 if (NewF) {
251 NewF->removeFromParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000252 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
253 NewF);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000254 }
255 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000256 }
257}
258
Andrey Bokhankocab58582015-08-31 13:20:44 +0000259void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
260 GlobalValReplacements.push_back(std::make_pair(GV, C));
261}
262
263void CodeGenModule::applyGlobalValReplacements() {
264 for (auto &I : GlobalValReplacements) {
265 llvm::GlobalValue *GV = I.first;
266 llvm::Constant *C = I.second;
267
268 GV->replaceAllUsesWith(C);
269 GV->eraseFromParent();
270 }
271}
272
Rafael Espindola27c60b52014-06-03 02:42:01 +0000273// This is only used in aliases that we created and we know they have a
274// linear structure.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000275static const llvm::GlobalObject *getAliasedGlobal(
276 const llvm::GlobalIndirectSymbol &GIS) {
277 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
278 const llvm::Constant *C = &GIS;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000279 for (;;) {
Rafael Espindolae11f40a2014-06-04 19:03:20 +0000280 C = C->stripPointerCasts();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000281 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
282 return GO;
283 // stripPointerCasts will not walk over weak aliases.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000284 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
285 if (!GIS2)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000286 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000287 if (!Visited.insert(GIS2).second)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000288 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000289 C = GIS2->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000290 }
291}
292
Rafael Espindola208b5c02013-10-22 19:26:13 +0000293void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000294 // Check if the constructed aliases are well formed. It is really unfortunate
295 // that we have to do this in CodeGen, but we only construct mangled names
296 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000297 bool Error = false;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000298 DiagnosticsEngine &Diags = getDiags();
Yaron Kerenb54db522015-06-11 12:33:25 +0000299 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000300 const auto *D = cast<ValueDecl>(GD.getDecl());
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000301 SourceLocation Location;
302 bool IsIFunc = D->hasAttr<IFuncAttr>();
303 if (const Attr *A = D->getDefiningAttr())
304 Location = A->getLocation();
305 else
306 llvm_unreachable("Not an alias or ifunc?");
Rafael Espindola208b5c02013-10-22 19:26:13 +0000307 StringRef MangledName = getMangledName(GD);
308 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000309 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000310 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
311 if (!GV) {
312 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000313 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000314 } else if (GV->isDeclaration()) {
Rafael Espindola93c7a652014-03-13 15:47:50 +0000315 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000316 Diags.Report(Location, diag::err_alias_to_undefined)
317 << IsIFunc << IsIFunc;
318 } else if (IsIFunc) {
319 // Check resolver function type.
320 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
321 GV->getType()->getPointerElementType());
322 assert(FTy);
323 if (!FTy->getReturnType()->isPointerTy())
324 Diags.Report(Location, diag::err_ifunc_resolver_return);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000325 }
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000326
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000327 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000328 llvm::GlobalValue *AliaseeGV;
329 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
330 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
331 else
332 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
333
Rafael Espindola502f65a2014-05-05 20:21:03 +0000334 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
335 StringRef AliasSection = SA->getName();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000336 if (AliasSection != AliaseeGV->getSection())
Rafael Espindola502f65a2014-05-05 20:21:03 +0000337 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000338 << AliasSection << IsIFunc << IsIFunc;
Rafael Espindola502f65a2014-05-05 20:21:03 +0000339 }
Rafael Espindola27c60b52014-06-03 02:42:01 +0000340
341 // We have to handle alias to weak aliases in here. LLVM itself disallows
342 // this since the object semantics would not match the IL one. For
343 // compatibility with gcc we implement it by just pointing the alias
344 // to its aliasee's aliasee. We also warn, since the user is probably
345 // expecting the link to be weak.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000346 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
Sanjoy Dasf60a0d72016-04-08 01:31:02 +0000347 if (GA->isInterposable()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000348 Diags.Report(Location, diag::warn_alias_to_weak_alias)
349 << GV->getName() << GA->getName() << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000350 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000351 GA->getIndirectSymbol(), Alias->getType());
352 Alias->setIndirectSymbol(Aliasee);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000353 }
354 }
Rafael Espindola208b5c02013-10-22 19:26:13 +0000355 }
356 if (!Error)
357 return;
358
Yaron Kerenb54db522015-06-11 12:33:25 +0000359 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola208b5c02013-10-22 19:26:13 +0000360 StringRef MangledName = getMangledName(GD);
361 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000362 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000363 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
364 Alias->eraseFromParent();
365 }
366}
367
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000368void CodeGenModule::clear() {
369 DeferredDeclsToEmit.clear();
Alexey Bataev91797552015-03-18 04:13:55 +0000370 if (OpenMPRuntime)
371 OpenMPRuntime->clear();
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000372}
373
Justin Bogner40b8ba12014-06-26 01:45:07 +0000374void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
375 StringRef MainFile) {
376 if (!hasDiagnostics())
377 return;
378 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
379 if (MainFile.empty())
380 MainFile = "<stdin>";
381 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
Vedant Kumar96d6ca72017-04-27 17:30:58 +0000382 } else {
383 if (Mismatched > 0)
384 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
385
386 if (Missing > 0)
387 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
388 }
Justin Bogner40b8ba12014-06-26 01:45:07 +0000389}
390
Ted Kremenek2c674f62008-08-05 18:50:11 +0000391void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000392 EmitDeferred();
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000393 EmitVTablesOpportunistically();
Andrey Bokhankocab58582015-08-31 13:20:44 +0000394 applyGlobalValReplacements();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000395 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000396 checkAliases();
Erich Keane281d20b2018-01-08 21:34:17 +0000397 emitMultiVersionFunctions();
Eli Friedman5866fe32010-01-08 00:50:11 +0000398 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000399 EmitCXXGlobalDtorFunc();
Akira Hatanaka617e2612018-04-17 18:41:52 +0000400 registerGlobalDtorsWithAtExit();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000401 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000402 if (ObjCRuntime)
403 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000404 AddGlobalCtor(ObjCInitFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000405 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
406 CUDARuntime) {
Artem Belevichc66d2542018-06-27 18:32:51 +0000407 if (llvm::Function *CudaCtorFunction =
408 CUDARuntime->makeModuleCtorFunction())
Artem Belevich52cc4872015-05-07 19:34:16 +0000409 AddGlobalCtor(CudaCtorFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000410 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000411 if (OpenMPRuntime) {
Samuel Antaoee8fb302016-01-06 13:42:12 +0000412 if (llvm::Function *OpenMPRegistrationFunction =
George Rokos29d0f002017-05-27 03:03:13 +0000413 OpenMPRuntime->emitRegistrationFunction()) {
414 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415 OpenMPRegistrationFunction : nullptr;
416 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
417 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000418 OpenMPRuntime->clear();
419 }
Easwaran Raman695890c2015-12-17 19:14:27 +0000420 if (PGOReader) {
Easwaran Raman81608122016-03-24 21:32:25 +0000421 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
Easwaran Raman695890c2015-12-17 19:14:27 +0000422 if (PGOStats.hasDiagnostics())
423 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
424 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000425 EmitCtorList(GlobalCtors, "llvm.global_ctors");
426 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000427 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000428 EmitStaticExternCAliases();
Alex Lorenzee024992014-08-04 18:41:51 +0000429 EmitDeferredUnusedCoverageMappings();
430 if (CoverageMapping)
431 CoverageMapping->emit();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000432 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000433 CodeGenFunction(*this).EmitCfiCheckFail();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000434 CodeGenFunction(*this).EmitCfiCheckStub();
435 }
Alex Lorenza8fbef42017-03-23 11:14:27 +0000436 emitAtAvailableLinkGuard();
Rafael Espindola060062a2014-03-06 22:15:10 +0000437 emitLLVMUsed();
Peter Collingbournedc134532016-01-16 00:31:22 +0000438 if (SanStats)
439 SanStats->finish();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000440
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000441 if (CodeGenOpts.Autolink &&
442 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000443 EmitModuleLinkOptions();
444 }
Nirav Dave8497ef42017-03-18 00:43:39 +0000445
Nirav Dave741dea02017-03-30 13:41:44 +0000446 // Record mregparm value now so it is visible through rest of codegen.
447 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
448 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
449 CodeGenOpts.NumRegisterParameters);
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000450
Reid Kleckner124955a2015-08-05 18:51:13 +0000451 if (CodeGenOpts.DwarfVersion) {
Manman Ren9691f7f2013-06-19 01:46:49 +0000452 // We actually want the latest version when there are conflicts.
453 // We can change from Warning to Latest if such mode is supported.
454 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
455 CodeGenOpts.DwarfVersion);
Reid Kleckner124955a2015-08-05 18:51:13 +0000456 }
457 if (CodeGenOpts.EmitCodeView) {
458 // Indicate that we want CodeView in the metadata.
459 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
460 }
Reid Kleckner75557712018-11-16 18:47:41 +0000461 if (CodeGenOpts.CodeViewGHash) {
462 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
463 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000464 if (CodeGenOpts.ControlFlowGuard) {
465 // We want function ID tables for Control Flow Guard.
Hans Wennborga912e3e2018-08-10 09:49:21 +0000466 getModule().addModuleFlag(llvm::Module::Warning, "cfguardtable", 1);
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000467 }
Piotr Padlewski9d0ecf22015-09-15 21:46:50 +0000468 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
469 // We don't support LTO with 2 with different StrictVTablePointers
470 // FIXME: we could support it by stripping all the information introduced
471 // by StrictVTablePointers.
472
473 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
474
475 llvm::Metadata *Ops[2] = {
476 llvm::MDString::get(VMContext, "StrictVTablePointers"),
477 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
478 llvm::Type::getInt32Ty(VMContext), 1))};
479
480 getModule().addModuleFlag(llvm::Module::Require,
481 "StrictVTablePointersRequirement",
482 llvm::MDNode::get(VMContext, Ops));
483 }
Manman Ren4b7f23d2013-11-22 19:42:45 +0000484 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000485 // We support a single version in the linked module. The LLVM
486 // parser will drop debug info with a different version number
487 // (and warn about it, too).
488 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000489 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000490
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000491 // We need to record the widths of enums and wchar_t, so that we can generate
Matthias Brauna4519532017-05-20 01:29:55 +0000492 // the correct build attributes in the ARM backend. wchar_size is also used by
493 // TargetLibraryInfo.
Matthias Braunbffc1bb2017-09-26 02:37:23 +0000494 uint64_t WCharWidth =
495 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
Matthias Brauna4519532017-05-20 01:29:55 +0000496 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
497
Justin Bogner9bb7f152014-06-23 20:03:28 +0000498 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000499 if ( Arch == llvm::Triple::arm
500 || Arch == llvm::Triple::armeb
501 || Arch == llvm::Triple::thumb
502 || Arch == llvm::Triple::thumbeb) {
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000503 // The minimum width of an enum in bytes
504 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
505 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
506 }
507
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000508 if (CodeGenOpts.SanitizeCfiCrossDso) {
509 // Indicate that we want cross-DSO control flow integrity checks.
510 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
511 }
512
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +0000513 if (CodeGenOpts.CFProtectionReturn &&
514 Target.checkCFProtectionReturnSupported(getDiags())) {
515 // Indicate that we want to instrument return control flow protection.
516 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
517 1);
518 }
519
520 if (CodeGenOpts.CFProtectionBranch &&
521 Target.checkCFProtectionBranchSupported(getDiags())) {
522 // Indicate that we want to instrument branch control flow protection.
523 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
524 1);
525 }
526
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000527 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
Justin Lebard3a44f62016-04-05 18:26:20 +0000528 // Indicate whether __nvvm_reflect should be configured to flush denormal
529 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
530 // property.)
531 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
Yaxun Liue1bfbc52018-07-21 02:02:22 +0000532 CodeGenOpts.FlushDenorm ? 1 : 0);
Justin Lebard3a44f62016-04-05 18:26:20 +0000533 }
534
Alexey Bader364a1162017-06-20 14:30:18 +0000535 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
536 if (LangOpts.OpenCL) {
537 EmitOpenCLMetadata();
538 // Emit SPIR version.
539 if (getTriple().getArch() == llvm::Triple::spir ||
540 getTriple().getArch() == llvm::Triple::spir64) {
541 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
542 // opencl.spir.version named metadata.
543 llvm::Metadata *SPIRVerElts[] = {
544 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
545 Int32Ty, LangOpts.OpenCLVersion / 100)),
546 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
547 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
548 llvm::NamedMDNode *SPIRVerMD =
549 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
550 llvm::LLVMContext &Ctx = TheModule.getContext();
551 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
552 }
553 }
554
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000555 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
Sriraman Tallam70e70e62016-04-28 22:34:00 +0000556 assert(PLevel < 3 && "Invalid PIC Level");
557 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
Rafael Espindolac9d336e2016-06-23 15:07:32 +0000558 if (Context.getLangOpts().PIE)
559 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000560 }
561
Caroline Tice62279732018-09-21 18:34:59 +0000562 if (getCodeGenOpts().CodeModel.size() > 0) {
563 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
564 .Case("tiny", llvm::CodeModel::Tiny)
565 .Case("small", llvm::CodeModel::Small)
566 .Case("kernel", llvm::CodeModel::Kernel)
567 .Case("medium", llvm::CodeModel::Medium)
568 .Case("large", llvm::CodeModel::Large)
569 .Default(~0u);
570 if (CM != ~0u) {
571 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
572 getModule().setCodeModel(codeModel);
573 }
574 }
575
Sriraman Tallam80af0052018-02-23 21:27:33 +0000576 if (CodeGenOpts.NoPLT)
577 getModule().setRtLibUseGOT();
578
John McCall0bdb1fd2010-09-16 06:16:50 +0000579 SimplifyPersonality();
580
John McCall09ae0322010-07-06 23:57:41 +0000581 if (getCodeGenOpts().EmitDeclMetadata)
582 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000583
584 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000585 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000586
587 if (DebugInfo)
588 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000589
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +0000590 if (getCodeGenOpts().EmitVersionIdentMetadata)
591 EmitVersionIdentMetadata();
Robert Lytton57765d52014-07-03 09:30:33 +0000592
Scott Linderde6beb02018-12-14 15:38:15 +0000593 if (!getCodeGenOpts().RecordCommandLine.empty())
594 EmitCommandLineMetadata();
595
Robert Lytton57765d52014-07-03 09:30:33 +0000596 EmitTargetMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000597}
598
Alexey Bader364a1162017-06-20 14:30:18 +0000599void CodeGenModule::EmitOpenCLMetadata() {
600 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
601 // opencl.ocl.version named metadata node.
602 llvm::Metadata *OCLVerElts[] = {
603 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
604 Int32Ty, LangOpts.OpenCLVersion / 100)),
605 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
606 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
607 llvm::NamedMDNode *OCLVerMD =
608 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
609 llvm::LLVMContext &Ctx = TheModule.getContext();
610 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
611}
612
Devang Patel945b8ae2011-03-23 16:29:39 +0000613void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
614 // Make sure that this type is translated.
615 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000616}
617
David Majnemer929025d2016-01-26 19:30:26 +0000618void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
619 // Make sure that this type is translated.
620 Types.RefreshTypeCacheForClass(RD);
621}
622
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000623llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
Dan Gohman947c9af2010-10-14 23:06:10 +0000624 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000625 return nullptr;
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000626 return TBAA->getTypeInfo(QTy);
Dan Gohman947c9af2010-10-14 23:06:10 +0000627}
628
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000629TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
Ivan A. Kosarev124a2182018-02-20 12:33:04 +0000630 if (!TBAA)
631 return TBAAAccessInfo();
632 return TBAA->getAccessInfo(AccessType);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000633}
634
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000635TBAAAccessInfo
636CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000637 if (!TBAA)
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000638 return TBAAAccessInfo();
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000639 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000640}
641
Dan Gohman22695fc2012-09-28 21:58:29 +0000642llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
643 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000644 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000645 return TBAA->getTBAAStructInfo(QTy);
646}
647
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000648llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
649 if (!TBAA)
650 return nullptr;
651 return TBAA->getBaseTypeInfo(QTy);
652}
653
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000654llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
Manman Renc451e572013-04-04 21:53:22 +0000655 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000656 return nullptr;
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000657 return TBAA->getAccessTagInfo(Info);
Manman Renc451e572013-04-04 21:53:22 +0000658}
659
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000660TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
661 TBAAAccessInfo TargetInfo) {
662 if (!TBAA)
663 return TBAAAccessInfo();
664 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
665}
666
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +0000667TBAAAccessInfo
668CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
669 TBAAAccessInfo InfoB) {
670 if (!TBAA)
671 return TBAAAccessInfo();
672 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
673}
674
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000675TBAAAccessInfo
676CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
677 TBAAAccessInfo SrcInfo) {
678 if (!TBAA)
679 return TBAAAccessInfo();
680 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
681}
682
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000683void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000684 TBAAAccessInfo TBAAInfo) {
685 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
686 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
Dan Gohman947c9af2010-10-14 23:06:10 +0000687}
688
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000689void CodeGenModule::DecorateInstructionWithInvariantGroup(
690 llvm::Instruction *I, const CXXRecordDecl *RD) {
Piotr Padlewski34046bd2017-04-24 12:58:43 +0000691 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
692 llvm::MDNode::get(getLLVMContext(), {}));
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000693}
694
Alp Toker29cb66b2014-01-26 06:17:37 +0000695void CodeGenModule::Error(SourceLocation loc, StringRef message) {
696 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
697 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000698}
699
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000700/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000701/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000702void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000703 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000704 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000705 std::string Msg = Type;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000706 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
707 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000708}
Chris Lattner41af8182007-12-02 06:27:33 +0000709
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000710/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000711/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000712void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000713 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000714 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000715 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000716 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000717}
718
John McCall23c29fe2011-06-24 21:55:10 +0000719llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
720 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
721}
722
Mike Stump11289f42009-09-09 15:08:12 +0000723void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000724 const NamedDecl *D) const {
Rafael Espindola123ce972018-01-24 18:58:32 +0000725 if (GV->hasDLLImportStorageClass())
726 return;
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000727 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000728 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000729 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000730 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000731 }
Rafael Espindola3f727a82018-03-14 18:14:46 +0000732 if (!D)
733 return;
John McCallc273f242010-10-30 11:50:40 +0000734 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000735 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000736 if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
Rafael Espindola4a5da442013-02-27 02:56:45 +0000737 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000738}
739
Rafael Espindola699f5d62018-02-07 22:15:33 +0000740static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
Rafael Espindola3dd49812018-02-23 00:22:15 +0000741 llvm::GlobalValue *GV) {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000742 if (GV->hasLocalLinkage())
743 return true;
744
745 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
746 return true;
747
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000748 // DLLImport explicitly marks the GV as external.
749 if (GV->hasDLLImportStorageClass())
750 return false;
751
Rafael Espindola699f5d62018-02-07 22:15:33 +0000752 const llvm::Triple &TT = CGM.getTriple();
Martin Storsjo5ff7a8e2018-08-29 17:26:58 +0000753 if (TT.isWindowsGNUEnvironment()) {
754 // In MinGW, variables without DLLImport can still be automatically
755 // imported from a DLL by the linker; don't mark variables that
756 // potentially could come from another DLL as DSO local.
757 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
758 !GV->isThreadLocal())
759 return false;
760 }
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000761 // Every other GV is local on COFF.
762 // Make an exception for windows OS in the triple: Some firmware builds use
763 // *-win32-macho triples. This (accidentally?) produced windows relocations
764 // without GOT tables in older clang versions; Keep this behaviour.
765 // FIXME: even thread local variables?
766 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
767 return true;
768
769 // Only handle COFF and ELF for now.
Rafael Espindola699f5d62018-02-07 22:15:33 +0000770 if (!TT.isOSBinFormatELF())
771 return false;
772
773 // If this is not an executable, don't assume anything is local.
774 const auto &CGOpts = CGM.getCodeGenOpts();
775 llvm::Reloc::Model RM = CGOpts.RelocationModel;
776 const auto &LOpts = CGM.getLangOpts();
777 if (RM != llvm::Reloc::Static && !LOpts.PIE)
778 return false;
779
780 // A definition cannot be preempted from an executable.
781 if (!GV->isDeclarationForLinker())
782 return true;
783
784 // Most PIC code sequences that assume that a symbol is local cannot produce a
785 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
786 // depended, it seems worth it to handle it here.
787 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
788 return false;
789
790 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
791 llvm::Triple::ArchType Arch = TT.getArch();
792 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
793 Arch == llvm::Triple::ppc64le)
794 return false;
795
796 // If we can use copy relocations we can assume it is local.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000797 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
798 if (!Var->isThreadLocal() &&
Rafael Espindola75e57362018-02-07 23:04:06 +0000799 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
800 return true;
Rafael Espindola699f5d62018-02-07 22:15:33 +0000801
802 // If we can use a plt entry as the symbol address we can assume it
803 // is local.
804 // FIXME: This should work for PIE, but the gold linker doesn't support it.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000805 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
Rafael Espindola699f5d62018-02-07 22:15:33 +0000806 return true;
807
808 // Otherwise don't assue it is local.
809 return false;
810}
811
Rafael Espindola3dd49812018-02-23 00:22:15 +0000812void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000813 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
Rafael Espindola699f5d62018-02-07 22:15:33 +0000814}
815
Rafael Espindolab7350042018-03-01 00:35:47 +0000816void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
817 GlobalDecl GD) const {
818 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
Reid Klecknerae9b0702018-03-16 19:40:50 +0000819 // C++ destructors have a few C++ ABI specific special cases.
Rafael Espindolab7350042018-03-01 00:35:47 +0000820 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
Reid Klecknerae9b0702018-03-16 19:40:50 +0000821 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
822 return;
Rafael Espindolab7350042018-03-01 00:35:47 +0000823 }
824 setDLLImportDLLExport(GV, D);
825}
826
827void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
828 const NamedDecl *D) const {
Rafael Espindola3f727a82018-03-14 18:14:46 +0000829 if (D && D->isExternallyVisible()) {
Rafael Espindolab7350042018-03-01 00:35:47 +0000830 if (D->hasAttr<DLLImportAttr>())
831 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
832 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
833 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
834 }
835}
836
837void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
838 GlobalDecl GD) const {
839 setDLLImportDLLExport(GV, GD);
840 setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
841}
842
Rafael Espindola699f5d62018-02-07 22:15:33 +0000843void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
844 const NamedDecl *D) const {
Rafael Espindolab7350042018-03-01 00:35:47 +0000845 setDLLImportDLLExport(GV, D);
846 setGlobalVisibilityAndLocal(GV, D);
847}
848
849void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
850 const NamedDecl *D) const {
Rafael Espindola699f5d62018-02-07 22:15:33 +0000851 setGlobalVisibility(GV, D);
Rafael Espindola3dd49812018-02-23 00:22:15 +0000852 setDSOLocal(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +0000853}
854
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000855static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
856 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
857 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
858 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
859 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
860 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
861}
862
863static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
864 CodeGenOptions::TLSModel M) {
865 switch (M) {
866 case CodeGenOptions::GeneralDynamicTLSModel:
867 return llvm::GlobalVariable::GeneralDynamicTLSModel;
868 case CodeGenOptions::LocalDynamicTLSModel:
869 return llvm::GlobalVariable::LocalDynamicTLSModel;
870 case CodeGenOptions::InitialExecTLSModel:
871 return llvm::GlobalVariable::InitialExecTLSModel;
872 case CodeGenOptions::LocalExecTLSModel:
873 return llvm::GlobalVariable::LocalExecTLSModel;
874 }
875 llvm_unreachable("Invalid TLS model!");
876}
877
David Majnemerbb525f7c2014-10-15 22:38:23 +0000878void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000879 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000880
David Majnemerbb525f7c2014-10-15 22:38:23 +0000881 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000882 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000883
884 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000885 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000886 TLM = GetLLVMTLSModel(Attr->getModel());
887 }
888
889 GV->setThreadLocalMode(TLM);
890}
891
Erich Keane3efe0022018-07-20 14:13:28 +0000892static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
893 StringRef Name) {
894 const TargetInfo &Target = CGM.getTarget();
895 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
896}
897
898static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
899 const CPUSpecificAttr *Attr,
Erich Keanede6480a32018-11-13 15:48:08 +0000900 unsigned CPUIndex,
Erich Keane3efe0022018-07-20 14:13:28 +0000901 raw_ostream &Out) {
Erich Keane19a8adc2018-10-25 18:57:19 +0000902 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
903 // supported.
Erich Keane3efe0022018-07-20 14:13:28 +0000904 if (Attr)
Erich Keanede6480a32018-11-13 15:48:08 +0000905 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
Erich Keane19a8adc2018-10-25 18:57:19 +0000906 else if (CGM.getTarget().supportsIFunc())
Erich Keane3efe0022018-07-20 14:13:28 +0000907 Out << ".resolver";
908}
909
Erich Keane281d20b2018-01-08 21:34:17 +0000910static void AppendTargetMangling(const CodeGenModule &CGM,
911 const TargetAttr *Attr, raw_ostream &Out) {
912 if (Attr->isDefaultVersion())
913 return;
914
915 Out << '.';
Erich Keane3efe0022018-07-20 14:13:28 +0000916 const TargetInfo &Target = CGM.getTarget();
Erich Keane281d20b2018-01-08 21:34:17 +0000917 TargetAttr::ParsedTargetAttr Info =
918 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
Erich Keane3efe0022018-07-20 14:13:28 +0000919 // Multiversioning doesn't allow "no-${feature}", so we can
920 // only have "+" prefixes here.
921 assert(LHS.startswith("+") && RHS.startswith("+") &&
922 "Features should always have a prefix.");
923 return Target.multiVersionSortPriority(LHS.substr(1)) >
924 Target.multiVersionSortPriority(RHS.substr(1));
925 });
Erich Keane281d20b2018-01-08 21:34:17 +0000926
927 bool IsFirst = true;
928
929 if (!Info.Architecture.empty()) {
930 IsFirst = false;
931 Out << "arch_" << Info.Architecture;
932 }
933
934 for (StringRef Feat : Info.Features) {
935 if (!IsFirst)
936 Out << '_';
937 IsFirst = false;
938 Out << Feat.substr(1);
939 }
940}
941
942static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
943 const NamedDecl *ND,
Erich Keane3efe0022018-07-20 14:13:28 +0000944 bool OmitMultiVersionMangling = false) {
Erich Keane281d20b2018-01-08 21:34:17 +0000945 SmallString<256> Buffer;
946 llvm::raw_svector_ostream Out(Buffer);
947 MangleContext &MC = CGM.getCXXABI().getMangleContext();
948 if (MC.shouldMangleDeclName(ND)) {
949 llvm::raw_svector_ostream Out(Buffer);
950 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
951 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
952 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
953 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
954 else
955 MC.mangleName(ND, Out);
956 } else {
957 IdentifierInfo *II = ND->getIdentifier();
958 assert(II && "Attempt to mangle unnamed decl.");
959 const auto *FD = dyn_cast<FunctionDecl>(ND);
960
961 if (FD &&
962 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
963 llvm::raw_svector_ostream Out(Buffer);
964 Out << "__regcall3__" << II->getName();
965 } else {
966 Out << II->getName();
967 }
968 }
969
970 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Erich Keane3efe0022018-07-20 14:13:28 +0000971 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
Erich Keane5c0d1922018-11-28 18:34:14 +0000972 switch (FD->getMultiVersionKind()) {
973 case MultiVersionKind::CPUDispatch:
974 case MultiVersionKind::CPUSpecific:
Erich Keanede6480a32018-11-13 15:48:08 +0000975 AppendCPUSpecificCPUDispatchMangling(CGM,
976 FD->getAttr<CPUSpecificAttr>(),
977 GD.getMultiVersionIndex(), Out);
Erich Keane5c0d1922018-11-28 18:34:14 +0000978 break;
979 case MultiVersionKind::Target:
Erich Keane3efe0022018-07-20 14:13:28 +0000980 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
Erich Keane5c0d1922018-11-28 18:34:14 +0000981 break;
982 case MultiVersionKind::None:
983 llvm_unreachable("None multiversion type isn't valid here");
984 }
Erich Keane3efe0022018-07-20 14:13:28 +0000985 }
986
Erich Keane281d20b2018-01-08 21:34:17 +0000987 return Out.str();
988}
989
990void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
991 const FunctionDecl *FD) {
992 if (!FD->isMultiVersion())
993 return;
994
995 // Get the name of what this would be without the 'target' attribute. This
996 // allows us to lookup the version that was emitted when this wasn't a
997 // multiversion function.
998 std::string NonTargetName =
Erich Keane3efe0022018-07-20 14:13:28 +0000999 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
Erich Keane281d20b2018-01-08 21:34:17 +00001000 GlobalDecl OtherGD;
1001 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1002 assert(OtherGD.getCanonicalDecl()
1003 .getDecl()
1004 ->getAsFunction()
1005 ->isMultiVersion() &&
1006 "Other GD should now be a multiversioned function");
1007 // OtherFD is the version of this function that was mangled BEFORE
1008 // becoming a MultiVersion function. It potentially needs to be updated.
Erich Keane7304f0a2018-11-28 20:58:43 +00001009 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1010 .getDecl()
1011 ->getAsFunction()
1012 ->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00001013 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1014 // This is so that if the initial version was already the 'default'
1015 // version, we don't try to update it.
1016 if (OtherName != NonTargetName) {
Erich Keanebc40c5c2018-01-09 01:09:12 +00001017 // Remove instead of erase, since others may have stored the StringRef
1018 // to this.
1019 const auto ExistingRecord = Manglings.find(NonTargetName);
1020 if (ExistingRecord != std::end(Manglings))
1021 Manglings.remove(&(*ExistingRecord));
Erich Keane281d20b2018-01-08 21:34:17 +00001022 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1023 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1024 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1025 Entry->setName(OtherName);
1026 }
1027 }
1028}
1029
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001030StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
David Majnemerd2385c02016-01-08 20:48:26 +00001031 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1032
1033 // Some ABIs don't have constructor variants. Make sure that base and
1034 // complete constructors get mangled the same.
1035 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1036 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1037 CXXCtorType OrigCtorType = GD.getCtorType();
1038 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1039 if (OrigCtorType == Ctor_Base)
1040 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1041 }
1042 }
1043
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +00001044 auto FoundName = MangledDeclNames.find(CanonicalGD);
1045 if (FoundName != MangledDeclNames.end())
1046 return FoundName->second;
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001047
Richard Smith6d0e97a2014-08-02 00:50:16 +00001048 // Keep the first result in the case of a mangling collision.
Erich Keane281d20b2018-01-08 21:34:17 +00001049 const auto *ND = cast<NamedDecl>(GD.getDecl());
1050 auto Result =
1051 Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +00001052 return MangledDeclNames[CanonicalGD] = Result.first->first();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +00001053}
1054
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001055StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1056 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001057 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1058 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +00001059
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001060 SmallString<256> Buffer;
1061 llvm::raw_svector_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +00001062 if (!D)
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001063 MangleCtx.mangleGlobalBlock(BD,
Fariborz Jahanian63628032012-06-26 16:06:38 +00001064 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001065 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001066 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001067 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001068 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001069 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001070 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001071
Richard Smith6d0e97a2014-08-02 00:50:16 +00001072 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1073 return Result.first->first();
Anders Carlsson635186a2010-06-09 02:36:32 +00001074}
1075
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001076llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +00001077 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +00001078}
1079
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001080/// AddGlobalCtor - Add a function to the list that will be called before
1081/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001082void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1083 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +00001084 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001085 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001086}
1087
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001088/// AddGlobalDtor - Add a function to the list that will be called
1089/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001090void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Akira Hatanaka617e2612018-04-17 18:41:52 +00001091 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1092 DtorsUsingAtExit[Priority].push_back(Dtor);
1093 return;
1094 }
1095
Daniel Dunbardec798b2009-01-13 02:25:00 +00001096 // FIXME: Type coercion of void()* types.
Craig Topper4b566922014-06-09 02:04:02 +00001097 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001098}
1099
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001100void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001101 if (Fns.empty()) return;
1102
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001103 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +00001104 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Dylan McKay21e7f5e2018-11-09 17:15:06 +00001105 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1106 TheModule.getDataLayout().getProgramAddressSpace());
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001107
Reid Kleckner563f0e82014-05-23 21:13:45 +00001108 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1109 llvm::StructType *CtorStructTy = llvm::StructType::get(
Dylan McKay21e7f5e2018-11-09 17:15:06 +00001110 Int32Ty, CtorPFTy, VoidPtrTy);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001111
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001112 // Construct the constructor and destructor arrays.
John McCall23c9dc62016-11-28 22:18:27 +00001113 ConstantInitBuilder builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001114 auto ctors = builder.beginArray(CtorStructTy);
Yaron Kerenb54db522015-06-11 12:33:25 +00001115 for (const auto &I : Fns) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001116 auto ctor = ctors.beginStruct(CtorStructTy);
1117 ctor.addInt(Int32Ty, I.Priority);
1118 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1119 if (I.AssociatedData)
1120 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1121 else
1122 ctor.addNullPointer(VoidPtrTy);
John McCallf1788632016-11-28 22:18:30 +00001123 ctor.finishAndAddTo(ctors);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001124 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001125
John McCall18081af2016-11-19 20:12:25 +00001126 auto list =
1127 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1128 /*constant*/ false,
1129 llvm::GlobalValue::AppendingLinkage);
1130
1131 // The LTO linker doesn't seem to like it when we set an alignment
1132 // on appending variables. Take it off as a workaround.
1133 list->setAlignment(0);
1134
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001135 Fns.clear();
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001136}
1137
John McCalld4324142010-02-19 01:32:20 +00001138llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001139CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001140 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +00001141
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001142 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +00001143
Reid Klecknerae9b0702018-03-16 19:40:50 +00001144 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1145 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
Reid Klecknera283e482017-12-21 19:44:23 +00001146
Richard Smith5179eb72016-06-28 19:03:57 +00001147 if (isa<CXXConstructorDecl>(D) &&
1148 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1149 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1150 // Our approach to inheriting constructors is fundamentally different from
1151 // that used by the MS ABI, so keep our inheriting constructor thunks
1152 // internal rather than trying to pick an unambiguous mangling for them.
1153 return llvm::GlobalValue::InternalLinkage;
1154 }
1155
Hans Wennborg275efb92014-05-28 01:52:23 +00001156 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +00001157}
Nuno Lopesb6f79532008-06-08 15:45:52 +00001158
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001159llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001160 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1161 if (!MDS) return nullptr;
1162
Benjamin Kramer630cf8c2016-11-23 11:20:27 +00001163 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001164}
1165
Erich Keanede6480a32018-11-13 15:48:08 +00001166void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
Mike Stump11289f42009-09-09 15:08:12 +00001167 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001168 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001169 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +00001170 llvm::AttributeList PAL;
Erich Keanede6480a32018-11-13 15:48:08 +00001171 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
Reid Klecknercdd26792017-04-18 23:50:03 +00001172 F->setAttributes(PAL);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001173 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +00001174}
1175
John McCall9b0a7ce2011-10-02 01:16:38 +00001176/// Determines whether the language options require us to model
1177/// unwind exceptions. We treat -fexceptions as mandating this
1178/// except under the fragile ObjC ABI with only ObjC exceptions
1179/// enabled. This means, for example, that C with -fexceptions
1180/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001181static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +00001182 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001183 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +00001184
1185 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001186 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +00001187
1188 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001189 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +00001190 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +00001191 }
1192
1193 return true;
1194}
1195
Peter Collingbournee44acad2018-06-26 02:15:47 +00001196static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1197 const CXXMethodDecl *MD) {
1198 // Check that the type metadata can ever actually be used by a call.
1199 if (!CGM.getCodeGenOpts().LTOUnit ||
1200 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1201 return false;
1202
1203 // Only functions whose address can be taken with a member function pointer
1204 // need this sort of type metadata.
1205 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1206 !isa<CXXDestructorDecl>(MD);
1207}
1208
1209std::vector<const CXXRecordDecl *>
1210CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1211 llvm::SetVector<const CXXRecordDecl *> MostBases;
1212
1213 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1214 CollectMostBases = [&](const CXXRecordDecl *RD) {
1215 if (RD->getNumBases() == 0)
1216 MostBases.insert(RD);
1217 for (const CXXBaseSpecifier &B : RD->bases())
1218 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1219 };
1220 CollectMostBases(RD);
1221 return MostBases.takeVector();
1222}
1223
Daniel Dunbar38932572009-04-14 08:05:55 +00001224void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1225 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001226 llvm::AttrBuilder B;
1227
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001228 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001229 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001230
David Blaikiebbafb8a2012-03-11 07:00:24 +00001231 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001232 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +00001233
Manoj Gupta4fbf84c2018-05-09 21:41:18 +00001234 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1235 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1236 B.addAttribute(llvm::Attribute::StackProtect);
1237 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1238 B.addAttribute(llvm::Attribute::StackProtectStrong);
1239 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1240 B.addAttribute(llvm::Attribute::StackProtectReq);
1241 }
Akira Hatanaka200500d2015-10-08 19:30:57 +00001242
1243 if (!D) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001244 // If we don't have a declaration to control inlining, the function isn't
1245 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1246 // disabled, mark the function as noinline.
1247 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1248 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1249 B.addAttribute(llvm::Attribute::NoInline);
1250
Reid Kleckneree4930b2017-05-02 22:07:37 +00001251 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Akira Hatanaka200500d2015-10-08 19:30:57 +00001252 return;
1253 }
1254
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001255 // Track whether we need to add the optnone LLVM attribute,
1256 // starting with the default for this optimization level.
1257 bool ShouldAddOptNone =
1258 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1259 // We can't add optnone in the following cases, it won't pass the verifier.
1260 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1261 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1262 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1263
1264 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001265 B.addAttribute(llvm::Attribute::OptimizeNone);
1266
1267 // OptimizeNone implies noinline; we should not be inlining such functions.
1268 B.addAttribute(llvm::Attribute::NoInline);
1269 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1270 "OptimizeNone and AlwaysInline on same function!");
1271
1272 // We still need to handle naked functions even though optnone subsumes
1273 // much of their semantics.
1274 if (D->hasAttr<NakedAttr>())
1275 B.addAttribute(llvm::Attribute::Naked);
1276
1277 // OptimizeNone wins over OptimizeForSize and MinSize.
1278 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1279 F->removeFnAttr(llvm::Attribute::MinSize);
1280 } else if (D->hasAttr<NakedAttr>()) {
Eli Friedmanc55efe42011-08-22 23:55:33 +00001281 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001282 B.addAttribute(llvm::Attribute::Naked);
1283 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001284 } else if (D->hasAttr<NoDuplicateAttr>()) {
1285 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001286 } else if (D->hasAttr<NoInlineAttr>()) {
1287 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +00001288 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Chandler Carruthfcd33142016-12-23 01:24:49 +00001289 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001290 // (noinline wins over always_inline, and we can't specify both in IR)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001291 B.addAttribute(llvm::Attribute::AlwaysInline);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001292 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1293 // If we're not inlining, then force everything that isn't always_inline to
1294 // carry an explicit noinline attribute.
1295 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1296 B.addAttribute(llvm::Attribute::NoInline);
1297 } else {
1298 // Otherwise, propagate the inline hint attribute and potentially use its
1299 // absence to mark things as noinline.
1300 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Trieu9b36a9c2018-10-23 01:26:28 +00001301 // Search function and template pattern redeclarations for inline.
1302 auto CheckForInline = [](const FunctionDecl *FD) {
1303 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1304 return Redecl->isInlineSpecified();
1305 };
1306 if (any_of(FD->redecls(), CheckRedeclForInline))
1307 return true;
1308 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1309 if (!Pattern)
1310 return false;
1311 return any_of(Pattern->redecls(), CheckRedeclForInline);
1312 };
1313 if (CheckForInline(FD)) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001314 B.addAttribute(llvm::Attribute::InlineHint);
1315 } else if (CodeGenOpts.getInlining() ==
1316 CodeGenOptions::OnlyHintInlining &&
1317 !FD->isInlined() &&
1318 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1319 B.addAttribute(llvm::Attribute::NoInline);
1320 }
1321 }
Eli Friedmanc55efe42011-08-22 23:55:33 +00001322 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +00001323
Chandler Carruthfcd33142016-12-23 01:24:49 +00001324 // Add other optimization related attributes if we are optimizing this
1325 // function.
1326 if (!D->hasAttr<OptimizeNoneAttr>()) {
1327 if (D->hasAttr<ColdAttr>()) {
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001328 if (!ShouldAddOptNone)
1329 B.addAttribute(llvm::Attribute::OptimizeForSize);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001330 B.addAttribute(llvm::Attribute::Cold);
1331 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001332
Chandler Carruthfcd33142016-12-23 01:24:49 +00001333 if (D->hasAttr<MinSizeAttr>())
1334 B.addAttribute(llvm::Attribute::MinSize);
1335 }
Richard Smithb555a762012-09-28 22:46:07 +00001336
Reid Kleckneree4930b2017-05-02 22:07:37 +00001337 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001338
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001339 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1340 if (alignment)
1341 F->setAlignment(alignment);
1342
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00001343 if (!D->hasAttr<AlignedAttr>())
1344 if (LangOpts.FunctionAlignment)
1345 F->setAlignment(1 << LangOpts.FunctionAlignment);
1346
Dan Gohmanc2853072015-09-03 22:51:53 +00001347 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1348 // reserve a bit for differentiating between virtual and non-virtual member
1349 // functions. If the current target's C++ ABI requires this and this is a
1350 // member function, set its alignment accordingly.
1351 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1352 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1353 F->setAlignment(2);
1354 }
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001355
1356 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1357 if (CodeGenOpts.SanitizeCfiCrossDso)
1358 if (auto *FD = dyn_cast<FunctionDecl>(D))
Peter Collingbournee44acad2018-06-26 02:15:47 +00001359 CreateFunctionTypeMetadataForIcall(FD, F);
1360
1361 // Emit type metadata on member functions for member function pointer checks.
1362 // These are only ever necessary on definitions; we're guaranteed that the
1363 // definition will be present in the LTO unit as a result of LTO visibility.
1364 auto *MD = dyn_cast<CXXMethodDecl>(D);
1365 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1366 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1367 llvm::Metadata *Id =
1368 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1369 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1370 F->addTypeMetadata(0, Id);
1371 }
1372 }
Daniel Dunbar449a3392008-09-04 23:41:35 +00001373}
1374
Rafael Espindola75c649c2018-03-01 00:06:55 +00001375void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1376 const Decl *D = GD.getDecl();
Rafael Espindolab7350042018-03-01 00:35:47 +00001377 if (dyn_cast_or_null<NamedDecl>(D))
1378 setGVProperties(GV, GD);
John McCall457a04e2010-10-22 21:05:15 +00001379 else
1380 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +00001381
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001382 if (D && D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +00001383 addUsedGlobal(GV);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00001384
1385 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1386 const auto *VD = cast<VarDecl>(D);
Erich Keane85822b32018-10-25 19:13:46 +00001387 if (VD->getType().isConstQualified() &&
1388 VD->getStorageDuration() == SD_Static)
Elizabeth Andrews6593df22018-08-22 19:05:19 +00001389 addUsedGlobal(GV);
1390 }
Rafael Espindola502f65a2014-05-05 20:21:03 +00001391}
1392
Erich Keanede6480a32018-11-13 15:48:08 +00001393bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
Erich Keane93e58662018-02-12 17:01:41 +00001394 llvm::AttrBuilder &Attrs) {
1395 // Add target-cpu and target-features attributes to functions. If
1396 // we have a decl for the function and it has a target attribute then
1397 // parse that and add it to the feature set.
1398 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1399 std::vector<std::string> Features;
Erich Keanede6480a32018-11-13 15:48:08 +00001400 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
Erich Keane93e58662018-02-12 17:01:41 +00001401 FD = FD ? FD->getMostRecentDecl() : FD;
1402 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
Erich Keane3efe0022018-07-20 14:13:28 +00001403 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
Erich Keane93e58662018-02-12 17:01:41 +00001404 bool AddedAttr = false;
Erich Keane3efe0022018-07-20 14:13:28 +00001405 if (TD || SD) {
Erich Keane93e58662018-02-12 17:01:41 +00001406 llvm::StringMap<bool> FeatureMap;
Erich Keanede6480a32018-11-13 15:48:08 +00001407 getFunctionFeatureMap(FeatureMap, GD);
Erich Keane93e58662018-02-12 17:01:41 +00001408
1409 // Produce the canonical string for this set of features.
1410 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1411 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1412
1413 // Now add the target-cpu and target-features to the function.
1414 // While we populated the feature map above, we still need to
1415 // get and parse the target attribute so we can get the cpu for
1416 // the function.
Erich Keane3efe0022018-07-20 14:13:28 +00001417 if (TD) {
1418 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1419 if (ParsedAttr.Architecture != "" &&
1420 getTarget().isValidCPUName(ParsedAttr.Architecture))
1421 TargetCPU = ParsedAttr.Architecture;
1422 }
Erich Keane93e58662018-02-12 17:01:41 +00001423 } else {
1424 // Otherwise just add the existing target cpu and target features to the
1425 // function.
1426 Features = getTarget().getTargetOpts().Features;
1427 }
1428
1429 if (TargetCPU != "") {
1430 Attrs.addAttribute("target-cpu", TargetCPU);
1431 AddedAttr = true;
1432 }
1433 if (!Features.empty()) {
Fangrui Song55fab262018-09-26 22:16:28 +00001434 llvm::sort(Features);
Erich Keane93e58662018-02-12 17:01:41 +00001435 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1436 AddedAttr = true;
1437 }
1438
1439 return AddedAttr;
1440}
1441
Rafael Espindola285271c2018-02-28 23:54:23 +00001442void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
Rafael Espindolaee076a22014-05-13 18:45:53 +00001443 llvm::GlobalObject *GO) {
Rafael Espindola285271c2018-02-28 23:54:23 +00001444 const Decl *D = GD.getDecl();
Rafael Espindola75c649c2018-03-01 00:06:55 +00001445 SetCommonAttributes(GD, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +00001446
Javed Absar2a67c9e2017-06-05 10:11:57 +00001447 if (D) {
1448 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1449 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1450 GV->addAttribute("bss-section", SA->getName());
1451 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1452 GV->addAttribute("data-section", SA->getName());
1453 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1454 GV->addAttribute("rodata-section", SA->getName());
1455 }
1456
1457 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1458 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
Erich Keane30994d22018-02-08 20:04:22 +00001459 if (!D->getAttr<SectionAttr>())
1460 F->addFnAttr("implicit-section-name", SA->getName());
Erich Keane93e58662018-02-12 17:01:41 +00001461
1462 llvm::AttrBuilder Attrs;
Erich Keanede6480a32018-11-13 15:48:08 +00001463 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
Erich Keane93e58662018-02-12 17:01:41 +00001464 // We know that GetCPUAndFeaturesAttributes will always have the
1465 // newest set, since it has the newest possible FunctionDecl, so the
1466 // new ones should replace the old.
1467 F->removeFnAttr("target-cpu");
1468 F->removeFnAttr("target-features");
1469 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1470 }
Javed Absar2a67c9e2017-06-05 10:11:57 +00001471 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001472
Erich Keane7963e8b2018-07-18 20:04:48 +00001473 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1474 GO->setSection(CSA->getName());
1475 else if (const auto *SA = D->getAttr<SectionAttr>())
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001476 GO->setSection(SA->getName());
Javed Absar2a67c9e2017-06-05 10:11:57 +00001477 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001478
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001479 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +00001480}
1481
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001482void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001483 llvm::Function *F,
1484 const CGFunctionInfo &FI) {
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001485 const Decl *D = GD.getDecl();
Erich Keanede6480a32018-11-13 15:48:08 +00001486 SetLLVMFunctionAttributes(GD, FI, F);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001487 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +00001488
1489 F->setLinkage(llvm::Function::InternalLinkage);
1490
Rafael Espindola285271c2018-02-28 23:54:23 +00001491 setNonAliasAttributes(GD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001492}
1493
Rafael Espindolab7350042018-03-01 00:35:47 +00001494static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
David Majnemerf6acb762014-04-25 17:07:16 +00001495 // Set linkage and visibility in case we never see a definition.
1496 LinkageInfo LV = ND->getLinkageAndVisibility();
Rafael Espindolab7350042018-03-01 00:35:47 +00001497 // Don't set internal linkage on declarations.
1498 // "extern_weak" is overloaded in LLVM; we probably should have
1499 // separate linkage types for this.
1500 if (isExternallyVisible(LV.getLinkage()) &&
1501 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1502 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
David Majnemerf6acb762014-04-25 17:07:16 +00001503}
1504
Peter Collingbournee44acad2018-06-26 02:15:47 +00001505void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1506 llvm::Function *F) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001507 // Only if we are checking indirect calls.
1508 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1509 return;
1510
Peter Collingbournee44acad2018-06-26 02:15:47 +00001511 // Non-static class methods are handled via vtable or member function pointer
1512 // checks elsewhere.
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001513 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1514 return;
1515
1516 // Additionally, if building with cross-DSO support...
1517 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001518 // Skip available_externally functions. They won't be codegen'ed in the
1519 // current module anyway.
1520 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1521 return;
1522 }
1523
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001524 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001525 F->addTypeMetadata(0, MD);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00001526 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001527
1528 // Emit a hash-based bit set entry for cross-DSO calls.
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001529 if (CodeGenOpts.SanitizeCfiCrossDso)
1530 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1531 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001532}
1533
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001534void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1535 bool IsIncompleteFunction,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001536 bool IsThunk) {
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001537
Pete Cooper2f1637a2015-05-20 17:17:45 +00001538 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001539 // If this is an intrinsic function, set the function's attributes
1540 // to the intrinsic's attributes.
Pete Cooper2f1637a2015-05-20 17:17:45 +00001541 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001542 return;
1543 }
1544
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001545 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +00001546
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001547 if (!IsIncompleteFunction) {
Erich Keanede6480a32018-11-13 15:48:08 +00001548 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001549 // Setup target-specific attributes.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001550 if (F->isDeclaration())
1551 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001552 }
Mike Stump11289f42009-09-09 15:08:12 +00001553
Bob Wilsonfc6297f2014-04-01 01:38:16 +00001554 // Add the Returned attribute for "this", except for iOS 5 and earlier
1555 // where substantial code, including the libstdc++ dylib, was compiled with
1556 // GCC and does not actually return "this".
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001557 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00001558 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001559 assert(!F->arg_empty() &&
1560 F->arg_begin()->getType()
1561 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1562 "unexpected this return");
1563 F->addAttribute(1, llvm::Attribute::Returned);
1564 }
1565
Daniel Dunbar38932572009-04-14 08:05:55 +00001566 // Only a few attributes are set on declarations; these may later be
1567 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +00001568
Jake Ehrlichba874ad2017-11-29 00:54:20 +00001569 setLinkageForGV(F, FD);
Rafael Espindola699f5d62018-02-07 22:15:33 +00001570 setGVProperties(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +00001571
Erich Keane7963e8b2018-07-18 20:04:48 +00001572 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1573 F->setSection(CSA->getName());
1574 else if (const auto *SA = FD->getAttr<SectionAttr>())
1575 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +00001576
Richard Smith351241c2016-04-07 21:46:12 +00001577 if (FD->isReplaceableGlobalAllocationFunction()) {
1578 // A replaceable global allocation function does not act like a builtin by
1579 // default, only if it is invoked by a new-expression or delete-expression.
Reid Klecknerde864822017-03-21 16:57:30 +00001580 F->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001581 llvm::Attribute::NoBuiltin);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001582
Richard Smith351241c2016-04-07 21:46:12 +00001583 // A sane operator new returns a non-aliasing pointer.
1584 // FIXME: Also add NonNull attribute to the return value
1585 // for the non-nothrow forms?
1586 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1587 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1588 (Kind == OO_New || Kind == OO_Array_New))
Reid Klecknerde864822017-03-21 16:57:30 +00001589 F->addAttribute(llvm::AttributeList::ReturnIndex,
Richard Smith351241c2016-04-07 21:46:12 +00001590 llvm::Attribute::NoAlias);
1591 }
1592
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001593 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001594 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001595 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1596 if (MD->isVirtual())
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001597 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001598
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001599 // Don't emit entries for function declarations in the cross-DSO mode. This
1600 // is handled with better precision by the receiving DSO.
1601 if (!CodeGenOpts.SanitizeCfiCrossDso)
Peter Collingbournee44acad2018-06-26 02:15:47 +00001602 CreateFunctionTypeMetadataForIcall(FD, F);
Alexey Bataevb952e632017-12-15 16:28:31 +00001603
1604 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1605 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001606}
1607
Rafael Espindola060062a2014-03-06 22:15:10 +00001608void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +00001609 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001610 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001611 LLVMUsed.emplace_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001612}
1613
Rafael Espindola060062a2014-03-06 22:15:10 +00001614void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1615 assert(!GV->isDeclaration() &&
1616 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001617 LLVMCompilerUsed.emplace_back(GV);
Rafael Espindola060062a2014-03-06 22:15:10 +00001618}
1619
1620static void emitUsed(CodeGenModule &CGM, StringRef Name,
Sanjoy Dase369bd92017-05-01 17:08:00 +00001621 std::vector<llvm::WeakTrackingVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001622 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +00001623 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001624 return;
1625
Rafael Espindola060062a2014-03-06 22:15:10 +00001626 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +00001627 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +00001628 UsedArray.resize(List.size());
1629 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001630 UsedArray[i] =
Justin Holewinskif37f3d32015-02-02 21:05:49 +00001631 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1632 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +00001633 }
Mike Stump11289f42009-09-09 15:08:12 +00001634
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001635 if (UsedArray.empty())
1636 return;
Rafael Espindola060062a2014-03-06 22:15:10 +00001637 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +00001638
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001639 auto *GV = new llvm::GlobalVariable(
1640 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1641 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001642
1643 GV->setSection("llvm.metadata");
1644}
1645
Rafael Espindola060062a2014-03-06 22:15:10 +00001646void CodeGenModule::emitLLVMUsed() {
1647 emitUsed(*this, "llvm.used", LLVMUsed);
1648 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1649}
1650
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001651void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001652 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001653 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1654}
1655
Aaron Ballman5d041be2013-06-04 02:07:14 +00001656void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1657 llvm::SmallString<32> Opt;
1658 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001659 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballman5d041be2013-06-04 02:07:14 +00001660 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1661}
1662
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00001663void CodeGenModule::AddELFLibDirective(StringRef Lib) {
1664 auto &C = getLLVMContext();
1665 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1666 C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1667}
1668
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001669void CodeGenModule::AddDependentLib(StringRef Lib) {
1670 llvm::SmallString<24> Opt;
1671 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001672 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001673 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1674}
1675
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001676/// Add link options implied by the given module, including modules
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001677/// it depends on, using a postorder walk.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001678static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
Peter Collingbourne89061b22017-06-12 20:10:48 +00001679 SmallVectorImpl<llvm::MDNode *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001680 llvm::SmallPtrSet<Module *, 16> &Visited) {
1681 // Import this module's parent.
David Blaikie82e95a32014-11-19 07:49:47 +00001682 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001683 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001684 }
1685
1686 // Import this module's dependencies.
1687 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001688 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001689 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001690 }
1691
1692 // Add linker options to link against the libraries/frameworks
1693 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001694 llvm::LLVMContext &Context = CGM.getLLVMContext();
Saleem Abdulrasool175890e2019-01-05 19:27:12 +00001695 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
1696 bool IsPS4 = CGM.getTarget().getTriple().isPS4();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00001697
1698 // For modules that use export_as for linking, use that module
1699 // name instead.
1700 if (Mod->UseExportAsModuleLinkName)
1701 return;
1702
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001703 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001704 // Link against a framework. Frameworks are currently Darwin only, so we
1705 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001706 if (Mod->LinkLibraries[I-1].IsFramework) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001707 llvm::Metadata *Args[2] = {
1708 llvm::MDString::get(Context, "-framework"),
1709 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001710
1711 Metadata.push_back(llvm::MDNode::get(Context, Args));
1712 continue;
1713 }
1714
1715 // Link against a library.
Saleem Abdulrasool175890e2019-01-05 19:27:12 +00001716 if (IsELF && !IsPS4) {
1717 llvm::Metadata *Args[2] = {
1718 llvm::MDString::get(Context, "lib"),
1719 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
1720 };
1721 Metadata.push_back(llvm::MDNode::get(Context, Args));
1722 } else {
1723 llvm::SmallString<24> Opt;
1724 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1725 Mod->LinkLibraries[I - 1].Library, Opt);
1726 auto *OptString = llvm::MDString::get(Context, Opt);
1727 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1728 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001729 }
1730}
1731
1732void CodeGenModule::EmitModuleLinkOptions() {
1733 // Collect the set of all of the modules we want to visit to emit link
1734 // options, which is essentially the imported modules and all of their
1735 // non-explicit child modules.
1736 llvm::SetVector<clang::Module *> LinkModules;
1737 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1738 SmallVector<clang::Module *, 16> Stack;
1739
1740 // Seed the stack with imported modules.
Manman Ren9803ee82017-01-11 18:47:38 +00001741 for (Module *M : ImportedModules) {
1742 // Do not add any link flags when an implementation TU of a module imports
1743 // a header of that same module.
1744 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1745 !getLangOpts().isCompilingModule())
1746 continue;
Yaron Kerenb54db522015-06-11 12:33:25 +00001747 if (Visited.insert(M).second)
1748 Stack.push_back(M);
Manman Ren9803ee82017-01-11 18:47:38 +00001749 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001750
1751 // Find all of the modules to import, making a little effort to prune
1752 // non-leaf modules.
1753 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001754 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001755
1756 bool AnyChildren = false;
1757
1758 // Visit the submodules of this module.
Saleem Abdulrasoolda32d7f2019-01-05 18:39:32 +00001759 for (const auto &SM : Mod->submodules()) {
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001760 // Skip explicit children; they need to be explicitly imported to be
1761 // linked against.
Saleem Abdulrasoolda32d7f2019-01-05 18:39:32 +00001762 if (SM->IsExplicit)
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001763 continue;
1764
Saleem Abdulrasoolda32d7f2019-01-05 18:39:32 +00001765 if (Visited.insert(SM).second) {
1766 Stack.push_back(SM);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001767 AnyChildren = true;
1768 }
1769 }
1770
1771 // We didn't find any children, so add this module to the list of
1772 // modules to link against.
1773 if (!AnyChildren) {
1774 LinkModules.insert(Mod);
1775 }
1776 }
1777
1778 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001779 // order. We don't do anything to try to order import link flags with respect
1780 // to linker options inserted by things like #pragma comment().
Peter Collingbourne89061b22017-06-12 20:10:48 +00001781 SmallVector<llvm::MDNode *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001782 Visited.clear();
Yaron Kerenb54db522015-06-11 12:33:25 +00001783 for (Module *M : LinkModules)
1784 if (Visited.insert(M).second)
1785 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
Daniel Dunbar69e47462013-01-17 01:35:06 +00001786 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001787 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001788
Daniel Dunbar69e47462013-01-17 01:35:06 +00001789 // Add the linker options metadata flag.
Peter Collingbourne89061b22017-06-12 20:10:48 +00001790 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1791 for (auto *MD : LinkerOptionsMetadata)
1792 NMD->addOperand(MD);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001793}
1794
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001795void CodeGenModule::EmitDeferred() {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001796 // Emit deferred declare target declarations.
1797 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1798 getOpenMPRuntime().emitDeferredTargetDecls();
1799
Chris Lattner45470942009-03-21 09:44:56 +00001800 // Emit code for any potentially referenced deferred decls. Since a
1801 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001802 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001803
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001804 if (!DeferredVTables.empty()) {
1805 EmitDeferredVTables();
John McCall6bd2a892013-01-25 22:31:03 +00001806
Eric Christopherd160c502016-01-29 01:35:53 +00001807 // Emitting a vtable doesn't directly cause more vtables to
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001808 // become deferred, although it can cause functions to be
Eric Christopherd160c502016-01-29 01:35:53 +00001809 // emitted that then need those vtables.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001810 assert(DeferredVTables.empty());
1811 }
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001812
Eric Christopherd160c502016-01-29 01:35:53 +00001813 // Stop if we're out of both deferred vtables and deferred declarations.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001814 if (DeferredDeclsToEmit.empty())
1815 return;
John McCall6bd2a892013-01-25 22:31:03 +00001816
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001817 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1818 // work, it will not interfere with this.
Sanjoy Das70a60512017-05-01 06:12:13 +00001819 std::vector<GlobalDecl> CurDeclsToEmit;
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001820 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1821
Sanjoy Das70a60512017-05-01 06:12:13 +00001822 for (GlobalDecl &D : CurDeclsToEmit) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00001823 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1824 // to get GlobalValue with exactly the type we need, not something that
1825 // might had been created for another decl with the same mangled name but
1826 // different type.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001827 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
John McCalld195d4c2016-11-30 23:25:13 +00001828 GetAddrOfGlobal(D, ForDefinition));
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001829
1830 // In case of different address spaces, we may still get a cast, even with
1831 // IsForDefinition equal to true. Query mangled names table to get
1832 // GlobalValue.
1833 if (!GV)
1834 GV = GetGlobalValue(getMangledName(D));
1835
1836 // Make sure GetGlobalValue returned non-null.
1837 assert(GV);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001838
John McCallc2af9392010-05-27 01:45:30 +00001839 // Check to see if we've already emitted this. This is necessary
1840 // for a couple of reasons: first, decls can end up in the
1841 // deferred-decls queue multiple times, and second, decls can end
1842 // up with definitions in unusual ways (e.g. by an extern inline
1843 // function acquiring a strong function redefinition). Just
1844 // ignore these cases.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001845 if (!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001846 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001847
Chris Lattner45470942009-03-21 09:44:56 +00001848 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001849 EmitGlobalDefinition(D, GV);
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001850
1851 // If we found out that we need to emit more decls, do that recursively.
1852 // This has the advantage that the decls are emitted in a DFS and related
1853 // ones are close together, which is convenient for testing.
1854 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1855 EmitDeferred();
1856 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1857 }
Chris Lattner45470942009-03-21 09:44:56 +00001858 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001859}
Chris Lattner09153c02007-06-22 18:48:09 +00001860
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001861void CodeGenModule::EmitVTablesOpportunistically() {
1862 // Try to emit external vtables as available_externally if they have emitted
1863 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1864 // is not allowed to create new references to things that need to be emitted
1865 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1866
Piotr Padlewski05547742017-06-01 09:24:36 +00001867 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1868 && "Only emit opportunistic vtables with optimizations");
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001869
1870 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1871 assert(getVTables().isVTableExternal(RD) &&
1872 "This queue should only contain external vtables");
1873 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1874 VTables.GenerateClassData(RD);
1875 }
1876 OpportunisticVTables.clear();
1877}
1878
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001879void CodeGenModule::EmitGlobalAnnotations() {
1880 if (Annotations.empty())
1881 return;
1882
1883 // Create a new global variable for the ConstantStruct in the Module.
1884 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1885 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001886 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1887 llvm::GlobalValue::AppendingLinkage,
1888 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001889 gv->setSection(AnnotationSection);
1890}
1891
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001892llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001893 llvm::Constant *&AStr = AnnotationStrings[Str];
1894 if (AStr)
1895 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001896
1897 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001898 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001899 auto *gv =
1900 new llvm::GlobalVariable(getModule(), s->getType(), true,
1901 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001902 gv->setSection(AnnotationSection);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001903 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Benjamin Kramereed80612013-11-10 16:55:11 +00001904 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001905 return gv;
1906}
1907
1908llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1909 SourceManager &SM = getContext().getSourceManager();
1910 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1911 if (PLoc.isValid())
1912 return EmitAnnotationString(PLoc.getFilename());
1913 return EmitAnnotationString(SM.getBufferName(Loc));
1914}
1915
1916llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1917 SourceManager &SM = getContext().getSourceManager();
1918 PresumedLoc PLoc = SM.getPresumedLoc(L);
1919 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1920 SM.getExpansionLineNumber(L);
1921 return llvm::ConstantInt::get(Int32Ty, LineNo);
1922}
1923
Mike Stump11289f42009-09-09 15:08:12 +00001924llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001925 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001926 SourceLocation L) {
1927 // Get the globals for file name, annotation, and the line number.
1928 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1929 *UnitGV = EmitAnnotationUnit(L),
1930 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001931
Daniel Dunbar346892a2009-04-14 22:41:13 +00001932 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001933 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001934 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1935 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1936 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1937 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001938 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001939 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001940}
1941
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001942void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1943 llvm::GlobalValue *GV) {
1944 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1945 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001946 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1947 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001948}
1949
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001950bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1951 llvm::Function *Fn,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001952 SourceLocation Loc) const {
1953 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1954 // Blacklist by function name.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001955 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001956 return true;
1957 // Blacklist by location.
Yaron Kerened1fe5d2015-10-03 05:15:57 +00001958 if (Loc.isValid())
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001959 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001960 // If location is unknown, this may be a compiler-generated function. Assume
1961 // it's located in the main file.
1962 auto &SM = Context.getSourceManager();
1963 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001964 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001965 }
1966 return false;
1967}
1968
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001969bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1970 SourceLocation Loc, QualType Ty,
1971 StringRef Category) const {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001972 // For now globals can be blacklisted only in ASan and KASan.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001973 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +00001974 (SanitizerKind::Address | SanitizerKind::KernelAddress |
1975 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001976 if (!EnabledAsanMask)
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001977 return false;
1978 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001979 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001980 return true;
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001981 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001982 return true;
1983 // Check global type.
1984 if (!Ty.isNull()) {
1985 // Drill down the array types: if global variable of a fixed type is
1986 // blacklisted, we also don't instrument arrays of them.
1987 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1988 Ty = AT->getElementType();
1989 Ty = Ty.getCanonicalType().getUnqualifiedType();
1990 // We allow to blacklist only record types (classes, structs etc.)
1991 if (Ty->isRecordType()) {
1992 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001993 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001994 return true;
1995 }
1996 }
1997 return false;
1998}
1999
Dean Michael Berris835832d2017-03-30 00:29:36 +00002000bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2001 StringRef Category) const {
Dean Michael Berris835832d2017-03-30 00:29:36 +00002002 const auto &XRayFilter = getContext().getXRayFilter();
2003 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
Dean Michael Berris488f7c22018-04-13 02:31:58 +00002004 auto Attr = ImbueAttr::NONE;
Dean Michael Berris835832d2017-03-30 00:29:36 +00002005 if (Loc.isValid())
2006 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2007 if (Attr == ImbueAttr::NONE)
2008 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2009 switch (Attr) {
2010 case ImbueAttr::NONE:
2011 return false;
2012 case ImbueAttr::ALWAYS:
2013 Fn->addFnAttr("function-instrument", "xray-always");
2014 break;
Dean Michael Berris170429e2017-05-24 05:46:36 +00002015 case ImbueAttr::ALWAYS_ARG1:
2016 Fn->addFnAttr("function-instrument", "xray-always");
2017 Fn->addFnAttr("xray-log-args", "1");
2018 break;
Dean Michael Berris835832d2017-03-30 00:29:36 +00002019 case ImbueAttr::NEVER:
2020 Fn->addFnAttr("function-instrument", "xray-never");
2021 break;
2022 }
2023 return true;
2024}
2025
Hans Wennborg43a0f992015-01-10 01:19:48 +00002026bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00002027 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002028 if (LangOpts.EmitAllDecls)
Hans Wennborg43a0f992015-01-10 01:19:48 +00002029 return true;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002030
Elizabeth Andrews6593df22018-08-22 19:05:19 +00002031 if (CodeGenOpts.KeepStaticConsts) {
2032 const auto *VD = dyn_cast<VarDecl>(Global);
2033 if (VD && VD->getType().isConstQualified() &&
Erich Keane85822b32018-10-25 19:13:46 +00002034 VD->getStorageDuration() == SD_Static)
Elizabeth Andrews6593df22018-08-22 19:05:19 +00002035 return true;
2036 }
2037
Hans Wennborg43a0f992015-01-10 01:19:48 +00002038 return getContext().DeclMustBeEmitted(Global);
2039}
2040
2041bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2042 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
2043 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2044 // Implicit template instantiations may change linkage if they are later
2045 // explicitly instantiated, so they should not be emitted eagerly.
2046 return false;
Richard Smithd9b90092016-07-02 01:32:16 +00002047 if (const auto *VD = dyn_cast<VarDecl>(Global))
2048 if (Context.getInlineVariableDefinitionKind(VD) ==
2049 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2050 // A definition of an inline constexpr static data member may change
2051 // linkage later if it's redeclared outside the class.
2052 return false;
Samuel Antaof8b50122015-07-13 22:54:53 +00002053 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2054 // codegen for global variables, because they may be marked as threadprivate.
2055 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
Alexey Bataev96edb2e2018-06-25 15:32:05 +00002056 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
Alexey Bataevd01b7492018-08-15 19:45:12 +00002057 !isTypeConstant(Global->getType(), false) &&
2058 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
Samuel Antaof8b50122015-07-13 22:54:53 +00002059 return false;
Hans Wennborg43a0f992015-01-10 01:19:48 +00002060
2061 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002062}
2063
John McCall7f416cc2015-09-08 08:05:57 +00002064ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
Nico Webercf4ff5862012-10-11 10:13:44 +00002065 const CXXUuidofExpr* E) {
2066 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
2067 // well-formed.
David Majnemer2041b462016-03-28 03:19:50 +00002068 StringRef Uuid = E->getUuidStr();
David Majnemercf963ce2013-08-09 08:35:59 +00002069 std::string Name = "_GUID_" + Uuid.lower();
2070 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00002071
David Majnemer65687602016-03-27 04:46:14 +00002072 // The UUID descriptor should be pointer aligned.
2073 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
John McCall7f416cc2015-09-08 08:05:57 +00002074
Nico Webercf4ff5862012-10-11 10:13:44 +00002075 // Look for an existing global.
2076 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
John McCall7f416cc2015-09-08 08:05:57 +00002077 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00002078
Nico Weber17d3a2c2014-09-08 16:26:36 +00002079 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Webercf4ff5862012-10-11 10:13:44 +00002080 assert(Init && "failed to initialize as constant");
2081
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002082 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00002083 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00002084 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002085 if (supportsCOMDAT())
2086 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolaca08d242018-03-20 15:42:58 +00002087 setDSOLocal(GV);
John McCall7f416cc2015-09-08 08:05:57 +00002088 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00002089}
2090
John McCall7f416cc2015-09-08 08:05:57 +00002091ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002092 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2093 assert(AA && "No alias?");
2094
John McCall7f416cc2015-09-08 08:05:57 +00002095 CharUnits Alignment = getContext().getDeclAlign(VD);
Chris Lattner2192fe52011-07-18 04:24:23 +00002096 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002097
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002098 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00002099 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002100 if (Entry) {
2101 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
John McCall7f416cc2015-09-08 08:05:57 +00002102 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2103 return ConstantAddress(Ptr, Alignment);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002104 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002105
2106 llvm::Constant *Aliasee;
2107 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002108 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2109 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00002110 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002111 else
John McCall7ec50432010-03-19 23:29:14 +00002112 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00002113 llvm::PointerType::getUnqual(DeclTy),
2114 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002115
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002116 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002117 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2118 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002119
John McCall7f416cc2015-09-08 08:05:57 +00002120 return ConstantAddress(Aliasee, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002121}
2122
Chris Lattnere0be0df2009-05-12 21:21:08 +00002123void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002124 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002125
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002126 // Weak references don't produce any output by themselves.
2127 if (Global->hasAttr<WeakRefAttr>())
2128 return;
2129
Chris Lattner54041692009-03-22 21:47:11 +00002130 // If this is an alias definition (which otherwise looks like a declaration)
2131 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002132 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00002133 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002134
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002135 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2136 if (Global->hasAttr<IFuncAttr>())
2137 return emitIFuncDefinition(GD);
2138
Erich Keane3efe0022018-07-20 14:13:28 +00002139 // If this is a cpu_dispatch multiversion function, emit the resolver.
2140 if (Global->hasAttr<CPUDispatchAttr>())
2141 return emitCPUDispatchDefinition(GD);
2142
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002143 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002144 if (LangOpts.CUDA) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00002145 if (LangOpts.CUDAIsDevice) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002146 if (!Global->hasAttr<CUDADeviceAttr>() &&
2147 !Global->hasAttr<CUDAGlobalAttr>() &&
2148 !Global->hasAttr<CUDAConstantAttr>() &&
2149 !Global->hasAttr<CUDASharedAttr>())
2150 return;
2151 } else {
Artem Belevich42e19492016-03-02 18:28:50 +00002152 // We need to emit host-side 'shadows' for all global
2153 // device-side variables because the CUDA runtime needs their
2154 // size and host-side address in order to provide access to
2155 // their device-side incarnations.
2156
2157 // So device-only functions are the only things we skip.
2158 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2159 Global->hasAttr<CUDADeviceAttr>())
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002160 return;
Artem Belevich42e19492016-03-02 18:28:50 +00002161
2162 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2163 "Expected Variable or Function");
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002164 }
2165 }
2166
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002167 if (LangOpts.OpenMP) {
2168 // If this is OpenMP device, check if it is legal to emit this global
2169 // normally.
2170 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2171 return;
2172 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2173 if (MustBeEmitted(Global))
2174 EmitOMPDeclareReduction(DRD);
2175 return;
2176 }
2177 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002178
Chris Lattner45470942009-03-21 09:44:56 +00002179 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002180 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002181 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002182 if (!FD->doesThisDeclarationHaveABody()) {
2183 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2184 return;
2185
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002186 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00002187
2188 // Compute the function info and LLVM type.
2189 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2190 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2191
2192 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2193 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002194 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002195 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00002196 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002197 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002198 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
Artem Belevich99535772018-12-22 01:11:09 +00002199 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
Richard Smithd9b90092016-07-02 01:32:16 +00002200 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00002201 if (LangOpts.OpenMP) {
2202 // Emit declaration of the must-be-emitted declare target variable.
2203 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2204 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2205 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
2206 (void)GetAddrOfGlobalVar(VD);
2207 } else {
2208 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
2209 "link claue expected.");
2210 (void)getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
2211 }
2212 return;
2213 }
2214 }
Richard Smithd9b90092016-07-02 01:32:16 +00002215 // If this declaration may have caused an inline variable definition to
2216 // change linkage, make sure that it's emitted.
2217 if (Context.getInlineVariableDefinitionKind(VD) ==
2218 ASTContext::InlineVariableDefinitionKind::Strong)
2219 GetAddrOfGlobalVar(VD);
Douglas Gregorbeecd582009-04-21 17:11:58 +00002220 return;
Richard Smithd9b90092016-07-02 01:32:16 +00002221 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002222 }
2223
Hans Wennborg43a0f992015-01-10 01:19:48 +00002224 // Defer code generation to first use when possible, e.g. if this is an inline
2225 // function. If the global must always be emitted, do it eagerly if possible
2226 // to benefit from cache locality.
2227 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002228 // Emit the definition if it can't be deferred.
2229 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002230 return;
2231 }
John McCall70013b62010-07-15 23:40:35 +00002232
2233 // If we're deferring emission of a C++ variable with an
2234 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002235 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00002236 cast<VarDecl>(Global)->hasInit()) {
2237 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00002238 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00002239 }
Hans Wennborg43a0f992015-01-10 01:19:48 +00002240
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002241 StringRef MangledName = getMangledName(GD);
Sanjoy Das70a60512017-05-01 06:12:13 +00002242 if (GetGlobalValue(MangledName) != nullptr) {
Hans Wennborg43a0f992015-01-10 01:19:48 +00002243 // The value has already been used and should therefore be emitted.
Sanjoy Das70a60512017-05-01 06:12:13 +00002244 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002245 } else if (MustBeEmitted(Global)) {
2246 // The value must be emitted, but cannot be emitted eagerly.
2247 assert(!MayBeEmittedEagerly(Global));
Sanjoy Das70a60512017-05-01 06:12:13 +00002248 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002249 } else {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002250 // Otherwise, remember that we saw a deferred decl with this name. The
2251 // first use of the mangled name will cause it to move into
2252 // DeferredDeclsToEmit.
2253 DeferredDecls[MangledName] = GD;
2254 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002255}
2256
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002257// Check if T is a class type with a destructor that's not dllimport.
2258static bool HasNonDllImportDtor(QualType T) {
2259 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2260 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2261 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2262 return true;
2263
2264 return false;
2265}
2266
Rafael Espindolac5941352011-10-26 20:41:06 +00002267namespace {
2268 struct FunctionIsDirectlyRecursive :
2269 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2270 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002271 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00002272 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002273 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2274 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002275 }
2276 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2277
2278 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002279 const FunctionDecl *FD = E->getDirectCallee();
2280 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00002281 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002282 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2283 if (Attr && Name == Attr->getLabel()) {
2284 Result = true;
2285 return false;
2286 }
2287 unsigned BuiltinID = FD->getBuiltinID();
David Majnemer41011f62015-06-25 23:50:40 +00002288 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
Rafael Espindolac5941352011-10-26 20:41:06 +00002289 return true;
Eric Christopher02d5d862015-08-06 01:01:12 +00002290 StringRef BuiltinName = BI.getName(BuiltinID);
Nick Lewycky9ed5b152012-01-18 03:41:19 +00002291 if (BuiltinName.startswith("__builtin_") &&
2292 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002293 Result = true;
2294 return false;
2295 }
2296 return true;
2297 }
2298 };
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002299
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002300 // Make sure we're not referencing non-imported vars or functions.
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002301 struct DLLImportFunctionVisitor
2302 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2303 bool SafeToInline = true;
2304
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002305 bool shouldVisitImplicitCode() const { return true; }
2306
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002307 bool VisitVarDecl(VarDecl *VD) {
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002308 if (VD->getTLSKind()) {
2309 // A thread-local variable cannot be imported.
2310 SafeToInline = false;
2311 return SafeToInline;
2312 }
2313
2314 // A variable definition might imply a destructor call.
2315 if (VD->isThisDeclarationADefinition())
2316 SafeToInline = !HasNonDllImportDtor(VD->getType());
2317
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002318 return SafeToInline;
2319 }
2320
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002321 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2322 if (const auto *D = E->getTemporary()->getDestructor())
2323 SafeToInline = D->hasAttr<DLLImportAttr>();
2324 return SafeToInline;
2325 }
2326
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002327 bool VisitDeclRefExpr(DeclRefExpr *E) {
2328 ValueDecl *VD = E->getDecl();
2329 if (isa<FunctionDecl>(VD))
2330 SafeToInline = VD->hasAttr<DLLImportAttr>();
2331 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2332 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2333 return SafeToInline;
2334 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002335
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002336 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2337 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2338 return SafeToInline;
2339 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002340
Hans Wennborg251c2042017-01-23 23:57:50 +00002341 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2342 CXXMethodDecl *M = E->getMethodDecl();
2343 if (!M) {
2344 // Call through a pointer to member function. This is safe to inline.
2345 SafeToInline = true;
2346 } else {
2347 SafeToInline = M->hasAttr<DLLImportAttr>();
2348 }
2349 return SafeToInline;
2350 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002351
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002352 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2353 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2354 return SafeToInline;
2355 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002356
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002357 bool VisitCXXNewExpr(CXXNewExpr *E) {
2358 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2359 return SafeToInline;
2360 }
2361 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002362}
Rafael Espindolac5941352011-10-26 20:41:06 +00002363
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002364// isTriviallyRecursive - Check if this function calls another
2365// decl that, because of the asm attribute or the other decl being a builtin,
2366// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00002367bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002368CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2369 StringRef Name;
2370 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00002371 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002372 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2373 if (!Attr)
2374 return false;
2375 Name = Attr->getLabel();
2376 } else {
2377 Name = FD->getName();
2378 }
Rafael Espindolac5941352011-10-26 20:41:06 +00002379
David Majnemer64b0bdf2015-06-30 04:41:18 +00002380 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002381 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00002382 return Walker.Result;
2383}
2384
Hans Wennborg93f75472016-09-13 21:08:20 +00002385bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002386 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00002387 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002388 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00002389 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00002390 return false;
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002391
2392 if (F->hasAttr<DLLImportAttr>()) {
2393 // Check whether it would be safe to inline this dllimport function.
2394 DLLImportFunctionVisitor Visitor;
2395 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2396 if (!Visitor.SafeToInline)
2397 return false;
Hans Wennborg93f75472016-09-13 21:08:20 +00002398
2399 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2400 // Implicit destructor invocations aren't captured in the AST, so the
2401 // check above can't see them. Check for them manually here.
2402 for (const Decl *Member : Dtor->getParent()->decls())
2403 if (isa<FieldDecl>(Member))
2404 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2405 return false;
2406 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2407 if (HasNonDllImportDtor(B.getType()))
2408 return false;
2409 }
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002410 }
2411
Rafael Espindolac5941352011-10-26 20:41:06 +00002412 // PR9614. Avoid cases where the source code is lying to us. An available
2413 // externally function should have an equivalent function somewhere else,
2414 // but a function that calls itself is clearly not equivalent to the real
2415 // implementation.
2416 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002417 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00002418}
2419
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002420bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2421 return CodeGenOpts.OptimizationLevel > 0;
2422}
2423
Erich Keanede6480a32018-11-13 15:48:08 +00002424void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
2425 llvm::GlobalValue *GV) {
2426 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2427
2428 if (FD->isCPUSpecificMultiVersion()) {
2429 auto *Spec = FD->getAttr<CPUSpecificAttr>();
2430 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
2431 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
2432 // Requires multiple emits.
2433 } else
2434 EmitGlobalFunctionDefinition(GD, GV);
2435}
2436
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002437void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002438 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002439
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002440 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00002441 Context.getSourceManager(),
2442 "Generating code for declaration");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002443
Erich Keanede6480a32018-11-13 15:48:08 +00002444 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002445 // At -O0, don't generate IR for functions with available_externally
Douglas Gregora700f682010-07-13 06:02:28 +00002446 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002447 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00002448 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00002449
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002450 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +00002451 // Make sure to emit the definition(s) before we emit the thunks.
2452 // This is necessary for the generation of certain thunks.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002453 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002454 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002455 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002456 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Erich Keanede6480a32018-11-13 15:48:08 +00002457 else if (FD->isMultiVersion())
2458 EmitMultiVersionFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002459 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002460 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002461
Douglas Gregora700f682010-07-13 06:02:28 +00002462 if (Method->isVirtual())
2463 getVTables().EmitThunks(GD);
2464
Eli Friedman49a94b12011-05-06 17:27:27 +00002465 return;
Douglas Gregora700f682010-07-13 06:02:28 +00002466 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00002467
Erich Keanede6480a32018-11-13 15:48:08 +00002468 if (FD->isMultiVersion())
2469 return EmitMultiVersionFunctionDefinition(GD, GV);
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002470 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00002471 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002472
2473 if (const auto *VD = dyn_cast<VarDecl>(D))
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002474 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002475
David Blaikie83d382b2011-09-23 05:06:16 +00002476 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00002477}
2478
Andrey Bokhankocab58582015-08-31 13:20:44 +00002479static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2480 llvm::Function *NewFn);
2481
Erich Keanef353ae12018-09-13 16:58:24 +00002482static unsigned
2483TargetMVPriority(const TargetInfo &TI,
2484 const CodeGenFunction::MultiVersionResolverOption &RO) {
2485 unsigned Priority = 0;
2486 for (StringRef Feat : RO.Conditions.Features)
2487 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2488
2489 if (!RO.Conditions.Architecture.empty())
2490 Priority = std::max(
2491 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2492 return Priority;
2493}
2494
Erich Keane281d20b2018-01-08 21:34:17 +00002495void CodeGenModule::emitMultiVersionFunctions() {
2496 for (GlobalDecl GD : MultiVersionFuncs) {
Erich Keanef353ae12018-09-13 16:58:24 +00002497 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
Erich Keane281d20b2018-01-08 21:34:17 +00002498 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2499 getContext().forEachMultiversionedFunctionVersion(
2500 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2501 GlobalDecl CurGD{
2502 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2503 StringRef MangledName = getMangledName(CurGD);
2504 llvm::Constant *Func = GetGlobalValue(MangledName);
2505 if (!Func) {
2506 if (CurFD->isDefined()) {
2507 EmitGlobalFunctionDefinition(CurGD, nullptr);
2508 Func = GetGlobalValue(MangledName);
2509 } else {
2510 const CGFunctionInfo &FI =
2511 getTypes().arrangeGlobalDeclaration(GD);
2512 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2513 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2514 /*DontDefer=*/false, ForDefinition);
2515 }
2516 assert(Func && "This should have just been created");
2517 }
Erich Keanef353ae12018-09-13 16:58:24 +00002518
2519 const auto *TA = CurFD->getAttr<TargetAttr>();
2520 llvm::SmallVector<StringRef, 8> Feats;
2521 TA->getAddedFeatures(Feats);
2522
2523 Options.emplace_back(cast<llvm::Function>(Func),
2524 TA->getArchitecture(), Feats);
Erich Keane281d20b2018-01-08 21:34:17 +00002525 });
2526
Erich Keane19a8adc2018-10-25 18:57:19 +00002527 llvm::Function *ResolverFunc;
2528 const TargetInfo &TI = getTarget();
2529
2530 if (TI.supportsIFunc() || FD->isTargetMultiVersion())
2531 ResolverFunc = cast<llvm::Function>(
2532 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2533 else
2534 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2535
Erich Keane0a6fde42018-01-16 19:49:52 +00002536 if (supportsCOMDAT())
2537 ResolverFunc->setComdat(
2538 getModule().getOrInsertComdat(ResolverFunc->getName()));
Erich Keanef353ae12018-09-13 16:58:24 +00002539
Erich Keane281d20b2018-01-08 21:34:17 +00002540 std::stable_sort(
2541 Options.begin(), Options.end(),
Erich Keanef353ae12018-09-13 16:58:24 +00002542 [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
2543 const CodeGenFunction::MultiVersionResolverOption &RHS) {
2544 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
2545 });
Erich Keane281d20b2018-01-08 21:34:17 +00002546 CodeGenFunction CGF(*this);
Erich Keanef353ae12018-09-13 16:58:24 +00002547 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
Erich Keane281d20b2018-01-08 21:34:17 +00002548 }
2549}
2550
Erich Keane3efe0022018-07-20 14:13:28 +00002551void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2552 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2553 assert(FD && "Not a FunctionDecl?");
2554 const auto *DD = FD->getAttr<CPUDispatchAttr>();
2555 assert(DD && "Not a cpu_dispatch Function?");
Erich Keane9e94c182018-11-01 15:11:41 +00002556 QualType CanonTy = Context.getCanonicalType(FD->getType());
2557 llvm::Type *DeclTy = getTypes().ConvertFunctionType(CanonTy, FD);
2558
2559 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
2560 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
2561 DeclTy = getTypes().GetFunctionType(FInfo);
2562 }
Erich Keane3efe0022018-07-20 14:13:28 +00002563
2564 StringRef ResolverName = getMangledName(GD);
Erich Keane19a8adc2018-10-25 18:57:19 +00002565
2566 llvm::Type *ResolverType;
2567 GlobalDecl ResolverGD;
2568 if (getTarget().supportsIFunc())
2569 ResolverType = llvm::FunctionType::get(
2570 llvm::PointerType::get(DeclTy,
2571 Context.getTargetAddressSpace(FD->getType())),
2572 false);
2573 else {
2574 ResolverType = DeclTy;
2575 ResolverGD = GD;
2576 }
2577
2578 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2579 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
Erich Keane3efe0022018-07-20 14:13:28 +00002580
Erich Keanef353ae12018-09-13 16:58:24 +00002581 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
Erich Keane3efe0022018-07-20 14:13:28 +00002582 const TargetInfo &Target = getTarget();
Erich Keanede6480a32018-11-13 15:48:08 +00002583 unsigned Index = 0;
Erich Keane3efe0022018-07-20 14:13:28 +00002584 for (const IdentifierInfo *II : DD->cpus()) {
2585 // Get the name of the target function so we can look it up/create it.
2586 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
2587 getCPUSpecificMangling(*this, II->getName());
Erich Keanede6480a32018-11-13 15:48:08 +00002588
2589 llvm::Constant *Func = GetGlobalValue(MangledName);
2590
Erich Keane248ed072018-12-07 15:31:23 +00002591 if (!Func) {
2592 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
2593 if (ExistingDecl.getDecl() &&
2594 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
2595 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
2596 Func = GetGlobalValue(MangledName);
2597 } else {
2598 if (!ExistingDecl.getDecl())
2599 ExistingDecl = GD.getWithMultiVersionIndex(Index);
2600
Erich Keanede6480a32018-11-13 15:48:08 +00002601 Func = GetOrCreateLLVMFunction(
Erich Keane248ed072018-12-07 15:31:23 +00002602 MangledName, DeclTy, ExistingDecl,
Erich Keanede6480a32018-11-13 15:48:08 +00002603 /*ForVTable=*/false, /*DontDefer=*/true,
2604 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
Erich Keane248ed072018-12-07 15:31:23 +00002605 }
2606 }
Erich Keanede6480a32018-11-13 15:48:08 +00002607
Erich Keane3efe0022018-07-20 14:13:28 +00002608 llvm::SmallVector<StringRef, 32> Features;
2609 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
2610 llvm::transform(Features, Features.begin(),
2611 [](StringRef Str) { return Str.substr(1); });
2612 Features.erase(std::remove_if(
2613 Features.begin(), Features.end(), [&Target](StringRef Feat) {
2614 return !Target.validateCpuSupports(Feat);
2615 }), Features.end());
Erich Keanef353ae12018-09-13 16:58:24 +00002616 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
Erich Keanede6480a32018-11-13 15:48:08 +00002617 ++Index;
Erich Keane3efe0022018-07-20 14:13:28 +00002618 }
2619
2620 llvm::sort(
Fangrui Song1d38c132018-09-30 21:41:11 +00002621 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
2622 const CodeGenFunction::MultiVersionResolverOption &RHS) {
Erich Keanef353ae12018-09-13 16:58:24 +00002623 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
2624 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
2625 });
Erich Keane44731c52018-11-01 12:50:37 +00002626
2627 // If the list contains multiple 'default' versions, such as when it contains
2628 // 'pentium' and 'generic', don't emit the call to the generic one (since we
2629 // always run on at least a 'pentium'). We do this by deleting the 'least
2630 // advanced' (read, lowest mangling letter).
2631 while (Options.size() > 1 &&
2632 CodeGenFunction::GetX86CpuSupportsMask(
2633 (Options.end() - 2)->Conditions.Features) == 0) {
2634 StringRef LHSName = (Options.end() - 2)->Function->getName();
2635 StringRef RHSName = (Options.end() - 1)->Function->getName();
2636 if (LHSName.compare(RHSName) < 0)
2637 Options.erase(Options.end() - 2);
2638 else
2639 Options.erase(Options.end() - 1);
2640 }
2641
Erich Keane3efe0022018-07-20 14:13:28 +00002642 CodeGenFunction CGF(*this);
Erich Keanef353ae12018-09-13 16:58:24 +00002643 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
Erich Keane3efe0022018-07-20 14:13:28 +00002644}
2645
Erich Keane19a8adc2018-10-25 18:57:19 +00002646/// If a dispatcher for the specified mangled name is not in the module, create
2647/// and return an llvm Function with the specified type.
2648llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
2649 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
Erich Keane3efe0022018-07-20 14:13:28 +00002650 std::string MangledName =
2651 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
Erich Keane19a8adc2018-10-25 18:57:19 +00002652
2653 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
2654 // a separate resolver).
2655 std::string ResolverName = MangledName;
2656 if (getTarget().supportsIFunc())
2657 ResolverName += ".ifunc";
2658 else if (FD->isTargetMultiVersion())
2659 ResolverName += ".resolver";
2660
2661 // If this already exists, just return that one.
2662 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
2663 return ResolverGV;
Erich Keane281d20b2018-01-08 21:34:17 +00002664
2665 // Since this is the first time we've created this IFunc, make sure
2666 // that we put this multiversioned function into the list to be
Erich Keane3efe0022018-07-20 14:13:28 +00002667 // replaced later if necessary (target multiversioning only).
2668 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
2669 MultiVersionFuncs.push_back(GD);
Erich Keane281d20b2018-01-08 21:34:17 +00002670
Erich Keane19a8adc2018-10-25 18:57:19 +00002671 if (getTarget().supportsIFunc()) {
2672 llvm::Type *ResolverType = llvm::FunctionType::get(
2673 llvm::PointerType::get(
2674 DeclTy, getContext().getTargetAddressSpace(FD->getType())),
2675 false);
2676 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2677 MangledName + ".resolver", ResolverType, GlobalDecl{},
2678 /*ForVTable=*/false);
2679 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2680 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2681 GIF->setName(ResolverName);
2682 SetCommonAttributes(FD, GIF);
Erich Keane281d20b2018-01-08 21:34:17 +00002683
Erich Keane19a8adc2018-10-25 18:57:19 +00002684 return GIF;
2685 }
2686
2687 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2688 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
2689 assert(isa<llvm::GlobalValue>(Resolver) &&
2690 "Resolver should be created for the first time");
2691 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
2692 return Resolver;
Erich Keane281d20b2018-01-08 21:34:17 +00002693}
2694
Chris Lattnerd4808922009-03-22 21:03:39 +00002695/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2696/// module, create and return an llvm Function with the specified type. If there
2697/// is something in the module with the specified name, return it potentially
2698/// bitcasted to the right type.
2699///
2700/// If D is non-null, it specifies a decl that correspond to this. This is used
2701/// to set the attributes on the function when it is first created.
Reid Klecknerde864822017-03-21 16:57:30 +00002702llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2703 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2704 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2705 ForDefinition_t IsForDefinition) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002706 const Decl *D = GD.getDecl();
2707
Erich Keane281d20b2018-01-08 21:34:17 +00002708 // Any attempts to use a MultiVersion function should result in retrieving
2709 // the iFunc instead. Name Mangling will handle the rest of the changes.
2710 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002711 // For the device mark the function as one that should be emitted.
2712 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
Alexey Bataev6d944102018-05-02 15:45:28 +00002713 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002714 !DontDefer && !IsForDefinition) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002715 if (const FunctionDecl *FDDef = FD->getDefinition()) {
2716 GlobalDecl GDDef;
2717 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2718 GDDef = GlobalDecl(CD, GD.getCtorType());
2719 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2720 GDDef = GlobalDecl(DD, GD.getDtorType());
2721 else
2722 GDDef = GlobalDecl(FDDef);
2723 EmitGlobal(GDDef);
2724 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002725 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002726
Erich Keane3efe0022018-07-20 14:13:28 +00002727 if (FD->isMultiVersion()) {
2728 const auto *TA = FD->getAttr<TargetAttr>();
2729 if (TA && TA->isDefaultVersion())
2730 UpdateMultiVersionNames(GD, FD);
Erich Keane281d20b2018-01-08 21:34:17 +00002731 if (!IsForDefinition)
Erich Keane19a8adc2018-10-25 18:57:19 +00002732 return GetOrCreateMultiVersionResolver(GD, Ty, FD);
Erich Keane281d20b2018-01-08 21:34:17 +00002733 }
2734 }
2735
Chris Lattnera85d68e2009-03-21 09:25:43 +00002736 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002737 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002738 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002739 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002740 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002741 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002742 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002743 }
2744
Hans Wennborg0a20f542014-08-29 00:16:06 +00002745 // Handle dropped DLL attributes.
Rafael Espindolac9643d82018-03-29 16:45:18 +00002746 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
Hans Wennborg0a20f542014-08-29 00:16:06 +00002747 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
Rafael Espindolac9643d82018-03-29 16:45:18 +00002748 setDSOLocal(Entry);
2749 }
Hans Wennborg0a20f542014-08-29 00:16:06 +00002750
Andrey Bokhankocab58582015-08-31 13:20:44 +00002751 // If there are two attempts to define the same mangled name, issue an
2752 // error.
2753 if (IsForDefinition && !Entry->isDeclaration()) {
2754 GlobalDecl OtherGD;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002755 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2756 // to make sure that we issue an error only once.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002757 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2758 (GD.getCanonicalDecl().getDecl() !=
2759 OtherGD.getCanonicalDecl().getDecl()) &&
2760 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00002761 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2762 << MangledName;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002763 getDiags().Report(OtherGD.getDecl()->getLocation(),
2764 diag::note_previous_definition);
2765 }
2766 }
2767
2768 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2769 (Entry->getType()->getElementType() == Ty)) {
Chris Lattnera85d68e2009-03-21 09:25:43 +00002770 return Entry;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002771 }
Mike Stump11289f42009-09-09 15:08:12 +00002772
Chris Lattnera85d68e2009-03-21 09:25:43 +00002773 // Make sure the result is of the correct type.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002774 // (If function is requested for a definition, we always need to create a new
2775 // function, not just return a bitcast.)
2776 if (!IsForDefinition)
2777 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00002778 }
Mike Stump11289f42009-09-09 15:08:12 +00002779
Eli Friedmancc522d92009-11-09 05:07:37 +00002780 // This function doesn't have a complete type (for example, the return
2781 // type is an incomplete struct). Use a fake type instead, and make
2782 // sure not to try to set attributes.
2783 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00002784
Chris Lattner2192fe52011-07-18 04:24:23 +00002785 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00002786 if (isa<llvm::FunctionType>(Ty)) {
2787 FTy = cast<llvm::FunctionType>(Ty);
2788 } else {
John McCall9dc0db22011-05-15 01:53:33 +00002789 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00002790 IsIncompleteFunction = true;
2791 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002792
2793 llvm::Function *F =
2794 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2795 Entry ? StringRef() : MangledName, &getModule());
2796
2797 // If we already created a function with the same mangled name (but different
2798 // type) before, take its name and add it to the list of functions to be
2799 // replaced with F at the end of CodeGen.
2800 //
2801 // This happens if there is a prototype for a function (e.g. "int f()") and
2802 // then a definition of a different type (e.g. "int f(int x)").
2803 if (Entry) {
2804 F->takeName(Entry);
2805
2806 // This might be an implementation of a function without a prototype, in
2807 // which case, try to do special replacement of calls which match the new
2808 // prototype. The really key thing here is that we also potentially drop
2809 // arguments from the call site so as to make a direct call, which makes the
2810 // inliner happier and suppresses a number of optimizer warnings (!) about
2811 // dropping arguments.
2812 if (!Entry->use_empty()) {
2813 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2814 Entry->removeDeadConstantUsers();
2815 }
2816
2817 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2818 F, Entry->getType()->getElementType()->getPointerTo());
2819 addGlobalValReplacement(Entry, BC);
2820 }
2821
John McCall7ec50432010-03-19 23:29:14 +00002822 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002823 if (D)
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002824 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Reid Klecknerde864822017-03-21 16:57:30 +00002825 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2826 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
Reid Kleckneree4930b2017-05-02 22:07:37 +00002827 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Bill Wendling9a677922013-01-23 00:21:06 +00002828 }
Eli Friedmancc522d92009-11-09 05:07:37 +00002829
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002830 if (!DontDefer) {
2831 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2832 // each other bottoming out with the base dtor. Therefore we emit non-base
2833 // dtors on usage, even if there is no dtor definition in the TU.
2834 if (D && isa<CXXDestructorDecl>(D) &&
2835 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2836 GD.getDtorType()))
Sanjoy Das70a60512017-05-01 06:12:13 +00002837 addDeferredDeclToEmit(GD);
John McCall357d0f32010-12-15 04:00:32 +00002838
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002839 // This is the first use or definition of a mangled name. If there is a
2840 // deferred decl with this name, remember that we need to emit it at the end
2841 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002842 auto DDI = DeferredDecls.find(MangledName);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002843 if (DDI != DeferredDecls.end()) {
2844 // Move the potentially referenced deferred decl to the
2845 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2846 // don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002847 addDeferredDeclToEmit(DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002848 DeferredDecls.erase(DDI);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002849
2850 // Otherwise, there are cases we have to worry about where we're
2851 // using a declaration for which we must emit a definition but where
2852 // we might not find a top-level definition:
2853 // - member functions defined inline in their classes
2854 // - friend functions defined inline in some class
2855 // - special member functions with implicit definitions
2856 // If we ever change our AST traversal to walk into class methods,
2857 // this will be unnecessary.
2858 //
2859 // We also don't emit a definition for a function if it's going to be an
Richard Smith46bb5812014-08-01 01:56:39 +00002860 // entry in a vtable, unless it's already marked as used.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002861 } else if (getLangOpts().CPlusPlus && D) {
2862 // Look for a declaration that's lexically in a record.
Richard Smith46bb5812014-08-01 01:56:39 +00002863 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2864 FD = FD->getPreviousDecl()) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002865 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Richard Smith46bb5812014-08-01 01:56:39 +00002866 if (FD->doesThisDeclarationHaveABody()) {
Sanjoy Das70a60512017-05-01 06:12:13 +00002867 addDeferredDeclToEmit(GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002868 break;
2869 }
John McCall357d0f32010-12-15 04:00:32 +00002870 }
Richard Smith46bb5812014-08-01 01:56:39 +00002871 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002872 }
Chris Lattner45470942009-03-21 09:44:56 +00002873 }
Mike Stump11289f42009-09-09 15:08:12 +00002874
John McCalld06fb862010-04-28 00:00:30 +00002875 // Make sure the result is of the requested type.
2876 if (!IsIncompleteFunction) {
2877 assert(F->getType()->getElementType() == Ty);
2878 return F;
2879 }
2880
Chris Lattnera5f58b02011-07-09 17:41:47 +00002881 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00002882 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002883}
2884
Chris Lattnerd4808922009-03-22 21:03:39 +00002885/// GetAddrOfFunction - Return the address of the given function. If Ty is
2886/// non-null, then this function will use the specified type if it has to
2887/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00002888llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00002889 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002890 bool ForVTable,
Andrey Bokhankocab58582015-08-31 13:20:44 +00002891 bool DontDefer,
John McCalld195d4c2016-11-30 23:25:13 +00002892 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002893 // If there was no specific requested type, just convert it now.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002894 if (!Ty) {
2895 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2896 auto CanonTy = Context.getCanonicalType(FD->getType());
2897 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2898 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002899
Reid Kleckner28103252018-03-16 22:20:57 +00002900 // Devirtualized destructor calls may come through here instead of via
2901 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2902 // of the complete destructor when necessary.
2903 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
2904 if (getTarget().getCXXABI().isMicrosoft() &&
2905 GD.getDtorType() == Dtor_Complete &&
2906 DD->getParent()->getNumVBases() == 0)
2907 GD = GlobalDecl(DD, Dtor_Base);
2908 }
2909
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002910 StringRef MangledName = getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002911 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +00002912 /*IsThunk=*/false, llvm::AttributeList(),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002913 IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002914}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002915
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002916static const FunctionDecl *
2917GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2918 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2919 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2920
2921 IdentifierInfo &CII = C.Idents.get(Name);
2922 for (const auto &Result : DC->lookup(&CII))
2923 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2924 return FD;
2925
2926 if (!C.getLangOpts().CPlusPlus)
2927 return nullptr;
2928
2929 // Demangle the premangled name from getTerminateFn()
2930 IdentifierInfo &CXXII =
Reid Klecknerfb931542018-03-16 20:36:49 +00002931 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002932 ? C.Idents.get("terminate")
2933 : C.Idents.get(Name);
2934
2935 for (const auto &N : {"__cxxabiv1", "std"}) {
2936 IdentifierInfo &NS = C.Idents.get(N);
2937 for (const auto &Result : DC->lookup(&NS)) {
2938 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2939 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2940 for (const auto &Result : LSD->lookup(&NS))
2941 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2942 break;
2943
2944 if (ND)
2945 for (const auto &Result : ND->lookup(&CXXII))
2946 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2947 return FD;
2948 }
2949 }
2950
2951 return nullptr;
2952}
2953
Chris Lattnerd4808922009-03-22 21:03:39 +00002954/// CreateRuntimeFunction - Create a new runtime function with the specified
2955/// type and name.
2956llvm::Constant *
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002957CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
Reid Klecknerde864822017-03-21 16:57:30 +00002958 llvm::AttributeList ExtraAttrs,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002959 bool Local) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002960 llvm::Constant *C =
2961 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002962 /*DontDefer=*/false, /*IsThunk=*/false,
2963 ExtraAttrs);
2964
2965 if (auto *F = dyn_cast<llvm::Function>(C)) {
2966 if (F->empty()) {
John McCall882987f2013-02-28 19:01:20 +00002967 F->setCallingConv(getRuntimeCC());
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002968
2969 if (!Local && getTriple().isOSBinFormatCOFF() &&
Martell Maloneb22e6002017-11-04 02:15:49 +00002970 !getCodeGenOpts().LTOVisibilityPublicStd &&
2971 !getTriple().isWindowsGNUEnvironment()) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002972 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2973 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2974 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2975 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2976 }
2977 }
Rafael Espindola3c9be622018-03-20 20:27:30 +00002978 setDSOLocal(F);
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002979 }
2980 }
2981
John McCall882987f2013-02-28 19:01:20 +00002982 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00002983}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002984
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002985/// CreateBuiltinFunction - Create a new builtin function with the specified
2986/// type and name.
2987llvm::Constant *
Reid Klecknerde864822017-03-21 16:57:30 +00002988CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2989 llvm::AttributeList ExtraAttrs) {
Rafael Espindola1193c372018-03-22 18:03:13 +00002990 return CreateRuntimeFunction(FTy, Name, ExtraAttrs, true);
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002991}
2992
Richard Smithe070fd22012-02-17 06:48:11 +00002993/// isTypeConstant - Determine whether an object of this type can be emitted
2994/// as a constant.
2995///
2996/// If ExcludeCtor is true, the duration when the object's constructor runs
2997/// will not be considered. The caller will need to verify that the object is
2998/// not written to during its construction.
2999bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3000 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00003001 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00003002
David Blaikiebbafb8a2012-03-11 07:00:24 +00003003 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00003004 if (const CXXRecordDecl *Record
3005 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3006 return ExcludeCtor && !Record->hasMutableFields() &&
3007 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00003008 }
Richard Smithe070fd22012-02-17 06:48:11 +00003009
Eli Friedmanb095e152009-12-11 21:23:03 +00003010 return true;
3011}
3012
Chris Lattnerd4808922009-03-22 21:03:39 +00003013/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3014/// create and return an llvm GlobalVariable with the specified type. If there
3015/// is something in the module with the specified name, return it potentially
3016/// bitcasted to the right type.
3017///
3018/// If D is non-null, it specifies a decl that correspond to this. This is used
3019/// to set the attributes on the global when it is first created.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003020///
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003021/// If IsForDefinition is true, it is guaranteed that an actual global with
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003022/// type Ty will be returned, not conversion of a variable with the same
3023/// mangled name but some other type.
John McCall7ec50432010-03-19 23:29:14 +00003024llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003025CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00003026 llvm::PointerType *Ty,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003027 const VarDecl *D,
John McCalld195d4c2016-11-30 23:25:13 +00003028 ForDefinition_t IsForDefinition) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00003029 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00003030 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00003031 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00003032 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00003033 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00003034 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00003035 }
3036
Hans Wennborg0a20f542014-08-29 00:16:06 +00003037 // Handle dropped DLL attributes.
3038 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3039 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3040
Alexey Bataev03f270c2018-03-30 18:31:07 +00003041 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3042 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3043
Chris Lattnerd4808922009-03-22 21:03:39 +00003044 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00003045 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00003046
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003047 // If there are two attempts to define the same mangled name, issue an
3048 // error.
3049 if (IsForDefinition && !Entry->isDeclaration()) {
3050 GlobalDecl OtherGD;
3051 const VarDecl *OtherD;
3052
3053 // Check that D is not yet in DiagnosedConflictingDefinitions is required
3054 // to make sure that we issue an error only once.
Artem Belevich2c323a02016-05-19 18:00:18 +00003055 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003056 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3057 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3058 OtherD->hasInit() &&
3059 DiagnosedConflictingDefinitions.insert(D).second) {
Richard Smithb5345102018-05-30 01:52:16 +00003060 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3061 << MangledName;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003062 getDiags().Report(OtherGD.getDecl()->getLocation(),
3063 diag::note_previous_definition);
3064 }
3065 }
3066
Chris Lattner3bfce182009-03-21 08:03:33 +00003067 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00003068 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3069 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3070
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003071 // (If global is requested for a definition, we always need to create a new
3072 // global, not just return a bitcast.)
3073 if (!IsForDefinition)
3074 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00003075 }
Mike Stump11289f42009-09-09 15:08:12 +00003076
Yaxun Liucbf647c2017-07-08 13:24:52 +00003077 auto AddrSpace = GetGlobalVarAddressSpace(D);
3078 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3079
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003080 auto *GV = new llvm::GlobalVariable(
3081 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00003082 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Yaxun Liucbf647c2017-07-08 13:24:52 +00003083 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00003084
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003085 // If we already created a global with the same mangled name (but different
3086 // type) before, take its name and remove it from its parent.
3087 if (Entry) {
3088 GV->takeName(Entry);
3089
3090 if (!Entry->use_empty()) {
3091 llvm::Constant *NewPtrForOldDecl =
3092 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3093 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3094 }
3095
3096 Entry->eraseFromParent();
3097 }
3098
Chris Lattner45470942009-03-21 09:44:56 +00003099 // This is the first use or definition of a mangled name. If there is a
3100 // deferred decl with this name, remember that we need to emit it at the end
3101 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00003102 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00003103 if (DDI != DeferredDecls.end()) {
3104 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3105 // list, and remove it from DeferredDecls (since we don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00003106 addDeferredDeclToEmit(DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00003107 DeferredDecls.erase(DDI);
3108 }
Mike Stump11289f42009-09-09 15:08:12 +00003109
Chris Lattner3bfce182009-03-21 08:03:33 +00003110 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00003111 if (D) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003112 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3113 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3114
Mike Stump18bb9282009-05-16 07:57:57 +00003115 // FIXME: This code is overly simple and should be merged with other global
3116 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00003117 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00003118
Ulrich Weigand46084382015-04-21 17:27:59 +00003119 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3120
Jake Ehrlichba874ad2017-11-29 00:54:20 +00003121 setLinkageForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00003122
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003123 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00003124 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003125 CXXThreadLocals.push_back(D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +00003126 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003127 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00003128
Rafael Espindola3dd49812018-02-23 00:22:15 +00003129 setGVProperties(GV, D);
3130
Hans Wennborgfeedf852013-11-21 00:15:56 +00003131 // If required by the ABI, treat declarations of static data members with
3132 // inline initializers as definitions.
Hans Wennborg56fc62b2014-07-17 20:25:23 +00003133 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Hans Wennborgfeedf852013-11-21 00:15:56 +00003134 EmitGlobalVarDefinition(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +00003135 }
Robert Lyttonf80d6882014-05-02 09:33:30 +00003136
Erich Keane99fdfb62017-09-26 23:42:34 +00003137 // Emit section information for extern variables.
3138 if (D->hasExternalStorage()) {
3139 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3140 GV->setSection(SA->getName());
3141 }
3142
Robert Lyttonf80d6882014-05-02 09:33:30 +00003143 // Handle XCore specific ABI requirements.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003144 if (getTriple().getArch() == llvm::Triple::xcore &&
Robert Lyttonf80d6882014-05-02 09:33:30 +00003145 D->getLanguageLinkage() == CLanguageLinkage &&
3146 D->getType().isConstant(Context) &&
3147 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3148 GV->setSection(".cp.rodata");
Mehdi Amini7cb1b302017-09-05 03:58:35 +00003149
3150 // Check if we a have a const declaration with an initializer, we may be
3151 // able to emit it as available_externally to expose it's value to the
3152 // optimizer.
3153 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3154 D->getType().isConstQualified() && !GV->hasInitializer() &&
3155 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3156 const auto *Record =
3157 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3158 bool HasMutableFields = Record && Record->hasMutableFields();
3159 if (!HasMutableFields) {
3160 const VarDecl *InitDecl;
3161 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3162 if (InitExpr) {
3163 ConstantEmitter emitter(*this);
3164 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3165 if (Init) {
3166 auto *InitType = Init->getType();
3167 if (GV->getType()->getElementType() != InitType) {
3168 // The type of the initializer does not match the definition.
3169 // This happens when an initializer has a different type from
3170 // the type of the global (because of padding at the end of a
3171 // structure for instance).
3172 GV->setName(StringRef());
3173 // Make a new global with the correct type, this is now guaranteed
3174 // to work.
3175 auto *NewGV = cast<llvm::GlobalVariable>(
3176 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
3177
3178 // Erase the old global, since it is no longer used.
George Burgess IV00f70bd2018-03-01 05:43:23 +00003179 GV->eraseFromParent();
Mehdi Amini7cb1b302017-09-05 03:58:35 +00003180 GV = NewGV;
3181 } else {
3182 GV->setInitializer(Init);
3183 GV->setConstant(true);
3184 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3185 }
3186 emitter.finalize(GV);
3187 }
3188 }
3189 }
3190 }
Chris Lattnerd4808922009-03-22 21:03:39 +00003191 }
Mike Stump11289f42009-09-09 15:08:12 +00003192
Alexander Richardson6d989432017-10-15 18:48:14 +00003193 LangAS ExpectedAS =
Yaxun Liucbf647c2017-07-08 13:24:52 +00003194 D ? D->getType().getAddressSpace()
Alexander Richardson6d989432017-10-15 18:48:14 +00003195 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
Benjamin Kramer6fbfdec2017-07-08 14:14:57 +00003196 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3197 Ty->getPointerAddressSpace());
Yaxun Liucbf647c2017-07-08 13:24:52 +00003198 if (AddrSpace != ExpectedAS)
3199 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3200 ExpectedAS, Ty);
Matt Arsenault00e65b22013-11-15 02:19:52 +00003201
3202 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00003203}
3204
Andrey Bokhankocab58582015-08-31 13:20:44 +00003205llvm::Constant *
3206CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
John McCalld195d4c2016-11-30 23:25:13 +00003207 ForDefinition_t IsForDefinition) {
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003208 const Decl *D = GD.getDecl();
3209 if (isa<CXXConstructorDecl>(D))
3210 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00003211 getFromCtorType(GD.getCtorType()),
3212 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3213 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003214 else if (isa<CXXDestructorDecl>(D))
3215 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00003216 getFromDtorType(GD.getDtorType()),
3217 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3218 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003219 else if (isa<CXXMethodDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00003220 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003221 cast<CXXMethodDecl>(D));
Andrey Bokhankocab58582015-08-31 13:20:44 +00003222 auto Ty = getTypes().GetFunctionType(*FInfo);
3223 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3224 IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003225 } else if (isa<FunctionDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00003226 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3227 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3228 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3229 IsForDefinition);
3230 } else
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003231 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003232 IsForDefinition);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003233}
Chris Lattnerd4808922009-03-22 21:03:39 +00003234
David Greenbe0c5b62018-09-12 14:09:06 +00003235llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3236 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3237 unsigned Alignment) {
Anders Carlssonda80af32011-01-29 18:20:20 +00003238 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00003239 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00003240
Anders Carlssonda80af32011-01-29 18:20:20 +00003241 if (GV) {
3242 // Check if the variable has the right type.
3243 if (GV->getType()->getElementType() == Ty)
3244 return GV;
3245
3246 // Because C++ name mangling, the only way we can end up with an already
3247 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00003248 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00003249 OldGV = GV;
3250 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003251
Anders Carlssonda80af32011-01-29 18:20:20 +00003252 // Create a new variable.
3253 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00003254 Linkage, nullptr, Name);
3255
Anders Carlssonda80af32011-01-29 18:20:20 +00003256 if (OldGV) {
3257 // Replace occurrences of the old variable if needed.
3258 GV->takeName(OldGV);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003259
Anders Carlssonda80af32011-01-29 18:20:20 +00003260 if (!OldGV->use_empty()) {
3261 llvm::Constant *NewPtrForOldDecl =
3262 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3263 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3264 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003265
Anders Carlssonda80af32011-01-29 18:20:20 +00003266 OldGV->eraseFromParent();
3267 }
Rafael Espindolacb92c192015-01-15 23:18:01 +00003268
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003269 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3270 !GV->hasAvailableExternallyLinkage())
3271 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00003272
David Greenbe0c5b62018-09-12 14:09:06 +00003273 GV->setAlignment(Alignment);
3274
Anders Carlssonda80af32011-01-29 18:20:20 +00003275 return GV;
3276}
3277
Chris Lattnerd4808922009-03-22 21:03:39 +00003278/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3279/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00003280/// then it will be created with the specified type instead of whatever the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003281/// normal requested type would be. If IsForDefinition is true, it is guaranteed
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003282/// that an actual global with type Ty will be returned, not conversion of a
3283/// variable with the same mangled name but some other type.
Chris Lattnerd4808922009-03-22 21:03:39 +00003284llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003285 llvm::Type *Ty,
John McCalld195d4c2016-11-30 23:25:13 +00003286 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00003287 assert(D->hasGlobalStorage() && "Not a global variable");
3288 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00003289 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00003290 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00003291
Chris Lattner2192fe52011-07-18 04:24:23 +00003292 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003293 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00003294
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003295 StringRef MangledName = getMangledName(D);
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003296 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00003297}
3298
3299/// CreateRuntimeVariable - Create a new runtime global variable with the
3300/// specified type and name.
3301llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00003302CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003303 StringRef Name) {
Rafael Espindola6ab4ae42018-03-21 01:30:16 +00003304 auto *Ret =
3305 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
3306 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3307 return Ret;
Chris Lattnerd4808922009-03-22 21:03:39 +00003308}
3309
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003310void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3311 assert(!D->getInit() && "Cannot emit definite definitions here!");
3312
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003313 StringRef MangledName = getMangledName(D);
3314 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3315
3316 // We already have a definition, not declaration, with the same mangled name.
3317 // Emitting of declaration is not required (and actually overwrites emitted
3318 // definition).
3319 if (GV && !GV->isDeclaration())
3320 return;
3321
3322 // If we have not seen a reference to this variable yet, place it into the
3323 // deferred declarations table to be emitted if needed later.
3324 if (!MustBeEmitted(D) && !GV) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003325 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003326 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00003327 }
3328
3329 // The tentative definition is the only definition.
Reid Kleckner953fe032015-12-05 01:52:14 +00003330 EmitGlobalVarDefinition(D);
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003331}
3332
Chris Lattner2192fe52011-07-18 04:24:23 +00003333CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00003334 return Context.toCharUnitsFromBits(
3335 getDataLayout().getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00003336}
3337
Alexander Richardson6d989432017-10-15 18:48:14 +00003338LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3339 LangAS AddrSpace = LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003340 if (LangOpts.OpenCL) {
Alexander Richardson6d989432017-10-15 18:48:14 +00003341 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003342 assert(AddrSpace == LangAS::opencl_global ||
3343 AddrSpace == LangAS::opencl_constant ||
3344 AddrSpace == LangAS::opencl_local ||
3345 AddrSpace >= LangAS::FirstTargetAddressSpace);
3346 return AddrSpace;
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003347 }
3348
Yaxun Liucbf647c2017-07-08 13:24:52 +00003349 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3350 if (D && D->hasAttr<CUDAConstantAttr>())
3351 return LangAS::cuda_constant;
3352 else if (D && D->hasAttr<CUDASharedAttr>())
3353 return LangAS::cuda_shared;
Yaxun Liua4005e12018-07-28 03:05:25 +00003354 else if (D && D->hasAttr<CUDADeviceAttr>())
3355 return LangAS::cuda_device;
3356 else if (D && D->getType().isConstQualified())
3357 return LangAS::cuda_constant;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003358 else
3359 return LangAS::cuda_device;
3360 }
3361
3362 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003363}
3364
Yaxun Liudaceb1e2018-05-14 19:20:12 +00003365LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3366 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3367 if (LangOpts.OpenCL)
3368 return LangAS::opencl_constant;
3369 if (auto AS = getTarget().getConstantAddressSpace())
3370 return AS.getValue();
3371 return LangAS::Default;
3372}
3373
3374// In address space agnostic languages, string literals are in default address
3375// space in AST. However, certain targets (e.g. amdgcn) request them to be
3376// emitted in constant address space in LLVM IR. To be consistent with other
3377// parts of AST, string literal global variables in constant address space
3378// need to be casted to default address space before being put into address
3379// map and referenced by other part of CodeGen.
3380// In OpenCL, string literals are in constant address space in AST, therefore
3381// they should not be casted to default address space.
3382static llvm::Constant *
3383castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3384 llvm::GlobalVariable *GV) {
3385 llvm::Constant *Cast = GV;
3386 if (!CGM.getLangOpts().OpenCL) {
3387 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3388 if (AS != LangAS::Default)
3389 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3390 CGM, GV, AS.getValue(), LangAS::Default,
3391 GV->getValueType()->getPointerTo(
3392 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3393 }
3394 }
3395 return Cast;
3396}
3397
Richard Smithdf931ce2013-04-06 05:00:46 +00003398template<typename SomeDecl>
3399void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3400 llvm::GlobalValue *GV) {
3401 if (!getLangOpts().CPlusPlus)
3402 return;
3403
3404 // Must have 'used' attribute, or else inline assembly can't rely on
3405 // the name existing.
3406 if (!D->template hasAttr<UsedAttr>())
3407 return;
3408
3409 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00003410 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00003411 return;
3412
3413 // Must be in an extern "C" context. Entities declared directly within
3414 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003415 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00003416 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00003417 return;
3418
3419 // OK, this is an internal linkage entity inside an extern "C" linkage
3420 // specification. Make a note of that so we can give it the "expected"
3421 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00003422 std::pair<StaticExternCMap::iterator, bool> R =
3423 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00003424
3425 // If we have multiple internal linkage entities with the same name
3426 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00003427 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00003428 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00003429}
3430
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003431static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3432 if (!CGM.supportsCOMDAT())
3433 return false;
3434
3435 if (D.hasAttr<SelectAnyAttr>())
3436 return true;
3437
3438 GVALinkage Linkage;
3439 if (auto *VD = dyn_cast<VarDecl>(&D))
3440 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3441 else
3442 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3443
3444 switch (Linkage) {
3445 case GVA_Internal:
3446 case GVA_AvailableExternally:
3447 case GVA_StrongExternal:
3448 return false;
3449 case GVA_DiscardableODR:
3450 case GVA_StrongODR:
3451 return true;
3452 }
3453 llvm_unreachable("No such linkage");
3454}
3455
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003456void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3457 llvm::GlobalObject &GO) {
3458 if (!shouldBeInCOMDAT(*this, D))
3459 return;
3460 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3461}
3462
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003463/// Pass IsTentative as true if you want to create a tentative definition.
3464void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3465 bool IsTentative) {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003466 // OpenCL global variables of sampler type are translated to function calls,
3467 // therefore no need to be translated.
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003468 QualType ASTTy = D->getType();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003469 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3470 return;
3471
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00003472 // If this is OpenMP device, check if it is legal to emit this global
3473 // normally.
3474 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3475 OpenMPRuntime->emitTargetGlobalVariable(D))
3476 return;
3477
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003478 llvm::Constant *Init = nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00003479 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3480 bool NeedsGlobalCtor = false;
3481 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00003482
Richard Smithdafff942012-01-14 04:30:29 +00003483 const VarDecl *InitDecl;
3484 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003485
John McCallde0fe072017-08-15 21:42:52 +00003486 Optional<ConstantEmitter> emitter;
3487
Artem Belevich97c01c32016-02-02 22:29:48 +00003488 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3489 // as part of their declaration." Sema has already checked for
3490 // error cases, so we just need to set Init to UndefValue.
Artem Belevich7b056662018-12-13 21:43:04 +00003491 bool IsCUDASharedVar =
3492 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
3493 // Shadows of initialized device-side global variables are also left
3494 // undefined.
3495 bool IsCUDAShadowVar =
3496 !getLangOpts().CUDAIsDevice &&
3497 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3498 D->hasAttr<CUDASharedAttr>());
3499 if (getLangOpts().CUDA && (IsCUDASharedVar || IsCUDAShadowVar))
Jingyue Wu284ebe22015-08-22 05:49:28 +00003500 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
Artem Belevich97c01c32016-02-02 22:29:48 +00003501 else if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00003502 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003503 // implicitly initialized with { 0 }.
3504 //
3505 // Note that tentative definitions are only emitted at the end of
3506 // a translation unit, so they should never have incomplete
3507 // type. In addition, EmitTentativeDefinition makes sure that we
3508 // never attempt to emit a tentative definition if a real one
3509 // exists. A use may still exists, however, so we still may need
3510 // to do a RAUW.
3511 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00003512 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003513 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003514 initializedGlobalDecl = GlobalDecl(D);
John McCallde0fe072017-08-15 21:42:52 +00003515 emitter.emplace(*this);
3516 Init = emitter->tryEmitForInitializer(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003517
Fariborz Jahanian63628032012-06-26 16:06:38 +00003518 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00003519 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00003520 if (D->getType()->isReferenceType())
3521 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00003522
David Blaikiebbafb8a2012-03-11 07:00:24 +00003523 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003524 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00003525 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003526 } else {
3527 ErrorUnsupported(D, "static initializer");
3528 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3529 }
John McCall70013b62010-07-15 23:40:35 +00003530 } else {
3531 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00003532 // initializer position (just in case this entry was delayed) if we
3533 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003534 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00003535 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00003536 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003537 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003538
Chris Lattner2192fe52011-07-18 04:24:23 +00003539 llvm::Type* InitType = Init->getType();
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003540 llvm::Constant *Entry =
John McCalld195d4c2016-11-30 23:25:13 +00003541 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
Mike Stump11289f42009-09-09 15:08:12 +00003542
Chris Lattner149927c2009-03-21 09:16:30 +00003543 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003544 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00003545 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00003546 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3547 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00003548 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00003549 Entry = CE->getOperand(0);
3550 }
Mike Stump11289f42009-09-09 15:08:12 +00003551
Chris Lattner149927c2009-03-21 09:16:30 +00003552 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003553 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003554
Chris Lattner149927c2009-03-21 09:16:30 +00003555 // We have a definition after a declaration with the wrong type.
3556 // We must make a new GlobalVariable* and update everything that used OldGV
3557 // (a declaration or tentative definition) with the new GlobalVariable*
3558 // (which will be a definition).
3559 //
3560 // This happens if there is a prototype for a global (e.g.
3561 // "extern int x[];") and then a definition of a different type (e.g.
3562 // "int x[10];"). This also happens when an initializer has a different type
3563 // from the type of the global (this happens with unions).
Yaxun Liucbf647c2017-07-08 13:24:52 +00003564 if (!GV || GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003565 GV->getType()->getAddressSpace() !=
Yaxun Liucbf647c2017-07-08 13:24:52 +00003566 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
Mike Stump11289f42009-09-09 15:08:12 +00003567
John McCall7ec50432010-03-19 23:29:14 +00003568 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003569 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00003570
Chris Lattner149927c2009-03-21 09:16:30 +00003571 // Make a new global with the correct type, this is now guaranteed to work.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003572 GV = cast<llvm::GlobalVariable>(
John McCalld195d4c2016-11-30 23:25:13 +00003573 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
Chris Lattnera85d68e2009-03-21 09:25:43 +00003574
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003575 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00003576 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00003577 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00003578 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003579
3580 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00003581 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00003582 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00003583
Richard Smithdf931ce2013-04-06 05:00:46 +00003584 MaybeHandleStaticInExternC(D, GV);
3585
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003586 if (D->hasAttr<AnnotateAttr>())
3587 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00003588
Artem Belevich42e19492016-03-02 18:28:50 +00003589 // Set the llvm linkage type as appropriate.
3590 llvm::GlobalValue::LinkageTypes Linkage =
3591 getLLVMLinkageVarDefinition(D, GV->isConstant());
3592
Jingyue Wu284ebe22015-08-22 05:49:28 +00003593 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3594 // the device. [...]"
3595 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3596 // __device__, declares a variable that: [...]
3597 // Is accessible from all the threads within the grid and from the host
3598 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3599 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
Artem Belevich42e19492016-03-02 18:28:50 +00003600 if (GV && LangOpts.CUDA) {
3601 if (LangOpts.CUDAIsDevice) {
3602 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3603 GV->setExternallyInitialized(true);
3604 } else {
3605 // Host-side shadows of external declarations of device-side
3606 // global variables become internal definitions. These have to
3607 // be internal in order to prevent name conflicts with global
3608 // host variables with the same name in a different TUs.
3609 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3610 Linkage = llvm::GlobalValue::InternalLinkage;
3611
3612 // Shadow variables and their properties must be registered
3613 // with CUDA runtime.
3614 unsigned Flags = 0;
3615 if (!D->hasDefinition())
3616 Flags |= CGCUDARuntime::ExternDeviceVar;
3617 if (D->hasAttr<CUDAConstantAttr>())
3618 Flags |= CGCUDARuntime::ConstantDeviceVar;
Artem Belevich99535772018-12-22 01:11:09 +00003619 // Extern global variables will be registered in the TU where they are
3620 // defined.
3621 if (!D->hasExternalStorage())
3622 getCUDARuntime().registerDeviceVar(*GV, Flags);
Artem Belevich42e19492016-03-02 18:28:50 +00003623 } else if (D->hasAttr<CUDASharedAttr>())
3624 // __shared__ variables are odd. Shadows do get created, but
3625 // they are not registered with the CUDA runtime, so they
3626 // can't really be used to access their device-side
3627 // counterparts. It's not clear yet whether it's nvcc's bug or
3628 // a feature, but we've got to do the same for compatibility.
3629 Linkage = llvm::GlobalValue::InternalLinkage;
3630 }
Jingyue Wu284ebe22015-08-22 05:49:28 +00003631 }
John McCallde0fe072017-08-15 21:42:52 +00003632
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003633 GV->setInitializer(Init);
John McCallde0fe072017-08-15 21:42:52 +00003634 if (emitter) emitter->finalize(GV);
Chris Lattnerf49573d2009-08-05 05:20:29 +00003635
3636 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00003637 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3638 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00003639
Hans Wennborg899ded92014-10-16 20:52:46 +00003640 // If it is in a read-only section, mark it 'constant'.
3641 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3642 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3643 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3644 GV->setConstant(true);
3645 }
3646
Ken Dyck160146e2010-01-27 17:10:57 +00003647 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00003648
David Majnemer35ab3282014-06-11 04:08:55 +00003649
Manman Ren68150262015-11-11 22:42:31 +00003650 // On Darwin, if the normal linkage of a C++ thread_local variable is
3651 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3652 // copies within a linkage unit; otherwise, the backing variable has
3653 // internal linkage and all accesses should just be calls to the
David Majnemer35ab3282014-06-11 04:08:55 +00003654 // Itanium-specified entry point, which has the normal linkage of the
Manman Ren68150262015-11-11 22:42:31 +00003655 // variable. This is to preserve the ability to change the implementation
3656 // behind the scenes.
David Majnemerbb525f7c2014-10-15 22:38:23 +00003657 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00003658 Context.getTargetInfo().getTriple().isOSDarwin() &&
Manman Ren68150262015-11-11 22:42:31 +00003659 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3660 !llvm::GlobalVariable::isWeakLinkage(Linkage))
David Majnemerbb525f7c2014-10-15 22:38:23 +00003661 Linkage = llvm::GlobalValue::InternalLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00003662
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003663 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00003664 if (D->hasAttr<DLLImportAttr>())
3665 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3666 else if (D->hasAttr<DLLExportAttr>())
3667 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00003668 else
3669 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00003670
Yaxun Liu402804b2016-12-15 08:09:08 +00003671 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
Chris Lattnerf49573d2009-08-05 05:20:29 +00003672 // common vars aren't constant even if declared const.
3673 GV->setConstant(false);
Yaxun Liu402804b2016-12-15 08:09:08 +00003674 // Tentative definition of global variables may be initialized with
3675 // non-zero null pointers. In this case they should have weak linkage
3676 // since common linkage must have zero initializer and must not have
3677 // explicit section therefore cannot have non-zero initial value.
3678 if (!GV->getInitializer()->isNullValue())
3679 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3680 }
Daniel Dunbard272cca2009-04-10 20:26:50 +00003681
Rafael Espindola502f65a2014-05-05 20:21:03 +00003682 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00003683
David Majnemerbb525f7c2014-10-15 22:38:23 +00003684 if (D->getTLSKind() && !GV->isThreadLocal()) {
3685 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003686 CXXThreadLocals.push_back(D);
David Majnemerbb525f7c2014-10-15 22:38:23 +00003687 setTLSMode(GV, *D);
3688 }
3689
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003690 maybeSetTrivialComdat(*D, *GV);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003691
John McCallcdf7ef52010-11-06 09:44:32 +00003692 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00003693 if (NeedsGlobalCtor || NeedsGlobalDtor)
3694 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00003695
Alexey Samsonov4b8de112014-08-01 21:35:28 +00003696 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany28a26c82012-08-21 06:53:28 +00003697
Sanjiv Gupta158143a2008-06-05 08:59:10 +00003698 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00003699 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00003700 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00003701 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003702}
Chris Lattner09153c02007-06-22 18:48:09 +00003703
David Majnemerc017d362014-08-05 00:01:13 +00003704static bool isVarDeclStrongDefinition(const ASTContext &Context,
Nico Weber608e7682015-04-15 23:04:24 +00003705 CodeGenModule &CGM, const VarDecl *D,
3706 bool NoCommon) {
David Majnemer9832a3d2014-04-10 16:53:16 +00003707 // Don't give variables common linkage if -fno-common was specified unless it
3708 // was overridden by a NoCommon attribute.
3709 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3710 return true;
3711
3712 // C11 6.9.2/2:
3713 // A declaration of an identifier for an object that has file scope without
3714 // an initializer, and without a storage-class specifier or with the
3715 // storage-class specifier static, constitutes a tentative definition.
3716 if (D->getInit() || D->hasExternalStorage())
3717 return true;
3718
3719 // A variable cannot be both common and exist in a section.
3720 if (D->hasAttr<SectionAttr>())
3721 return true;
3722
Javed Absar2a67c9e2017-06-05 10:11:57 +00003723 // A variable cannot be both common and exist in a section.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003724 // We don't try to determine which is the right section in the front-end.
Javed Absar2a67c9e2017-06-05 10:11:57 +00003725 // If no specialized section name is applicable, it will resort to default.
3726 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3727 D->hasAttr<PragmaClangDataSectionAttr>() ||
3728 D->hasAttr<PragmaClangRodataSectionAttr>())
3729 return true;
3730
David Majnemer9832a3d2014-04-10 16:53:16 +00003731 // Thread local vars aren't considered common linkage.
3732 if (D->getTLSKind())
3733 return true;
3734
3735 // Tentative definitions marked with WeakImportAttr are true definitions.
3736 if (D->hasAttr<WeakImportAttr>())
3737 return true;
3738
Nico Weber608e7682015-04-15 23:04:24 +00003739 // A variable cannot be both common and exist in a comdat.
3740 if (shouldBeInCOMDAT(CGM, *D))
3741 return true;
3742
Sanjay Patel2f9303a2016-06-30 21:02:40 +00003743 // Declarations with a required alignment do not have common linkage in MSVC
David Majnemerc017d362014-08-05 00:01:13 +00003744 // mode.
David Majnemer3f021502015-10-08 04:53:31 +00003745 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemere1a0b2e2015-02-03 08:49:32 +00003746 if (D->hasAttr<AlignedAttr>())
3747 return true;
3748 QualType VarType = D->getType();
3749 if (Context.isAlignmentRequired(VarType))
3750 return true;
3751
3752 if (const auto *RT = VarType->getAs<RecordType>()) {
3753 const RecordDecl *RD = RT->getDecl();
3754 for (const FieldDecl *FD : RD->fields()) {
3755 if (FD->isBitField())
3756 continue;
3757 if (FD->hasAttr<AlignedAttr>())
3758 return true;
3759 if (Context.isAlignmentRequired(FD->getType()))
3760 return true;
3761 }
3762 }
3763 }
Erich Keane85c62242019-01-08 18:44:22 +00003764 // COFF doesn't support alignments greater than 32, so these cannot be
3765 // in common.
3766 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
3767 Context.getTypeAlignIfKnown(D->getType()) > 32)
3768 return true;
David Majnemerc017d362014-08-05 00:01:13 +00003769
David Majnemer9832a3d2014-04-10 16:53:16 +00003770 return false;
3771}
3772
Hans Wennborg1a3a0742014-05-14 19:54:53 +00003773llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00003774 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003775 if (Linkage == GVA_Internal)
3776 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003777
3778 if (D->hasAttr<WeakAttr>()) {
3779 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003780 return llvm::GlobalVariable::WeakODRLinkage;
3781 else
3782 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003783 }
3784
Erich Keane7ef210d2018-10-22 21:20:45 +00003785 if (const auto *FD = D->getAsFunction())
3786 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
3787 return llvm::GlobalVariable::LinkOnceAnyLinkage;
3788
David Majnemer27d69db2014-04-28 22:17:59 +00003789 // We are guaranteed to have a strong definition somewhere else,
3790 // so we can use available_externally linkage.
3791 if (Linkage == GVA_AvailableExternally)
David Blaikie9ffe5a32017-01-30 05:00:26 +00003792 return llvm::GlobalValue::AvailableExternallyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003793
David Majnemer27d69db2014-04-28 22:17:59 +00003794 // Note that Apple's kernel linker doesn't support symbol
3795 // coalescing, so we need to avoid linkonce and weak linkages there.
3796 // Normally, this means we just map to internal, but for explicit
3797 // instantiations we'll map to external.
3798
3799 // In C++, the compiler has to emit a definition in every translation unit
3800 // that references the function. We should use linkonce_odr because
3801 // a) if all references in this translation unit are optimized away, we
3802 // don't need to codegen it. b) if the function persists, it needs to be
3803 // merged with other definitions. c) C++ has the ODR, so we know the
3804 // definition is dependable.
3805 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00003806 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00003807 : llvm::Function::InternalLinkage;
3808
3809 // An explicit instantiation of a template has weak linkage, since
3810 // explicit instantiations can occur in multiple translation units
3811 // and must all be equivalent. However, we are not allowed to
3812 // throw away these explicit instantiations.
Justin Lebar27ee1302016-06-30 18:41:33 +00003813 //
3814 // We don't currently support CUDA device code spread out across multiple TUs,
3815 // so say that CUDA templates are either external (for kernels) or internal.
3816 // This lets llvm perform aggressive inter-procedural optimizations.
3817 if (Linkage == GVA_StrongODR) {
3818 if (Context.getLangOpts().AppleKext)
3819 return llvm::Function::ExternalLinkage;
3820 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3821 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3822 : llvm::Function::InternalLinkage;
3823 return llvm::Function::WeakODRLinkage;
3824 }
David Majnemer27d69db2014-04-28 22:17:59 +00003825
David Majnemer27d69db2014-04-28 22:17:59 +00003826 // C++ doesn't have tentative definitions and thus cannot have common
3827 // linkage.
3828 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Nico Weber608e7682015-04-15 23:04:24 +00003829 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
David Majnemerc017d362014-08-05 00:01:13 +00003830 CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00003831 return llvm::GlobalVariable::CommonLinkage;
3832
David Majnemer27d69db2014-04-28 22:17:59 +00003833 // selectany symbols are externally visible, so use weak instead of
3834 // linkonce. MSVC optimizes away references to const selectany globals, so
3835 // all definitions should be the same and ODR linkage should be used.
3836 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3837 if (D->hasAttr<SelectAnyAttr>())
3838 return llvm::GlobalVariable::WeakODRLinkage;
3839
3840 // Otherwise, we have strong external linkage.
3841 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003842 return llvm::GlobalVariable::ExternalLinkage;
3843}
3844
David Majnemer27d69db2014-04-28 22:17:59 +00003845llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3846 const VarDecl *VD, bool IsConstant) {
3847 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00003848 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00003849}
3850
John McCall49954ca2012-12-12 22:21:47 +00003851/// Replace the uses of a function that was declared with a non-proto type.
3852/// We want to silently drop extra arguments from call sites
3853static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3854 llvm::Function *newFn) {
3855 // Fast path.
3856 if (old->use_empty()) return;
3857
3858 llvm::Type *newRetTy = newFn->getReturnType();
3859 SmallVector<llvm::Value*, 4> newArgs;
David Majnemer0b17d442015-12-15 21:27:59 +00003860 SmallVector<llvm::OperandBundleDef, 1> newBundles;
John McCall49954ca2012-12-12 22:21:47 +00003861
3862 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3863 ui != ue; ) {
3864 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003865 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00003866
3867 // Recognize and replace uses of bitcasts. Most calls to
3868 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003869 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00003870 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3871 replaceUsesOfNonProtoConstant(bitcast, newFn);
3872 continue;
3873 }
3874
3875 // Recognize calls to the function.
3876 llvm::CallSite callSite(user);
3877 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003878 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00003879
3880 // If the return types don't match exactly, then we can't
3881 // transform this call unless it's dead.
3882 if (callSite->getType() != newRetTy && !callSite->use_empty())
3883 continue;
3884
3885 // Get the call site's attribute list.
Reid Kleckner7f720332017-04-13 00:58:09 +00003886 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
Reid Klecknerde864822017-03-21 16:57:30 +00003887 llvm::AttributeList oldAttrs = callSite.getAttributes();
John McCall49954ca2012-12-12 22:21:47 +00003888
John McCall49954ca2012-12-12 22:21:47 +00003889 // If the function was passed too few arguments, don't transform.
3890 unsigned newNumArgs = newFn->arg_size();
3891 if (callSite.arg_size() < newNumArgs) continue;
3892
3893 // If extra arguments were passed, we silently drop them.
3894 // If any of the types mismatch, we don't transform.
3895 unsigned argNo = 0;
3896 bool dontTransform = false;
Reid Kleckner7f720332017-04-13 00:58:09 +00003897 for (llvm::Argument &A : newFn->args()) {
3898 if (callSite.getArgument(argNo)->getType() != A.getType()) {
John McCall49954ca2012-12-12 22:21:47 +00003899 dontTransform = true;
3900 break;
3901 }
3902
3903 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00003904 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
Reid Kleckner7f720332017-04-13 00:58:09 +00003905 argNo++;
John McCall49954ca2012-12-12 22:21:47 +00003906 }
3907 if (dontTransform)
3908 continue;
3909
John McCall49954ca2012-12-12 22:21:47 +00003910 // Okay, we can transform this. Create the new call instruction and copy
3911 // over the required information.
3912 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3913
David Majnemer0b17d442015-12-15 21:27:59 +00003914 // Copy over any operand bundles.
3915 callSite.getOperandBundlesAsDefs(newBundles);
3916
John McCall49954ca2012-12-12 22:21:47 +00003917 llvm::CallSite newCall;
3918 if (callSite.isCall()) {
David Majnemer0b17d442015-12-15 21:27:59 +00003919 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003920 callSite.getInstruction());
3921 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003922 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCall49954ca2012-12-12 22:21:47 +00003923 newCall = llvm::InvokeInst::Create(newFn,
3924 oldInvoke->getNormalDest(),
3925 oldInvoke->getUnwindDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003926 newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003927 callSite.getInstruction());
3928 }
3929 newArgs.clear(); // for the next iteration
3930
3931 if (!newCall->getType()->isVoidTy())
3932 newCall->takeName(callSite.getInstruction());
Reid Kleckner7f720332017-04-13 00:58:09 +00003933 newCall.setAttributes(llvm::AttributeList::get(
3934 newFn->getContext(), oldAttrs.getFnAttributes(),
3935 oldAttrs.getRetAttributes(), newArgAttrs));
John McCall49954ca2012-12-12 22:21:47 +00003936 newCall.setCallingConv(callSite.getCallingConv());
3937
3938 // Finally, remove the old call, replacing any uses with the new one.
3939 if (!callSite->use_empty())
3940 callSite->replaceAllUsesWith(newCall.getInstruction());
3941
3942 // Copy debug location attached to CI.
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00003943 if (callSite->getDebugLoc())
John McCall49954ca2012-12-12 22:21:47 +00003944 newCall->setDebugLoc(callSite->getDebugLoc());
David Majnemer0b17d442015-12-15 21:27:59 +00003945
John McCall49954ca2012-12-12 22:21:47 +00003946 callSite->eraseFromParent();
3947 }
3948}
3949
Chris Lattner36797ab2009-05-05 06:16:31 +00003950/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3951/// implement a function with no prototype, e.g. "int foo() {}". If there are
3952/// existing call uses of the old function in the module, this adjusts them to
3953/// call the new function directly.
3954///
3955/// This is not just a cleanup: the always_inline pass requires direct calls to
3956/// functions to be able to inline them. If there is a bitcast in the way, it
3957/// won't inline them. Instcombine normally deletes these calls, but it isn't
3958/// run at -O0.
3959static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3960 llvm::Function *NewFn) {
3961 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00003962 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00003963
John McCall49954ca2012-12-12 22:21:47 +00003964 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00003965}
3966
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003967void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
David Majnemer60e5bdc2016-07-11 04:28:21 +00003968 auto DK = VD->isThisDeclarationADefinition();
3969 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3970 return;
3971
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003972 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3973 // If we have a definition, this might be a deferred decl. If the
3974 // instantiation is explicit, make sure we emit it at the end.
3975 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3976 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003977
3978 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00003979}
Daniel Dunbar9c426522008-07-29 23:18:29 +00003980
Rafael Espindolacd7743b2013-12-09 16:01:03 +00003981void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3982 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003983 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00003984
John McCall46288ef2011-03-09 08:12:35 +00003985 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00003986 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3987 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00003988
Chris Lattnereb7466d2009-05-12 20:58:15 +00003989 // Get or create the prototype for the function.
Andrey Bokhankocab58582015-08-31 13:20:44 +00003990 if (!GV || (GV->getType()->getElementType() != Ty))
3991 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3992 /*DontDefer=*/true,
John McCalld195d4c2016-11-30 23:25:13 +00003993 ForDefinition));
Mike Stump11289f42009-09-09 15:08:12 +00003994
Andrey Bokhankocab58582015-08-31 13:20:44 +00003995 // Already emitted.
3996 if (!GV->isDeclaration())
Renato Golinc640ff62015-04-15 08:44:40 +00003997 return;
Mike Stump11289f42009-09-09 15:08:12 +00003998
John McCall8e7cb6d2010-11-02 21:04:24 +00003999 // We need to set linkage and visibility on the function before
4000 // generating code for it because various parts of IR generation
4001 // want to propagate this information down (e.g. to local static
4002 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004003 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00004004 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00004005
Rafael Espindolae033c8c2014-05-08 15:26:12 +00004006 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Rafael Espindolab7350042018-03-01 00:35:47 +00004007 setGVProperties(Fn, GD);
John McCall8e7cb6d2010-11-02 21:04:24 +00004008
Richard Smithdf931ce2013-04-06 05:00:46 +00004009 MaybeHandleStaticInExternC(D, Fn);
4010
Yaxun Liu4306f202018-04-20 17:01:03 +00004011
Rafael Espindoladbee8a72015-01-15 21:36:08 +00004012 maybeSetTrivialComdat(*D, *Fn);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00004013
John McCalla738c252011-03-09 04:27:21 +00004014 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00004015
Rafael Espindolae4e78132018-03-01 00:00:02 +00004016 setNonAliasAttributes(GD, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00004017 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00004018
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004019 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00004020 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004021 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00004022 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00004023 if (D->hasAttr<AnnotateAttr>())
4024 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00004025}
4026
John McCall7ec50432010-03-19 23:29:14 +00004027void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004028 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004029 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00004030 assert(AA && "Not an alias?");
4031
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004032 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00004033
Hal Finkel0e2b9752015-09-04 21:49:21 +00004034 if (AA->getAliasee() == MangledName) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004035 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Hal Finkel0e2b9752015-09-04 21:49:21 +00004036 return;
4037 }
4038
John McCall7ec50432010-03-19 23:29:14 +00004039 // If there is a definition in the module, then it wins over the alias.
4040 // This is dubious, but allow it to be safe. Just ignore the alias.
4041 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4042 if (Entry && !Entry->isDeclaration())
4043 return;
4044
Rafael Espindola208b5c02013-10-22 19:26:13 +00004045 Aliases.push_back(GD);
4046
Chris Lattner2192fe52011-07-18 04:24:23 +00004047 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00004048
4049 // Create a reference to the named value. This ensures that it is emitted
4050 // if a deferred decl.
4051 llvm::Constant *Aliasee;
4052 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00004053 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00004054 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00004055 else
John McCall7ec50432010-03-19 23:29:14 +00004056 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00004057 llvm::PointerType::getUnqual(DeclTy),
David Majnemerbb525f7c2014-10-15 22:38:23 +00004058 /*D=*/nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00004059
4060 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00004061 auto *GA = llvm::GlobalAlias::create(
David Blaikie2a791d72015-09-14 18:38:22 +00004062 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00004063
Chris Lattner54041692009-03-22 21:47:11 +00004064 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00004065 if (GA->getAliasee() == Entry) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004066 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Rafael Espindolab2633b92014-05-16 19:35:48 +00004067 return;
4068 }
4069
John McCall7ec50432010-03-19 23:29:14 +00004070 assert(Entry->isDeclaration());
4071
Chris Lattner54041692009-03-22 21:47:11 +00004072 // If there is a declaration in the module, then we had an extern followed
4073 // by the alias, as in:
4074 // extern int test6();
4075 // ...
4076 // int test6() __attribute__((alias("test7")));
4077 //
4078 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00004079 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00004080
Owen Andersonade90fd2009-07-29 18:54:39 +00004081 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00004082 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00004083 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00004084 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00004085 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00004086 }
Mike Stump11289f42009-09-09 15:08:12 +00004087
Daniel Dunbar38932572009-04-14 08:05:55 +00004088 // Set attributes which are particular to an alias; this is a
4089 // specialization of the attributes which may be set on a global
4090 // variable/function.
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00004091 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4092 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00004093 GA->setLinkage(llvm::Function::WeakAnyLinkage);
4094 }
4095
David Majnemerbb525f7c2014-10-15 22:38:23 +00004096 if (const auto *VD = dyn_cast<VarDecl>(D))
4097 if (VD->getTLSKind())
4098 setTLSMode(GA, *VD);
4099
Rafael Espindolab7350042018-03-01 00:35:47 +00004100 SetCommonAttributes(GD, GA);
Chris Lattner54041692009-03-22 21:47:11 +00004101}
4102
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004103void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4104 const auto *D = cast<ValueDecl>(GD.getDecl());
4105 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4106 assert(IFA && "Not an ifunc?");
4107
4108 StringRef MangledName = getMangledName(GD);
4109
4110 if (IFA->getResolver() == MangledName) {
4111 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4112 return;
4113 }
4114
4115 // Report an error if some definition overrides ifunc.
4116 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4117 if (Entry && !Entry->isDeclaration()) {
4118 GlobalDecl OtherGD;
4119 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4120 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00004121 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4122 << MangledName;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004123 Diags.Report(OtherGD.getDecl()->getLocation(),
4124 diag::note_previous_definition);
4125 }
4126 return;
4127 }
4128
4129 Aliases.push_back(GD);
4130
4131 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4132 llvm::Constant *Resolver =
4133 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4134 /*ForVTable=*/false);
4135 llvm::GlobalIFunc *GIF =
4136 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4137 "", Resolver, &getModule());
4138 if (Entry) {
4139 if (GIF->getResolver() == Entry) {
4140 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4141 return;
4142 }
4143 assert(Entry->isDeclaration());
4144
4145 // If there is a declaration in the module, then we had an extern followed
4146 // by the ifunc, as in:
4147 // extern int test();
4148 // ...
4149 // int test() __attribute__((ifunc("resolver")));
4150 //
4151 // Remove it and replace uses of it with the ifunc.
4152 GIF->takeName(Entry);
4153
4154 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4155 Entry->getType()));
4156 Entry->eraseFromParent();
4157 } else
4158 GIF->setName(MangledName);
4159
Rafael Espindola75c649c2018-03-01 00:06:55 +00004160 SetCommonAttributes(GD, GIF);
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004161}
4162
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00004163llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00004164 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00004165 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00004166 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00004167}
Chris Lattner1eec6602007-08-31 04:31:45 +00004168
David Blaikie2e804282015-04-05 22:47:07 +00004169static llvm::StringMapEntry<llvm::GlobalVariable *> &
4170GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4171 const StringLiteral *Literal, bool TargetIsLSB,
4172 bool &IsUTF16, unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004173 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004174 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00004175
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00004176 // Check for simple case.
4177 if (!Literal->containsNonAsciiOrNull()) {
4178 StringLength = NumBytes;
David Blaikie13156b62014-11-19 03:06:06 +00004179 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00004180 }
4181
Bill Wendling82b87f12012-03-30 00:26:17 +00004182 // Otherwise, convert the UTF8 literals into a string of shorts.
4183 IsUTF16 = true;
4184
Justin Lebar90910552016-09-30 00:38:45 +00004185 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4186 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4187 llvm::UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00004188
Justin Lebar90910552016-09-30 00:38:45 +00004189 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4190 ToPtr + NumBytes, llvm::strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00004191
Daniel Dunbar91ade142009-07-23 23:41:22 +00004192 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00004193 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00004194
Bill Wendling82b87f12012-03-30 00:26:17 +00004195 // Add an explicit null.
4196 *ToPtr = 0;
David Blaikie13156b62014-11-19 03:06:06 +00004197 return *Map.insert(std::make_pair(
4198 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4199 (StringLength + 1) * 2),
4200 nullptr)).first;
Daniel Dunbar64509b22009-07-23 22:52:48 +00004201}
4202
John McCall7f416cc2015-09-08 08:05:57 +00004203ConstantAddress
Daniel Dunbar64509b22009-07-23 22:52:48 +00004204CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4205 unsigned StringLength = 0;
4206 bool isUTF16 = false;
David Blaikie2e804282015-04-05 22:47:07 +00004207 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4208 GetConstantCFStringEntry(CFConstantStringMap, Literal,
4209 getDataLayout().isLittleEndian(), isUTF16,
4210 StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00004211
David Blaikie13156b62014-11-19 03:06:06 +00004212 if (auto *C = Entry.second)
John McCall7f416cc2015-09-08 08:05:57 +00004213 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Mike Stump11289f42009-09-09 15:08:12 +00004214
Chris Lattnerece04092012-02-07 00:39:47 +00004215 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00004216 llvm::Constant *Zeros[] = { Zero, Zero };
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004217
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004218 const ASTContext &Context = getContext();
4219 const llvm::Triple &Triple = getTriple();
4220
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004221 const auto CFRuntime = getLangOpts().CFRuntime;
4222 const bool IsSwiftABI =
4223 static_cast<unsigned>(CFRuntime) >=
4224 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4225 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4226
Chris Lattneraa64ca22009-07-16 16:48:25 +00004227 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00004228 if (!CFConstantStringClassRef) {
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004229 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
Chris Lattner2192fe52011-07-18 04:24:23 +00004230 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00004231 Ty = llvm::ArrayType::get(Ty, 0);
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004232
4233 switch (CFRuntime) {
4234 default: break;
4235 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
Saleem Abdulrasool0c16a132018-10-25 17:52:13 +00004236 case LangOptions::CoreFoundationABI::Swift5_0:
4237 CFConstantStringClassName =
Saleem Abdulrasool98ac9982018-10-26 03:16:16 +00004238 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4239 : "$s10Foundation19_NSCFConstantStringCN";
Saleem Abdulrasool0c16a132018-10-25 17:52:13 +00004240 Ty = IntPtrTy;
4241 break;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004242 case LangOptions::CoreFoundationABI::Swift4_2:
4243 CFConstantStringClassName =
Saleem Abdulrasool98ac9982018-10-26 03:16:16 +00004244 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4245 : "$S10Foundation19_NSCFConstantStringCN";
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004246 Ty = IntPtrTy;
4247 break;
4248 case LangOptions::CoreFoundationABI::Swift4_1:
4249 CFConstantStringClassName =
4250 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4251 : "__T010Foundation19_NSCFConstantStringCN";
4252 Ty = IntPtrTy;
4253 break;
4254 }
4255
4256 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004257
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004258 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
Kristina Brooks34e24d52018-09-25 22:27:40 +00004259 llvm::GlobalValue *GV = nullptr;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004260
Kristina Brooks34e24d52018-09-25 22:27:40 +00004261 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004262 IdentifierInfo &II = Context.Idents.get(GV->getName());
4263 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
Kristina Brooks34e24d52018-09-25 22:27:40 +00004264 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00004265
Kristina Brooks34e24d52018-09-25 22:27:40 +00004266 const VarDecl *VD = nullptr;
4267 for (const auto &Result : DC->lookup(&II))
4268 if ((VD = dyn_cast<VarDecl>(Result)))
4269 break;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004270
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004271 if (Triple.isOSBinFormatELF()) {
Kristina Brooks34e24d52018-09-25 22:27:40 +00004272 if (!VD)
4273 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004274 } else {
4275 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4276 if (!VD || !VD->hasAttr<DLLExportAttr>())
Kristina Brooks34e24d52018-09-25 22:27:40 +00004277 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004278 else
Kristina Brooks34e24d52018-09-25 22:27:40 +00004279 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Kristina Brooks34e24d52018-09-25 22:27:40 +00004280 }
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004281
Kristina Brooks34e24d52018-09-25 22:27:40 +00004282 setDSOLocal(GV);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00004283 }
4284 }
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004285
Daniel Dunbard644ad62008-08-23 18:37:06 +00004286 // Decay array -> ptr
Saleem Abdulrasool4fab7452016-09-11 01:25:15 +00004287 CFConstantStringClassRef =
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004288 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4289 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004290 }
Mike Stump11289f42009-09-09 15:08:12 +00004291
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004292 QualType CFTy = Context.getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00004293
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004294 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00004295
John McCall23c9dc62016-11-28 22:18:27 +00004296 ConstantInitBuilder Builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00004297 auto Fields = Builder.beginStruct(STy);
Douglas Gregor91f84212008-12-11 16:49:14 +00004298
Anders Carlssonb04ea612007-08-21 00:21:21 +00004299 // Class pointer.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004300 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
Mike Stump11289f42009-09-09 15:08:12 +00004301
Anders Carlssonb04ea612007-08-21 00:21:21 +00004302 // Flags.
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004303 if (IsSwiftABI) {
4304 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4305 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4306 } else {
4307 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4308 }
Anders Carlsson157c3212009-08-16 05:55:31 +00004309
Anders Carlssonb04ea612007-08-21 00:21:21 +00004310 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00004311 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00004312 if (isUTF16) {
Craig Topperc005cc02015-09-27 03:44:08 +00004313 auto Arr = llvm::makeArrayRef(
David Blaikie13156b62014-11-19 03:06:06 +00004314 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4315 Entry.first().size() / 2);
Bill Wendling82b87f12012-03-30 00:26:17 +00004316 C = llvm::ConstantDataArray::get(VMContext, Arr);
4317 } else {
David Blaikie13156b62014-11-19 03:06:06 +00004318 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling82b87f12012-03-30 00:26:17 +00004319 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00004320
Bill Wendling86131f22012-01-10 08:46:39 +00004321 // Note: -fwritable-strings doesn't make the backing store strings of
4322 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004323 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00004324 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4325 llvm::GlobalValue::PrivateLinkage, C, ".str");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004326 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigandfa806422013-05-06 16:23:57 +00004327 // Don't enforce the target's minimum global alignment, since the only use
4328 // of the string is via this class initializer.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004329 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4330 : Context.getTypeAlignInChars(Context.CharTy);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004331 GV->setAlignment(Align.getQuantity());
4332
4333 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4334 // Without it LLVM can merge the string with a non unnamed_addr one during
4335 // LTO. Doing that changes the section it ends in, which surprises ld64.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004336 if (Triple.isOSBinFormatMachO())
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004337 GV->setSection(isUTF16 ? "__TEXT,__ustring"
4338 : "__TEXT,__cstring,cstring_literals");
Kristina Brooks34e24d52018-09-25 22:27:40 +00004339 // Make sure the literal ends up in .rodata to allow for safe ICF and for
4340 // the static linker to adjust permissions to read-only later on.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004341 else if (Triple.isOSBinFormatELF())
Kristina Brooks34e24d52018-09-25 22:27:40 +00004342 GV->setSection(".rodata");
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004343
Bill Wendling82b87f12012-03-30 00:26:17 +00004344 // String.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004345 llvm::Constant *Str =
David Blaikied3c127e2015-05-07 17:27:56 +00004346 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00004347
Bill Wendling82b87f12012-03-30 00:26:17 +00004348 if (isUTF16)
4349 // Cast the UTF16 string to the correct type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004350 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4351 Fields.add(Str);
Bill Wendling82b87f12012-03-30 00:26:17 +00004352
Anders Carlssonb04ea612007-08-21 00:21:21 +00004353 // String length.
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004354 llvm::IntegerType *LengthTy =
4355 llvm::IntegerType::get(getModule().getContext(),
4356 Context.getTargetInfo().getLongWidth());
4357 if (IsSwiftABI) {
4358 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4359 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4360 LengthTy = Int32Ty;
4361 else
4362 LengthTy = IntPtrTy;
4363 }
4364 Fields.addInt(LengthTy, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00004365
John McCall7f416cc2015-09-08 08:05:57 +00004366 CharUnits Alignment = getPointerAlign();
4367
Anders Carlssonb04ea612007-08-21 00:21:21 +00004368 // The struct.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004369 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4370 /*isConstant=*/false,
4371 llvm::GlobalVariable::PrivateLinkage);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004372 switch (Triple.getObjectFormat()) {
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004373 case llvm::Triple::UnknownObjectFormat:
4374 llvm_unreachable("unknown file format");
4375 case llvm::Triple::COFF:
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004376 case llvm::Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00004377 case llvm::Triple::Wasm:
Saleem Abdulrasool0295f8c2016-07-09 01:59:51 +00004378 GV->setSection("cfstring");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004379 break;
4380 case llvm::Triple::MachO:
4381 GV->setSection("__DATA,__cfstring");
4382 break;
4383 }
David Blaikie13156b62014-11-19 03:06:06 +00004384 Entry.second = GV;
Mike Stump11289f42009-09-09 15:08:12 +00004385
John McCall7f416cc2015-09-08 08:05:57 +00004386 return ConstantAddress(GV, Alignment);
Anders Carlssonb04ea612007-08-21 00:21:21 +00004387}
Chris Lattnerfb300092007-11-28 05:34:05 +00004388
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +00004389bool CodeGenModule::getExpressionLocationsEnabled() const {
4390 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4391}
4392
Douglas Gregor636e2002011-08-09 17:23:49 +00004393QualType CodeGenModule::getObjCFastEnumerationStateType() {
4394 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004395 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00004396 D->startDefinition();
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004397
Douglas Gregor636e2002011-08-09 17:23:49 +00004398 QualType FieldTypes[] = {
4399 Context.UnsignedLongTy,
4400 Context.getPointerType(Context.getObjCIdType()),
4401 Context.getPointerType(Context.UnsignedLongTy),
4402 Context.getConstantArrayType(Context.UnsignedLongTy,
4403 llvm::APInt(32, 5), ArrayType::Normal, 0)
4404 };
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004405
Douglas Gregor636e2002011-08-09 17:23:49 +00004406 for (size_t i = 0; i < 4; ++i) {
4407 FieldDecl *Field = FieldDecl::Create(Context,
4408 D,
4409 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004410 SourceLocation(), nullptr,
4411 FieldTypes[i], /*TInfo=*/nullptr,
4412 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00004413 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004414 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00004415 Field->setAccess(AS_public);
4416 D->addDecl(Field);
4417 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004418
Douglas Gregor636e2002011-08-09 17:23:49 +00004419 D->completeDefinition();
4420 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4421 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004422
Douglas Gregor636e2002011-08-09 17:23:49 +00004423 return ObjCFastEnumerationStateType;
4424}
4425
Eli Friedmanfcec6302011-11-01 02:23:42 +00004426llvm::Constant *
4427CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4428 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004429
Eli Friedmanfcec6302011-11-01 02:23:42 +00004430 // Don't emit it as the address of the string, emit the string data itself
4431 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00004432 if (E->getCharByteWidth() == 1) {
4433 SmallString<64> Str(E->getString());
4434
4435 // Resize the string to the right size, which is indicated by its type.
4436 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4437 Str.resize(CAT->getSize().getZExtValue());
4438 return llvm::ConstantDataArray::getString(VMContext, Str, false);
4439 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004440
4441 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00004442 llvm::Type *ElemTy = AType->getElementType();
4443 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00004444
4445 // Wide strings have either 2-byte or 4-byte elements.
4446 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4447 SmallVector<uint16_t, 32> Elements;
4448 Elements.reserve(NumElements);
4449
4450 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4451 Elements.push_back(E->getCodeUnit(i));
4452 Elements.resize(NumElements);
4453 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00004454 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004455
Chris Lattner02cb1712012-02-06 22:52:04 +00004456 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4457 SmallVector<uint32_t, 32> Elements;
4458 Elements.reserve(NumElements);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004459
Chris Lattner02cb1712012-02-06 22:52:04 +00004460 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4461 Elements.push_back(E->getCodeUnit(i));
4462 Elements.resize(NumElements);
4463 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00004464}
4465
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004466static llvm::GlobalVariable *
4467GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4468 CodeGenModule &CGM, StringRef GlobalName,
John McCall7f416cc2015-09-08 08:05:57 +00004469 CharUnits Alignment) {
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004470 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4471 CGM.getStringLiteralAddressSpace());
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004472
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004473 llvm::Module &M = CGM.getModule();
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004474 // Create a global variable for this string
4475 auto *GV = new llvm::GlobalVariable(
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004476 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4477 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +00004478 GV->setAlignment(Alignment.getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004479 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004480 if (GV->isWeakForLinker()) {
4481 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4482 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4483 }
Rafael Espindola0d40f122018-03-20 20:42:55 +00004484 CGM.setDSOLocal(GV);
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004485
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004486 return GV;
4487}
4488
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004489/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4490/// constant array for the given string literal.
John McCall7f416cc2015-09-08 08:05:57 +00004491ConstantAddress
Alexey Bataevec474782014-10-09 08:45:04 +00004492CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4493 StringRef Name) {
John McCall7f416cc2015-09-08 08:05:57 +00004494 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
James Molloye735b2b2014-05-09 16:28:56 +00004495
Richard Smith00db2f12014-07-29 21:20:12 +00004496 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4497 llvm::GlobalVariable **Entry = nullptr;
David Majnemer58e5bee2014-03-24 21:43:36 +00004498 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004499 Entry = &ConstantStringMap[C];
4500 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004501 if (Alignment.getQuantity() > GV->getAlignment())
4502 GV->setAlignment(Alignment.getQuantity());
4503 return ConstantAddress(GV, Alignment);
David Majnemer58e5bee2014-03-24 21:43:36 +00004504 }
Eli Friedman49ddc5f2009-11-16 05:55:46 +00004505 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00004506
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004507 SmallString<256> MangledNameBuffer;
4508 StringRef GlobalVariableName;
4509 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00004510
Reid Kleckner7a368962018-09-06 18:25:39 +00004511 // Mangle the string literal if that's how the ABI merges duplicate strings.
4512 // Don't do it if they are writable, since we don't want writes in one TU to
4513 // affect strings in another.
4514 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4515 !LangOpts.WritableStrings) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004516 llvm::raw_svector_ostream Out(MangledNameBuffer);
4517 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004518 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4519 GlobalVariableName = MangledNameBuffer;
4520 } else {
4521 LT = llvm::GlobalValue::PrivateLinkage;
Alexey Bataevec474782014-10-09 08:45:04 +00004522 GlobalVariableName = Name;
David Majnemer58e5bee2014-03-24 21:43:36 +00004523 }
4524
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004525 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4526 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004527 *Entry = GV;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00004528
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00004529 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4530 QualType());
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004531
4532 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4533 Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004534}
4535
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004536/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4537/// array for the given ObjCEncodeExpr node.
John McCall7f416cc2015-09-08 08:05:57 +00004538ConstantAddress
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004539CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4540 std::string Str;
4541 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00004542
4543 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004544}
4545
Alexey Samsonovadc90372014-06-04 20:25:57 +00004546/// GetAddrOfConstantCString - Returns a pointer to a character array containing
4547/// the literal and a terminating '\0' character.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004548/// The result has pointer to array type.
John McCall7f416cc2015-09-08 08:05:57 +00004549ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4550 const std::string &Str, const char *GlobalName) {
Alexey Samsonovadc90372014-06-04 20:25:57 +00004551 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall7f416cc2015-09-08 08:05:57 +00004552 CharUnits Alignment =
4553 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004554
Richard Smith00db2f12014-07-29 21:20:12 +00004555 llvm::Constant *C =
4556 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4557
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004558 // Don't share any string literals if strings aren't constant.
Richard Smith00db2f12014-07-29 21:20:12 +00004559 llvm::GlobalVariable **Entry = nullptr;
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004560 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004561 Entry = &ConstantStringMap[C];
4562 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004563 if (Alignment.getQuantity() > GV->getAlignment())
4564 GV->setAlignment(Alignment.getQuantity());
4565 return ConstantAddress(GV, Alignment);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004566 }
4567 }
4568
Daniel Dunbar08b216a2009-03-31 23:42:16 +00004569 // Get the default prefix if a name wasn't specified.
4570 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00004571 GlobalName = ".str";
Chris Lattnerfb300092007-11-28 05:34:05 +00004572 // Create a global variable for this.
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004573 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4574 GlobalName, Alignment);
4575 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004576 *Entry = GV;
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004577
4578 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4579 Alignment);
Chris Lattnerfb300092007-11-28 05:34:05 +00004580}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004581
John McCall7f416cc2015-09-08 08:05:57 +00004582ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00004583 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00004584 assert((E->getStorageDuration() == SD_Static ||
4585 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004586 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00004587
4588 // If we're not materializing a subobject of the temporary, keep the
4589 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00004590 QualType MaterializedType = Init->getType();
4591 if (Init == E->GetTemporaryExpr())
4592 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004593
John McCall7f416cc2015-09-08 08:05:57 +00004594 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4595
David Majnemer2dcef9e2015-08-13 23:50:15 +00004596 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
John McCall7f416cc2015-09-08 08:05:57 +00004597 return ConstantAddress(Slot, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004598
4599 // FIXME: If an externally-visible declaration extends multiple temporaries,
4600 // we need to give each temporary the same name in every translation unit (and
4601 // we also need to make the temporaries externally-visible).
4602 SmallString<256> Name;
4603 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00004604 getCXXABI().getMangleContext().mangleReferenceTemporary(
4605 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00004606
Craig Topper8a13c412014-05-21 05:09:00 +00004607 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004608 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00004609 // We might have a cached constant initializer for this temporary. Note
4610 // that this might have a different value from the value computed by
4611 // evaluating the initializer if the surrounding constant expression
4612 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00004613 Value = getContext().getMaterializedTemporaryValue(E, false);
4614 if (Value && Value->isUninit())
Craig Topper8a13c412014-05-21 05:09:00 +00004615 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004616 }
4617
Richard Smitha509f2f2013-06-14 03:07:01 +00004618 // Try evaluating it now, it might have a constant initializer.
4619 Expr::EvalResult EvalResult;
4620 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4621 !EvalResult.hasSideEffects())
4622 Value = &EvalResult.Val;
4623
Alexander Richardson6d989432017-10-15 18:48:14 +00004624 LangAS AddrSpace =
John McCallde0fe072017-08-15 21:42:52 +00004625 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4626
4627 Optional<ConstantEmitter> emitter;
Craig Topper8a13c412014-05-21 05:09:00 +00004628 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00004629 bool Constant = false;
4630 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00004631 if (Value) {
4632 // The temporary has a constant initializer, use it.
John McCallde0fe072017-08-15 21:42:52 +00004633 emitter.emplace(*this);
4634 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4635 MaterializedType);
Richard Smitha509f2f2013-06-14 03:07:01 +00004636 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4637 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004638 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00004639 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00004640 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00004641 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00004642 }
4643
4644 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00004645 llvm::GlobalValue::LinkageTypes Linkage =
4646 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004647 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4648 const VarDecl *InitVD;
4649 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4650 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4651 // Temporaries defined inside a class get linkonce_odr linkage because the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004652 // class can be defined in multiple translation units.
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004653 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4654 } else {
4655 // There is no need for this temporary to have external linkage if the
4656 // VarDecl has external linkage.
4657 Linkage = llvm::GlobalVariable::InternalLinkage;
4658 }
4659 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00004660 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004661 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00004662 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
Yaxun Liucbf647c2017-07-08 13:24:52 +00004663 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
John McCallde0fe072017-08-15 21:42:52 +00004664 if (emitter) emitter->finalize(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +00004665 setGVProperties(GV, VD);
John McCall7f416cc2015-09-08 08:05:57 +00004666 GV->setAlignment(Align.getQuantity());
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004667 if (supportsCOMDAT() && GV->isWeakForLinker())
4668 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smithe6c01442013-06-05 00:46:14 +00004669 if (VD->getTLSKind())
4670 setTLSMode(GV, *VD);
Yaxun Liucbf647c2017-07-08 13:24:52 +00004671 llvm::Constant *CV = GV;
4672 if (AddrSpace != LangAS::Default)
4673 CV = getTargetCodeGenInfo().performAddrSpaceCast(
4674 *this, GV, AddrSpace, LangAS::Default,
4675 Type->getPointerTo(
4676 getContext().getTargetAddressSpace(LangAS::Default)));
4677 MaterializedGlobalTemporaryMap[E] = CV;
4678 return ConstantAddress(CV, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004679}
4680
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004681/// EmitObjCPropertyImplementations - Emit information for synthesized
4682/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00004683void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004684 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004685 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004686 // Dynamic is just for type-checking.
4687 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4688 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4689
4690 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00004691 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004692 // we want, that just indicates if the decl came from a
4693 // property. What we want to know is if the method is defined in
4694 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004695 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004696 CodeGenFunction(*this).GenerateObjCGetter(
4697 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004698 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004699 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004700 CodeGenFunction(*this).GenerateObjCSetter(
4701 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004702 }
4703 }
4704}
4705
John McCall6a4fa522011-03-22 07:05:39 +00004706static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004707 const ObjCInterfaceDecl *iface = impl->getClassInterface();
4708 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00004709 ivar; ivar = ivar->getNextIvar())
4710 if (ivar->getType().isDestructedType())
4711 return true;
4712
4713 return false;
4714}
4715
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004716static bool AllTrivialInitializers(CodeGenModule &CGM,
4717 ObjCImplementationDecl *D) {
4718 CodeGenFunction CGF(CGM);
4719 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4720 E = D->init_end(); B != E; ++B) {
4721 CXXCtorInitializer *CtorInitExp = *B;
4722 Expr *Init = CtorInitExp->getInit();
4723 if (!CGF.isTrivialInitializer(Init))
4724 return false;
4725 }
4726 return true;
4727}
4728
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004729/// EmitObjCIvarInitializations - Emit information for ivar initialization
4730/// for an implementation.
4731void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00004732 // We might need a .cxx_destruct even if we don't have any ivar initializers.
4733 if (needsDestructMethod(D)) {
4734 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4735 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4736 ObjCMethodDecl *DTORMethod =
4737 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004738 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004739 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004740 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004741 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00004742 D->addInstanceMethod(DTORMethod);
4743 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00004744 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00004745 }
4746
4747 // If the implementation doesn't have any ivar initializers, we don't need
4748 // a .cxx_construct.
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004749 if (D->getNumIvarInitializers() == 0 ||
4750 AllTrivialInitializers(*this, D))
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004751 return;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004752
John McCall6a4fa522011-03-22 07:05:39 +00004753 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4754 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004755 // The constructor returns 'self'.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004756 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004757 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004758 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004759 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00004760 getContext().getObjCIdType(),
4761 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004762 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004763 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004764 /*isImplicitlyDeclared=*/true,
4765 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004766 ObjCMethodDecl::Required);
4767 D->addInstanceMethod(CTORMethod);
4768 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00004769 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004770}
4771
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004772// EmitLinkageSpec - Emit all declarations in a linkage spec.
4773void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00004774 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4775 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004776 ErrorUnsupported(LSD, "linkage spec");
4777 return;
4778 }
4779
Richard Smith8df390f2016-09-08 23:14:54 +00004780 EmitDeclContext(LSD);
4781}
4782
4783void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4784 for (auto *I : DC->decls()) {
4785 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4786 // are themselves considered "top-level", so EmitTopLevelDecl on an
4787 // ObjCImplDecl does not recursively visit them. We need to do that in
4788 // case they're nested inside another construct (LinkageSpecDecl /
4789 // ExportDecl) that does stop them from being considered "top-level".
Aaron Ballman629afae2014-03-07 19:56:05 +00004790 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004791 for (auto *M : OID->methods())
4792 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004793 }
Richard Smith8df390f2016-09-08 23:14:54 +00004794
Aaron Ballman629afae2014-03-07 19:56:05 +00004795 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004796 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004797}
4798
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004799/// EmitTopLevelDecl - Emit code for a single top level declaration.
4800void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00004801 // Ignore dependent declarations.
Richard Smith32b615c2018-02-01 00:28:36 +00004802 if (D->isTemplated())
Douglas Gregor70d83e22009-06-29 17:30:29 +00004803 return;
Mike Stump11289f42009-09-09 15:08:12 +00004804
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004805 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00004806 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00004807 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004808 case Decl::Function:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004809 EmitGlobal(cast<FunctionDecl>(D));
Alex Lorenzee024992014-08-04 18:41:51 +00004810 // Always provide some coverage mapping
4811 // even for the functions that aren't emitted.
4812 AddDeferredUnusedCoverageMapping(D);
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004813 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004814
Richard Smithada08882017-04-19 21:15:45 +00004815 case Decl::CXXDeductionGuide:
4816 // Function-like, but does not result in code emission.
4817 break;
4818
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004819 case Decl::Var:
Richard Smithbdb84f32016-07-22 23:36:59 +00004820 case Decl::Decomposition:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004821 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004822 EmitGlobal(cast<VarDecl>(D));
Richard Smithda383632016-08-15 01:33:41 +00004823 if (auto *DD = dyn_cast<DecompositionDecl>(D))
4824 for (auto *B : DD->bindings())
4825 if (auto *HD = B->getHoldingVar())
4826 EmitGlobal(HD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004827 break;
4828
John McCall32f44bd2011-04-12 01:01:22 +00004829 // Indirect fields from global anonymous structs and unions can be
4830 // ignored; only the actual variable requires IR gen support.
4831 case Decl::IndirectField:
4832 break;
4833
Anders Carlssonf7475242009-04-15 15:55:24 +00004834 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004835 case Decl::Namespace:
Richard Smith8df390f2016-09-08 23:14:54 +00004836 EmitDeclContext(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004837 break;
Richard Smithe1246122017-11-03 01:26:01 +00004838 case Decl::ClassTemplateSpecialization: {
4839 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4840 if (DebugInfo &&
4841 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4842 Spec->hasDefinition())
4843 DebugInfo->completeTemplateDefinition(*Spec);
4844 } LLVM_FALLTHROUGH;
Richard Smith62f19e72016-06-25 00:15:56 +00004845 case Decl::CXXRecord:
David Blaikie1ac9c982017-04-11 21:13:37 +00004846 if (DebugInfo) {
4847 if (auto *ES = D->getASTContext().getExternalSource())
4848 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4849 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4850 }
Richard Smith62f19e72016-06-25 00:15:56 +00004851 // Emit any static data members, they may be definitions.
4852 for (auto *I : cast<CXXRecordDecl>(D)->decls())
4853 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4854 EmitTopLevelDecl(I);
4855 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00004856 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00004857 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004858 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004859 case Decl::VarTemplate:
4860 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004861 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00004862 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00004863 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00004864 case Decl::Empty:
Richard Smith7c7e5312018-10-26 03:21:20 +00004865 case Decl::Binding:
Douglas Gregorfec52632009-06-20 00:51:54 +00004866 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00004867 case Decl::Using: // using X; [C++]
4868 if (CGDebugInfo *DI = getModuleDebugInfo())
4869 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4870 return;
David Blaikief121b932013-05-20 22:50:41 +00004871 case Decl::NamespaceAlias:
4872 if (CGDebugInfo *DI = getModuleDebugInfo())
4873 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4874 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00004875 case Decl::UsingDirective: // using namespace X; [C++]
4876 if (CGDebugInfo *DI = getModuleDebugInfo())
4877 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4878 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00004879 case Decl::CXXConstructor:
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00004880 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00004881 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004882 case Decl::CXXDestructor:
Reid Klecknere7de47e2013-07-22 13:51:44 +00004883 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004884 break;
Anders Carlsson87835432009-06-11 21:22:55 +00004885
4886 case Decl::StaticAssert:
4887 // Nothing to do.
4888 break;
4889
Anders Carlssonf7475242009-04-15 15:55:24 +00004890 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00004891
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004892 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00004893 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00004894 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00004895 break;
4896
Douglas Gregorf6102672012-01-01 21:23:57 +00004897 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004898 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00004899 if (Proto->isThisDeclarationADefinition())
4900 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004901 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00004902 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004903
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004904 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004905 // Categories have properties but don't support synthesize so we
4906 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00004907 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004908 break;
4909
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004910 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004911 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004912 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004913 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00004914 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00004915 // Emit global variable debug information.
4916 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00004917 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00004918 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4919 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004920 break;
Mike Stump11289f42009-09-09 15:08:12 +00004921 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004922 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004923 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004924 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004925 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004926 CodeGenFunction(*this).GenerateObjCMethod(OMD);
4927 break;
4928 }
Mike Stump11289f42009-09-09 15:08:12 +00004929 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00004930 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004931 break;
4932
Nico Weber66220292016-03-02 17:28:48 +00004933 case Decl::PragmaComment: {
4934 const auto *PCD = cast<PragmaCommentDecl>(D);
4935 switch (PCD->getCommentKind()) {
4936 case PCK_Unknown:
4937 llvm_unreachable("unexpected pragma comment kind");
4938 case PCK_Linker:
4939 AppendLinkerOptions(PCD->getArg());
4940 break;
4941 case PCK_Lib:
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00004942 if (getTarget().getTriple().isOSBinFormatELF() &&
4943 !getTarget().getTriple().isPS4())
4944 AddELFLibDirective(PCD->getArg());
4945 else
4946 AddDependentLib(PCD->getArg());
Nico Weber66220292016-03-02 17:28:48 +00004947 break;
4948 case PCK_Compiler:
4949 case PCK_ExeStr:
4950 case PCK_User:
4951 break; // We ignore all of these.
4952 }
4953 break;
4954 }
4955
Nico Webercbbaeb12016-03-02 19:28:54 +00004956 case Decl::PragmaDetectMismatch: {
4957 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4958 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4959 break;
4960 }
4961
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004962 case Decl::LinkageSpec:
4963 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004964 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004965
4966 case Decl::FileScopeAsm: {
Artem Belevich0488d1e2015-04-27 18:52:00 +00004967 // File-scope asm is ignored during device-side CUDA compilation.
4968 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4969 break;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004970 // File-scope asm is ignored during device-side OpenMP compilation.
4971 if (LangOpts.OpenMPIsDevice)
4972 break;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004973 auto *AD = cast<FileScopeAsmDecl>(D);
Joerg Sonnenbergerdfd511e2015-03-13 00:54:30 +00004974 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004975 break;
4976 }
Mike Stump11289f42009-09-09 15:08:12 +00004977
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004978 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004979 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004980
Richard Smithdc1f0422016-07-20 19:10:16 +00004981 // If we've already imported this module, we're done.
4982 if (!ImportedModules.insert(Import->getImportedModule()))
Richard Smithc52efa72015-08-19 02:30:28 +00004983 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004984
Richard Smithdc1f0422016-07-20 19:10:16 +00004985 // Emit debug information for direct imports.
4986 if (!Import->getImportedOwningModule()) {
4987 if (CGDebugInfo *DI = getModuleDebugInfo())
4988 DI->EmitImportDecl(*Import);
4989 }
4990
Manman Ren3b5dbf22016-10-14 18:55:44 +00004991 // Find all of the submodules and emit the module initializers.
4992 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4993 SmallVector<clang::Module *, 16> Stack;
4994 Visited.insert(Import->getImportedModule());
4995 Stack.push_back(Import->getImportedModule());
4996
4997 while (!Stack.empty()) {
4998 clang::Module *Mod = Stack.pop_back_val();
4999 if (!EmittedModuleInitializers.insert(Mod).second)
5000 continue;
5001
5002 for (auto *D : Context.getModuleInitializers(Mod))
5003 EmitTopLevelDecl(D);
5004
5005 // Visit the submodules of this module.
5006 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5007 SubEnd = Mod->submodule_end();
5008 Sub != SubEnd; ++Sub) {
5009 // Skip explicit children; they need to be explicitly imported to emit
5010 // the initializers.
5011 if ((*Sub)->IsExplicit)
5012 continue;
5013
5014 if (Visited.insert(*Sub).second)
5015 Stack.push_back(*Sub);
5016 }
5017 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005018 break;
David Blaikie0e716b42014-03-03 23:48:23 +00005019 }
5020
Richard Smith8df390f2016-09-08 23:14:54 +00005021 case Decl::Export:
5022 EmitDeclContext(cast<ExportDecl>(D));
5023 break;
5024
Alexey Bataev97720002014-11-11 04:05:39 +00005025 case Decl::OMPThreadPrivate:
5026 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5027 break;
5028
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005029 case Decl::OMPDeclareReduction:
5030 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5031 break;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00005032
Kelvin Li1408f912018-09-26 04:28:39 +00005033 case Decl::OMPRequires:
5034 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5035 break;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005036
Mike Stump11289f42009-09-09 15:08:12 +00005037 default:
Mike Stump18bb9282009-05-16 07:57:57 +00005038 // Make sure we handled everything we should, every other kind is a
5039 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
5040 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005041 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Richard Smitha634ff22014-12-01 18:59:10 +00005042 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005043 }
5044}
John McCall09ae0322010-07-06 23:57:41 +00005045
Alex Lorenzee024992014-08-04 18:41:51 +00005046void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5047 // Do we need to generate coverage mapping?
5048 if (!CodeGenOpts.CoverageMapping)
5049 return;
5050 switch (D->getKind()) {
5051 case Decl::CXXConversion:
5052 case Decl::CXXMethod:
5053 case Decl::Function:
5054 case Decl::ObjCMethod:
5055 case Decl::CXXConstructor:
5056 case Decl::CXXDestructor: {
Justin Bogner203f0922015-07-28 00:41:51 +00005057 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
Alex Lorenzee024992014-08-04 18:41:51 +00005058 return;
Vedant Kumar0acf3432017-09-22 18:23:04 +00005059 SourceManager &SM = getContext().getSourceManager();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005060 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
Vedant Kumar0acf3432017-09-22 18:23:04 +00005061 return;
Alex Lorenzee024992014-08-04 18:41:51 +00005062 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5063 if (I == DeferredEmptyCoverageMappingDecls.end())
5064 DeferredEmptyCoverageMappingDecls[D] = true;
5065 break;
5066 }
5067 default:
5068 break;
5069 };
5070}
5071
5072void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5073 // Do we need to generate coverage mapping?
5074 if (!CodeGenOpts.CoverageMapping)
5075 return;
5076 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5077 if (Fn->isTemplateInstantiation())
5078 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5079 }
5080 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5081 if (I == DeferredEmptyCoverageMappingDecls.end())
5082 DeferredEmptyCoverageMappingDecls[D] = false;
5083 else
5084 I->second = false;
5085}
5086
5087void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
Eli Friedman8516b7f2017-12-19 01:54:09 +00005088 // We call takeVector() here to avoid use-after-free.
5089 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5090 // we deserialize function bodies to emit coverage info for them, and that
5091 // deserializes more declarations. How should we handle that case?
5092 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
Eli Friedmandbcfade2017-12-13 00:14:17 +00005093 if (!Entry.second)
Alex Lorenzee024992014-08-04 18:41:51 +00005094 continue;
Eli Friedmandbcfade2017-12-13 00:14:17 +00005095 const Decl *D = Entry.first;
Alex Lorenzee024992014-08-04 18:41:51 +00005096 switch (D->getKind()) {
5097 case Decl::CXXConversion:
5098 case Decl::CXXMethod:
5099 case Decl::Function:
5100 case Decl::ObjCMethod: {
5101 CodeGenPGO PGO(*this);
5102 GlobalDecl GD(cast<FunctionDecl>(D));
5103 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5104 getFunctionLinkage(GD));
5105 break;
5106 }
5107 case Decl::CXXConstructor: {
5108 CodeGenPGO PGO(*this);
5109 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5110 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5111 getFunctionLinkage(GD));
5112 break;
5113 }
5114 case Decl::CXXDestructor: {
5115 CodeGenPGO PGO(*this);
5116 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5117 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5118 getFunctionLinkage(GD));
5119 break;
5120 }
5121 default:
5122 break;
5123 };
5124 }
5125}
5126
John McCall09ae0322010-07-06 23:57:41 +00005127/// Turns the given pointer into a constant.
5128static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5129 const void *Ptr) {
5130 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00005131 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00005132 return llvm::ConstantInt::get(i64, PtrInt);
5133}
5134
5135static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5136 llvm::NamedMDNode *&GlobalMetadata,
5137 GlobalDecl D,
5138 llvm::GlobalValue *Addr) {
5139 if (!GlobalMetadata)
5140 GlobalMetadata =
5141 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5142
5143 // TODO: should we report variant information for ctors/dtors?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005144 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5145 llvm::ConstantAsMetadata::get(GetPointerConstant(
5146 CGM.getLLVMContext(), D.getDecl()))};
Jay Foadea324f12011-04-21 19:59:12 +00005147 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00005148}
5149
Richard Smithdf931ce2013-04-06 05:00:46 +00005150/// For each function which is declared within an extern "C" region and marked
5151/// as 'used', but has internal linkage, create an alias from the unmangled
5152/// name to the mangled name if possible. People expect to be able to refer
5153/// to such functions with an unmangled name from inline assembly within the
5154/// same translation unit.
5155void CodeGenModule::EmitStaticExternCAliases() {
Yaxun Liub0eee292018-03-29 14:50:00 +00005156 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
Justin Lebarcd2f6bb2016-01-25 22:36:37 +00005157 return;
Yaron Kerenb54db522015-06-11 12:33:25 +00005158 for (auto &I : StaticExternCValues) {
5159 IdentifierInfo *Name = I.first;
5160 llvm::GlobalValue *Val = I.second;
Richard Smith85465e62013-04-06 07:07:44 +00005161 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola27c60b52014-06-03 02:42:01 +00005162 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith85465e62013-04-06 07:07:44 +00005163 }
Richard Smithdf931ce2013-04-06 05:00:46 +00005164}
5165
Alp Tokerfb8d02b2014-06-05 22:10:59 +00005166bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5167 GlobalDecl &Result) const {
5168 auto Res = Manglings.find(MangledName);
5169 if (Res == Manglings.end())
5170 return false;
5171 Result = Res->getValue();
5172 return true;
5173}
5174
John McCall09ae0322010-07-06 23:57:41 +00005175/// Emits metadata nodes associating all the global values in the
5176/// current module with the Decls they came from. This is useful for
5177/// projects using IR gen as a subroutine.
5178///
5179/// Since there's currently no way to associate an MDNode directly
5180/// with an llvm::GlobalValue, we create a global named metadata
5181/// with the name 'clang.global.decl.ptrs'.
5182void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00005183 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00005184
Robert Lytton5b88f78f2014-07-03 09:30:29 +00005185 for (auto &I : MangledDeclNames) {
5186 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
Keno Fischer0e2d4222015-11-05 23:18:44 +00005187 // Some mangled names don't necessarily have an associated GlobalValue
5188 // in this module, e.g. if we mangled it for DebugInfo.
5189 if (Addr)
5190 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall09ae0322010-07-06 23:57:41 +00005191 }
5192}
5193
5194/// Emits metadata nodes for all the local variables in the current
5195/// function.
5196void CodeGenFunction::EmitDeclMetadata() {
5197 if (LocalDeclMap.empty()) return;
5198
5199 llvm::LLVMContext &Context = getLLVMContext();
5200
5201 // Find the unique metadata ID for this name.
5202 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5203
Craig Topper8a13c412014-05-21 05:09:00 +00005204 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00005205
Robert Lytton5b88f78f2014-07-03 09:30:29 +00005206 for (auto &I : LocalDeclMap) {
5207 const Decl *D = I.first;
John McCall7f416cc2015-09-08 08:05:57 +00005208 llvm::Value *Addr = I.second.getPointer();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005209 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00005210 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005211 Alloca->setMetadata(
5212 DeclPtrKind, llvm::MDNode::get(
5213 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005214 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00005215 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5216 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5217 }
5218 }
5219}
Daniel Dunbar900546d2010-07-16 00:00:15 +00005220
Rafael Espindola3bfa4682013-10-16 19:28:50 +00005221void CodeGenModule::EmitVersionIdentMetadata() {
5222 llvm::NamedMDNode *IdentMetadata =
5223 TheModule.getOrInsertNamedMetadata("llvm.ident");
5224 std::string Version = getClangFullVersion();
5225 llvm::LLVMContext &Ctx = TheModule.getContext();
5226
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005227 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola3bfa4682013-10-16 19:28:50 +00005228 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5229}
5230
Scott Linderde6beb02018-12-14 15:38:15 +00005231void CodeGenModule::EmitCommandLineMetadata() {
5232 llvm::NamedMDNode *CommandLineMetadata =
5233 TheModule.getOrInsertNamedMetadata("llvm.commandline");
5234 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
5235 llvm::LLVMContext &Ctx = TheModule.getContext();
5236
5237 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5238 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5239}
5240
Robert Lytton57765d52014-07-03 09:30:33 +00005241void CodeGenModule::EmitTargetMetadata() {
Richard Smith1ba0a072014-08-01 20:39:36 +00005242 // Warning, new MangledDeclNames may be appended within this loop.
5243 // We rely on MapVector insertions adding new elements to the end
5244 // of the container.
5245 // FIXME: Move this loop into the one target that needs it, and only
5246 // loop over those declarations for which we couldn't emit the target
5247 // metadata when we emitted the declaration.
5248 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
Richard Smith570706d2014-08-01 22:17:28 +00005249 auto Val = *(MangledDeclNames.begin() + I);
Richard Smith1ba0a072014-08-01 20:39:36 +00005250 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
5251 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Robert Lytton57765d52014-07-03 09:30:33 +00005252 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
5253 }
5254}
5255
Nick Lewycky85c011d2011-05-05 00:08:20 +00005256void CodeGenModule::EmitCoverageFile() {
Nick Lewycky97e49ac2016-08-31 23:04:32 +00005257 if (getCodeGenOpts().CoverageDataFile.empty() &&
5258 getCodeGenOpts().CoverageNotesFile.empty())
5259 return;
5260
5261 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5262 if (!CUNode)
5263 return;
5264
5265 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5266 llvm::LLVMContext &Ctx = TheModule.getContext();
5267 auto *CoverageDataFile =
5268 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5269 auto *CoverageNotesFile =
5270 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5271 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5272 llvm::MDNode *CU = CUNode->getOperand(i);
5273 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5274 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky480cb992011-05-04 20:46:58 +00005275 }
5276}
Nico Webercf4ff5862012-10-11 10:13:44 +00005277
Nico Weber17d3a2c2014-09-08 16:26:36 +00005278llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Webercf4ff5862012-10-11 10:13:44 +00005279 // Sema has checked that all uuid strings are of the form
5280 // "12345678-1234-1234-1234-1234567890ab".
5281 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00005282 for (unsigned i = 0; i < 36; ++i) {
5283 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5284 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00005285 }
Nico Webercf4ff5862012-10-11 10:13:44 +00005286
Nico Weberdfa274e2014-09-08 16:11:15 +00005287 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemerbbecd092013-08-15 19:59:14 +00005288 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00005289
David Majnemerbbecd092013-08-15 19:59:14 +00005290 llvm::Constant *Field3[8];
5291 for (unsigned Idx = 0; Idx < 8; ++Idx)
5292 Field3[Idx] = llvm::ConstantInt::get(
5293 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5294
5295 llvm::Constant *Fields[4] = {
5296 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
5297 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
5298 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5299 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5300 };
5301
5302 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00005303}
David Majnemere2cb8d12014-07-07 06:20:47 +00005304
5305llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5306 bool ForEH) {
5307 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5308 // FIXME: should we even be calling this method if RTTI is disabled
5309 // and it's not for EH?
Yaxun Liu6328f9a2018-06-05 15:11:02 +00005310 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
David Majnemere2cb8d12014-07-07 06:20:47 +00005311 return llvm::Constant::getNullValue(Int8PtrTy);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00005312
David Majnemere2cb8d12014-07-07 06:20:47 +00005313 if (ForEH && Ty->isObjCObjectPointerType() &&
5314 LangOpts.ObjCRuntime.isGNUFamily())
5315 return ObjCRuntime->GetEHType(Ty);
5316
David Majnemer443250f2015-03-17 20:35:00 +00005317 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
David Majnemere2cb8d12014-07-07 06:20:47 +00005318}
5319
Alexey Bataev97720002014-11-11 04:05:39 +00005320void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005321 // Do not emit threadprivates in simd-only mode.
5322 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5323 return;
Alexey Bataev97720002014-11-11 04:05:39 +00005324 for (auto RefExpr : D->varlists()) {
5325 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5326 bool PerformInit =
5327 VD->getAnyInitializer() &&
5328 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5329 /*ForRef=*/false);
John McCall7f416cc2015-09-08 08:05:57 +00005330
5331 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
Alexey Bataev3eff5f42015-02-25 08:32:46 +00005332 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005333 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
Alexey Bataev97720002014-11-11 04:05:39 +00005334 CXXGlobalInits.push_back(InitFunction);
5335 }
5336}
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005337
Peter Collingbournee44acad2018-06-26 02:15:47 +00005338llvm::Metadata *
5339CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5340 StringRef Suffix) {
5341 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00005342 if (InternalId)
5343 return InternalId;
5344
5345 if (isExternallyVisible(T->getLinkage())) {
5346 std::string OutName;
5347 llvm::raw_string_ostream Out(OutName);
5348 getCXXABI().getMangleContext().mangleTypeName(T, Out);
Peter Collingbournee44acad2018-06-26 02:15:47 +00005349 Out << Suffix;
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00005350
5351 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5352 } else {
5353 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5354 llvm::ArrayRef<llvm::Metadata *>());
5355 }
5356
5357 return InternalId;
5358}
5359
Peter Collingbournee44acad2018-06-26 02:15:47 +00005360llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5361 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5362}
5363
5364llvm::Metadata *
5365CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5366 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5367}
5368
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005369// Generalize pointer types to a void pointer with the qualifiers of the
5370// originally pointed-to type, e.g. 'const char *' and 'char * const *'
5371// generalize to 'const void *' while 'char *' and 'const char **' generalize to
5372// 'void *'.
5373static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5374 if (!Ty->isPointerType())
5375 return Ty;
5376
5377 return Ctx.getPointerType(
5378 QualType(Ctx.VoidTy).withCVRQualifiers(
5379 Ty->getPointeeType().getCVRQualifiers()));
5380}
5381
5382// Apply type generalization to a FunctionType's return and argument types
5383static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5384 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5385 SmallVector<QualType, 8> GeneralizedParams;
5386 for (auto &Param : FnType->param_types())
5387 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5388
5389 return Ctx.getFunctionType(
5390 GeneralizeType(Ctx, FnType->getReturnType()),
5391 GeneralizedParams, FnType->getExtProtoInfo());
5392 }
5393
5394 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5395 return Ctx.getFunctionNoProtoType(
5396 GeneralizeType(Ctx, FnType->getReturnType()));
5397
5398 llvm_unreachable("Encountered unknown FunctionType");
5399}
5400
5401llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
Peter Collingbournee44acad2018-06-26 02:15:47 +00005402 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5403 GeneralizedMetadataIdMap, ".generalized");
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005404}
5405
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005406/// Returns whether this module needs the "all-vtables" type identifier.
5407bool CodeGenModule::NeedAllVtablesTypeId() const {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005408 // Returns true if at least one of vtable-based CFI checkers is enabled and
5409 // is not in the trapping mode.
5410 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5411 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5412 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5413 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5414 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5415 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5416 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5417 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5418}
5419
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005420void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5421 CharUnits Offset,
5422 const CXXRecordDecl *RD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005423 llvm::Metadata *MD =
5424 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005425 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005426
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005427 if (CodeGenOpts.SanitizeCfiCrossDso)
5428 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5429 VTable->addTypeMetadata(Offset.getQuantity(),
5430 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005431
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005432 if (NeedAllVtablesTypeId()) {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005433 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005434 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005435 }
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005436}
Eric Christopher2b90a642015-11-11 23:05:08 +00005437
Gabor Buella1a83d062018-06-07 08:48:36 +00005438TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5439 assert(TD != nullptr);
5440 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5441
5442 ParsedAttr.Features.erase(
5443 llvm::remove_if(ParsedAttr.Features,
5444 [&](const std::string &Feat) {
5445 return !Target.isValidFeatureName(
5446 StringRef{Feat}.substr(1));
5447 }),
5448 ParsedAttr.Features.end());
5449 return ParsedAttr;
5450}
5451
5452
Eric Christopher2b90a642015-11-11 23:05:08 +00005453// Fills in the supplied string map with the set of target features for the
5454// passed in function.
5455void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
Erich Keanede6480a32018-11-13 15:48:08 +00005456 GlobalDecl GD) {
Eric Christopher2b90a642015-11-11 23:05:08 +00005457 StringRef TargetCPU = Target.getTargetOpts().CPU;
Erich Keanede6480a32018-11-13 15:48:08 +00005458 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
Eric Christopher2b90a642015-11-11 23:05:08 +00005459 if (const auto *TD = FD->getAttr<TargetAttr>()) {
Gabor Buella1a83d062018-06-07 08:48:36 +00005460 TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
Erich Keanecf8807c2017-10-27 18:32:23 +00005461
Eric Christopher2b90a642015-11-11 23:05:08 +00005462 // Make a copy of the features as passed on the command line into the
5463 // beginning of the additional features from the function to override.
Erich Keaneb0d44232017-07-18 20:41:02 +00005464 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
Eric Christopher2b90a642015-11-11 23:05:08 +00005465 Target.getTargetOpts().FeaturesAsWritten.begin(),
5466 Target.getTargetOpts().FeaturesAsWritten.end());
5467
Erich Keanecf8807c2017-10-27 18:32:23 +00005468 if (ParsedAttr.Architecture != "" &&
5469 Target.isValidCPUName(ParsedAttr.Architecture))
5470 TargetCPU = ParsedAttr.Architecture;
Eric Christopher2b90a642015-11-11 23:05:08 +00005471
5472 // Now populate the feature map, first with the TargetCPU which is either
5473 // the default or a new one from the target attribute string. Then we'll use
5474 // the passed in features (FeaturesAsWritten) along with the new ones from
5475 // the attribute.
Erich Keaneb0d44232017-07-18 20:41:02 +00005476 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5477 ParsedAttr.Features);
Erich Keane3efe0022018-07-20 14:13:28 +00005478 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
5479 llvm::SmallVector<StringRef, 32> FeaturesTmp;
Erich Keanede6480a32018-11-13 15:48:08 +00005480 Target.getCPUSpecificCPUDispatchFeatures(
5481 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
Erich Keane3efe0022018-07-20 14:13:28 +00005482 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5483 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
Eric Christopher2b90a642015-11-11 23:05:08 +00005484 } else {
5485 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5486 Target.getTargetOpts().Features);
5487 }
5488}
Peter Collingbournedc134532016-01-16 00:31:22 +00005489
5490llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5491 if (!SanStats)
5492 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5493
5494 return *SanStats;
5495}
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005496llvm::Value *
5497CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5498 CodeGenFunction &CGF) {
John McCallde0fe072017-08-15 21:42:52 +00005499 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00005500 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005501 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5502 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5503 "__translate_sampler_initializer"),
5504 {C});
5505}