blob: ae511ae4fe405f0d6144aa80e39cbe2e68276b26 [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"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCall.h"
18#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000019#include "CGObjCRuntime.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000020#include "CGOpenCLRuntime.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "CodeGenFunction.h"
Justin Bogneref512b92014-01-06 22:27:43 +000023#include "CodeGenPGO.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000024#include "CodeGenTBAA.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000025#include "CoverageMappingGen.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000026#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000027#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000028#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000029#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000031#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000032#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000033#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000034#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000035#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000036#include "clang/Basic/CharInfo.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000037#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000038#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000039#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000040#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000041#include "clang/Basic/Version.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindola208b5c02013-10-22 19:26:13 +000043#include "clang/Sema/SemaDiagnostic.h"
Sebastian Redl4a7eab22012-02-25 20:51:20 +000044#include "llvm/ADT/APSInt.h"
John McCallbeec5a02010-03-06 00:35:14 +000045#include "llvm/ADT/Triple.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000046#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000047#include "llvm/IR/CallingConv.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/Intrinsics.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Module.h"
Justin Bogner837a6f62014-04-18 21:52:00 +000052#include "llvm/ProfileData/InstrProfReader.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000053#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000054#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000055
Chris Lattnerbed31442007-05-28 01:07:47 +000056using namespace clang;
57using namespace CodeGen;
58
Julien Lerouge5a6b6982011-09-09 22:41:49 +000059static const char AnnotationSection[] = "llvm.metadata";
60
Alp Toker82862252013-12-28 21:58:40 +000061static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000062 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000063 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000064 case TargetCXXABI::GenericARM:
65 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000066 case TargetCXXABI::iOS64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000067 case TargetCXXABI::GenericMIPS:
John McCall57625922013-01-25 23:36:14 +000068 case TargetCXXABI::GenericItanium:
Alp Toker82862252013-12-28 21:58:40 +000069 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000070 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000071 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000072 }
73
74 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000075}
76
Chandler Carruthbc55fe22009-11-12 17:24:48 +000077CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall568d4102013-04-16 22:48:20 +000078 llvm::Module &M, const llvm::DataLayout &TD,
Alex Lorenzee024992014-08-04 18:41:51 +000079 DiagnosticsEngine &diags,
80 CoverageSourceInfo *CoverageInfo)
Alexey Samsonovd6e043b2013-08-12 11:48:05 +000081 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
82 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
Craig Topper8a13c412014-05-21 05:09:00 +000083 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr),
84 TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this),
85 ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr),
86 CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr),
87 NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
88 CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
89 NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
90 NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
91 BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
92 GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
Alexey Samsonov0b15e342014-10-15 22:17:27 +000093 LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietzf54319c2013-01-18 11:30:38 +000094
Chris Lattnerece04092012-02-07 00:39:47 +000095 // Initialize the type cache.
96 llvm::LLVMContext &LLVMContext = M.getContext();
97 VoidTy = llvm::Type::getVoidTy(LLVMContext);
98 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
99 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
100 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
101 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
102 FloatTy = llvm::Type::getFloatTy(LLVMContext);
103 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
104 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
105 PointerAlignInBytes =
106 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
107 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
108 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
109 Int8PtrTy = Int8Ty->getPointerTo(0);
110 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
111
John McCall882987f2013-02-28 19:01:20 +0000112 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
Anton Korobeynikovd90dd792014-12-02 16:04:58 +0000113 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
John McCall882987f2013-02-28 19:01:20 +0000114
David Blaikiebbafb8a2012-03-11 07:00:24 +0000115 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000116 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000117 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000118 createOpenCLRuntime();
Alexey Bataev9959db52014-05-06 10:08:46 +0000119 if (LangOpts.OpenMP)
120 createOpenMPRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000121 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000122 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000123
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000124 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000125 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000126 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
127 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Alp Toker82862252013-12-28 21:58:40 +0000128 getCXXABI().getMangleContext());
Dan Gohman947c9af2010-10-14 23:06:10 +0000129
Nick Lewycky207bce32011-04-21 23:44:07 +0000130 // If debug info or coverage generation is enabled, create the CGDebugInfo
131 // object.
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000132 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000133 CodeGenOpts.EmitGcovArcs ||
Nick Lewycky207bce32011-04-21 23:44:07 +0000134 CodeGenOpts.EmitGcovNotes)
135 DebugInfo = new CGDebugInfo(*this);
John McCallad7c5c12011-02-08 08:22:06 +0000136
137 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000138
David Blaikiebbafb8a2012-03-11 07:00:24 +0000139 if (C.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +0000140 ARCData = new ARCEntrypoints();
141 RRData = new RREntrypoints();
Justin Bogneref512b92014-01-06 22:27:43 +0000142
Justin Bogner837a6f62014-04-18 21:52:00 +0000143 if (!CodeGenOpts.InstrProfileInput.empty()) {
Justin Bognerd29a4a32015-02-16 21:29:05 +0000144 auto ReaderOrErr =
145 llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput);
146 if (std::error_code EC = ReaderOrErr.getError()) {
Justin Bogner837a6f62014-04-18 21:52:00 +0000147 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
148 "Could not read profile: %0");
149 getDiags().Report(DiagID) << EC.message();
150 }
Justin Bognerd29a4a32015-02-16 21:29:05 +0000151 PGOReader = std::move(ReaderOrErr.get());
Justin Bogner837a6f62014-04-18 21:52:00 +0000152 }
Alex Lorenzee024992014-08-04 18:41:51 +0000153
154 // If coverage mapping generation is enabled, create the
155 // CoverageMappingModuleGen object.
156 if (CodeGenOpts.CoverageMapping)
157 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattnera087ff92008-03-01 08:45:05 +0000158}
159
160CodeGenModule::~CodeGenModule() {
Peter Collingbournee1d20992011-07-27 20:29:46 +0000161 delete ObjCRuntime;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000162 delete OpenCLRuntime;
Alexey Bataev9959db52014-05-06 10:08:46 +0000163 delete OpenMPRuntime;
Peter Collingbournefe883422011-10-06 18:29:37 +0000164 delete CUDARuntime;
Ted Kremenekc168e502011-10-08 05:28:26 +0000165 delete TheTargetCodeGenInfo;
Dan Gohmand19ee8a2010-10-15 18:04:46 +0000166 delete TBAA;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000167 delete DebugInfo;
John McCall31168b02011-06-15 23:02:42 +0000168 delete ARCData;
169 delete RRData;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000170}
171
David Chisnall481e3a82010-01-23 02:40:42 +0000172void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000173 // This is just isGNUFamily(), but we want to force implementors of
174 // new ABIs to decide how best to do this.
175 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000176 case ObjCRuntime::GNUstep:
177 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000178 case ObjCRuntime::ObjFW:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000179 ObjCRuntime = CreateGNUObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000180 return;
181
182 case ObjCRuntime::FragileMacOSX:
183 case ObjCRuntime::MacOSX:
184 case ObjCRuntime::iOS:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000185 ObjCRuntime = CreateMacObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000186 return;
187 }
188 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000189}
190
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000191void CodeGenModule::createOpenCLRuntime() {
192 OpenCLRuntime = new CGOpenCLRuntime(*this);
193}
194
Alexey Bataev9959db52014-05-06 10:08:46 +0000195void CodeGenModule::createOpenMPRuntime() {
196 OpenMPRuntime = new CGOpenMPRuntime(*this);
197}
198
Peter Collingbournefe883422011-10-06 18:29:37 +0000199void CodeGenModule::createCUDARuntime() {
200 CUDARuntime = CreateNVCUDARuntime(*this);
201}
202
Rafael Espindola1e4df922014-09-16 15:18:21 +0000203void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
204 Replacements[Name] = C;
205}
206
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000207void CodeGenModule::applyReplacements() {
208 for (ReplacementsTy::iterator I = Replacements.begin(),
209 E = Replacements.end();
210 I != E; ++I) {
211 StringRef MangledName = I->first();
212 llvm::Constant *Replacement = I->second;
213 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
214 if (!Entry)
215 continue;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000216 auto *OldF = cast<llvm::Function>(Entry);
217 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000218 if (!NewF) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000219 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
Rafael Espindola0fcad882014-05-16 22:20:18 +0000220 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Reid Klecknerb78257d2014-02-03 18:54:51 +0000221 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000222 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Reid Klecknerb78257d2014-02-03 18:54:51 +0000223 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
224 CE->getOpcode() == llvm::Instruction::GetElementPtr);
225 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
226 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000227 }
228
229 // Replace old with new, but keep the old order.
230 OldF->replaceAllUsesWith(Replacement);
231 if (NewF) {
232 NewF->removeFromParent();
233 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
234 }
235 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000236 }
237}
238
Rafael Espindola27c60b52014-06-03 02:42:01 +0000239// This is only used in aliases that we created and we know they have a
240// linear structure.
241static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
242 llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
243 const llvm::Constant *C = &GA;
244 for (;;) {
Rafael Espindolae11f40a2014-06-04 19:03:20 +0000245 C = C->stripPointerCasts();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000246 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
247 return GO;
248 // stripPointerCasts will not walk over weak aliases.
249 auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
250 if (!GA2)
251 return nullptr;
David Blaikie82e95a32014-11-19 07:49:47 +0000252 if (!Visited.insert(GA2).second)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000253 return nullptr;
254 C = GA2->getAliasee();
255 }
256}
257
Rafael Espindola208b5c02013-10-22 19:26:13 +0000258void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000259 // Check if the constructed aliases are well formed. It is really unfortunate
260 // that we have to do this in CodeGen, but we only construct mangled names
261 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000262 bool Error = false;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000263 DiagnosticsEngine &Diags = getDiags();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000264 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
265 E = Aliases.end(); I != E; ++I) {
266 const GlobalDecl &GD = *I;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000267 const auto *D = cast<ValueDecl>(GD.getDecl());
Rafael Espindola208b5c02013-10-22 19:26:13 +0000268 const AliasAttr *AA = D->getAttr<AliasAttr>();
269 StringRef MangledName = getMangledName(GD);
270 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000271 auto *Alias = cast<llvm::GlobalAlias>(Entry);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000272 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
273 if (!GV) {
274 Error = true;
275 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
276 } else if (GV->isDeclaration()) {
Rafael Espindola93c7a652014-03-13 15:47:50 +0000277 Error = true;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000278 Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000279 }
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000280
Rafael Espindola27c60b52014-06-03 02:42:01 +0000281 llvm::Constant *Aliasee = Alias->getAliasee();
282 llvm::GlobalValue *AliaseeGV;
283 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
284 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
285 else
286 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
287
Rafael Espindola502f65a2014-05-05 20:21:03 +0000288 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
289 StringRef AliasSection = SA->getName();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000290 if (AliasSection != AliaseeGV->getSection())
Rafael Espindola502f65a2014-05-05 20:21:03 +0000291 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
292 << AliasSection;
293 }
Rafael Espindola27c60b52014-06-03 02:42:01 +0000294
295 // We have to handle alias to weak aliases in here. LLVM itself disallows
296 // this since the object semantics would not match the IL one. For
297 // compatibility with gcc we implement it by just pointing the alias
298 // to its aliasee's aliasee. We also warn, since the user is probably
299 // expecting the link to be weak.
300 if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
301 if (GA->mayBeOverridden()) {
302 Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
303 << GV->getName() << GA->getName();
304 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
305 GA->getAliasee(), Alias->getType());
306 Alias->setAliasee(Aliasee);
307 }
308 }
Rafael Espindola208b5c02013-10-22 19:26:13 +0000309 }
310 if (!Error)
311 return;
312
313 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
314 E = Aliases.end(); I != E; ++I) {
315 const GlobalDecl &GD = *I;
316 StringRef MangledName = getMangledName(GD);
317 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000318 auto *Alias = cast<llvm::GlobalAlias>(Entry);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000319 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
320 Alias->eraseFromParent();
321 }
322}
323
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000324void CodeGenModule::clear() {
325 DeferredDeclsToEmit.clear();
Alexey Bataev91797552015-03-18 04:13:55 +0000326 if (OpenMPRuntime)
327 OpenMPRuntime->clear();
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000328}
329
Justin Bogner40b8ba12014-06-26 01:45:07 +0000330void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
331 StringRef MainFile) {
332 if (!hasDiagnostics())
333 return;
334 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
335 if (MainFile.empty())
336 MainFile = "<stdin>";
337 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
338 } else
339 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
340 << Mismatched;
341}
342
Ted Kremenek2c674f62008-08-05 18:50:11 +0000343void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000344 EmitDeferred();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000345 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000346 checkAliases();
Eli Friedman5866fe32010-01-08 00:50:11 +0000347 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000348 EmitCXXGlobalDtorFunc();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000349 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000350 if (ObjCRuntime)
351 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000352 AddGlobalCtor(ObjCInitFunction);
Justin Bogner40b8ba12014-06-26 01:45:07 +0000353 if (PGOReader && PGOStats.hasDiagnostics())
354 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000355 EmitCtorList(GlobalCtors, "llvm.global_ctors");
356 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000357 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000358 EmitStaticExternCAliases();
Alex Lorenzee024992014-08-04 18:41:51 +0000359 EmitDeferredUnusedCoverageMappings();
360 if (CoverageMapping)
361 CoverageMapping->emit();
Rafael Espindola060062a2014-03-06 22:15:10 +0000362 emitLLVMUsed();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000363
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000364 if (CodeGenOpts.Autolink &&
365 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000366 EmitModuleLinkOptions();
367 }
Manman Ren9691f7f2013-06-19 01:46:49 +0000368 if (CodeGenOpts.DwarfVersion)
369 // We actually want the latest version when there are conflicts.
370 // We can change from Warning to Latest if such mode is supported.
371 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
372 CodeGenOpts.DwarfVersion);
Manman Ren4b7f23d2013-11-22 19:42:45 +0000373 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000374 // We support a single version in the linked module. The LLVM
375 // parser will drop debug info with a different version number
376 // (and warn about it, too).
377 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000378 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000379
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000380 // We need to record the widths of enums and wchar_t, so that we can generate
381 // the correct build attributes in the ARM backend.
Justin Bogner9bb7f152014-06-23 20:03:28 +0000382 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000383 if ( Arch == llvm::Triple::arm
384 || Arch == llvm::Triple::armeb
385 || Arch == llvm::Triple::thumb
386 || Arch == llvm::Triple::thumbeb) {
387 // Width of wchar_t in bytes
388 uint64_t WCharWidth =
389 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
390 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
391
392 // The minimum width of an enum in bytes
393 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
394 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
395 }
396
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000397 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
398 llvm::PICLevel::Level PL = llvm::PICLevel::Default;
399 switch (PLevel) {
400 case 0: break;
401 case 1: PL = llvm::PICLevel::Small; break;
402 case 2: PL = llvm::PICLevel::Large; break;
403 default: llvm_unreachable("Invalid PIC Level");
404 }
405
406 getModule().setPICLevel(PL);
407 }
408
John McCall0bdb1fd2010-09-16 06:16:50 +0000409 SimplifyPersonality();
410
John McCall09ae0322010-07-06 23:57:41 +0000411 if (getCodeGenOpts().EmitDeclMetadata)
412 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000413
414 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000415 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000416
417 if (DebugInfo)
418 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000419
420 EmitVersionIdentMetadata();
Robert Lytton57765d52014-07-03 09:30:33 +0000421
422 EmitTargetMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000423}
424
Devang Patel945b8ae2011-03-23 16:29:39 +0000425void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
426 // Make sure that this type is translated.
427 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000428}
429
Dan Gohman947c9af2010-10-14 23:06:10 +0000430llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
431 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000432 return nullptr;
Dan Gohman947c9af2010-10-14 23:06:10 +0000433 return TBAA->getTBAAInfo(QTy);
434}
435
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000436llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
437 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000438 return nullptr;
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000439 return TBAA->getTBAAInfoForVTablePtr();
440}
441
Dan Gohman22695fc2012-09-28 21:58:29 +0000442llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
443 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000444 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000445 return TBAA->getTBAAStructInfo(QTy);
446}
447
Manman Renc451e572013-04-04 21:53:22 +0000448llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
449 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000450 return nullptr;
Manman Renc451e572013-04-04 21:53:22 +0000451 return TBAA->getTBAAStructTypeInfo(QTy);
452}
453
454llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
455 llvm::MDNode *AccessN,
456 uint64_t O) {
457 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000458 return nullptr;
Manman Renc451e572013-04-04 21:53:22 +0000459 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
460}
461
Manman Ren4f755de2013-10-08 00:08:49 +0000462/// Decorate the instruction with a TBAA tag. For both scalar TBAA
463/// and struct-path aware TBAA, the tag has the same format:
464/// base type, access type and offset.
Manman Rene1ad74e2013-04-11 23:02:56 +0000465/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
Dan Gohman947c9af2010-10-14 23:06:10 +0000466void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
Manman Rene1ad74e2013-04-11 23:02:56 +0000467 llvm::MDNode *TBAAInfo,
468 bool ConvertTypeToTag) {
Manman Ren4f755de2013-10-08 00:08:49 +0000469 if (ConvertTypeToTag && TBAA)
Manman Rene1ad74e2013-04-11 23:02:56 +0000470 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
471 TBAA->getTBAAScalarTagInfo(TBAAInfo));
472 else
473 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
Dan Gohman947c9af2010-10-14 23:06:10 +0000474}
475
Alp Toker29cb66b2014-01-26 06:17:37 +0000476void CodeGenModule::Error(SourceLocation loc, StringRef message) {
477 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
478 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000479}
480
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000481/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000482/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000483void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000484 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000485 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000486 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000487 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
488 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000489}
Chris Lattner41af8182007-12-02 06:27:33 +0000490
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000491/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000492/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000493void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000494 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000495 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000496 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000497 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000498}
499
John McCall23c29fe2011-06-24 21:55:10 +0000500llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
501 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
502}
503
Mike Stump11289f42009-09-09 15:08:12 +0000504void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000505 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000506 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000507 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000508 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000509 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000510 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000511
John McCallc273f242010-10-30 11:50:40 +0000512 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000513 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000514 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
515 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000516}
517
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000518static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
519 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
520 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
521 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
522 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
523 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
524}
525
526static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
527 CodeGenOptions::TLSModel M) {
528 switch (M) {
529 case CodeGenOptions::GeneralDynamicTLSModel:
530 return llvm::GlobalVariable::GeneralDynamicTLSModel;
531 case CodeGenOptions::LocalDynamicTLSModel:
532 return llvm::GlobalVariable::LocalDynamicTLSModel;
533 case CodeGenOptions::InitialExecTLSModel:
534 return llvm::GlobalVariable::InitialExecTLSModel;
535 case CodeGenOptions::LocalExecTLSModel:
536 return llvm::GlobalVariable::LocalExecTLSModel;
537 }
538 llvm_unreachable("Invalid TLS model!");
539}
540
David Majnemerbb525f7c2014-10-15 22:38:23 +0000541void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000542 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000543
David Majnemerbb525f7c2014-10-15 22:38:23 +0000544 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000545 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000546
547 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000548 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000549 TLM = GetLLVMTLSModel(Attr->getModel());
550 }
551
552 GV->setThreadLocalMode(TLM);
553}
554
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000555StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000556 StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
557 if (!FoundStr.empty())
558 return FoundStr;
559
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000560 const auto *ND = cast<NamedDecl>(GD.getDecl());
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000561 SmallString<256> Buffer;
562 StringRef Str;
563 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
564 llvm::raw_svector_ostream Out(Buffer);
565 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
566 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
567 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
568 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
569 else
570 getCXXABI().getMangleContext().mangleName(ND, Out);
571 Str = Out.str();
572 } else {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000573 IdentifierInfo *II = ND->getIdentifier();
574 assert(II && "Attempt to mangle unnamed decl.");
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000575 Str = II->getName();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000576 }
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000577
Richard Smith6d0e97a2014-08-02 00:50:16 +0000578 // Keep the first result in the case of a mangling collision.
579 auto Result = Manglings.insert(std::make_pair(Str, GD));
580 return FoundStr = Result.first->first();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000581}
582
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000583StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
584 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000585 MangleContext &MangleCtx = getCXXABI().getMangleContext();
586 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +0000587
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000588 SmallString<256> Buffer;
589 llvm::raw_svector_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +0000590 if (!D)
Fariborz Jahanian63628032012-06-26 16:06:38 +0000591 MangleCtx.mangleGlobalBlock(BD,
592 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000593 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000594 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000595 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000596 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000597 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000598 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +0000599
Richard Smith6d0e97a2014-08-02 00:50:16 +0000600 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
601 return Result.first->first();
Anders Carlsson635186a2010-06-09 02:36:32 +0000602}
603
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000604llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +0000605 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000606}
607
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000608/// AddGlobalCtor - Add a function to the list that will be called before
609/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000610void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
611 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000612 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000613 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000614}
615
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000616/// AddGlobalDtor - Add a function to the list that will be called
617/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000618void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000619 // FIXME: Type coercion of void()* types.
Craig Topper4b566922014-06-09 02:04:02 +0000620 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000621}
622
623void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
624 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +0000625 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000626 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000627
Reid Kleckner563f0e82014-05-23 21:13:45 +0000628 // Get the type of a ctor entry, { i32, void ()*, i8* }.
629 llvm::StructType *CtorStructTy = llvm::StructType::get(
Reid Kleckneree7cf842014-12-01 22:02:27 +0000630 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000631
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000632 // Construct the constructor and destructor arrays.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000633 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000634 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner3def9ae2012-02-06 22:16:34 +0000635 llvm::Constant *S[] = {
Reid Kleckner563f0e82014-05-23 21:13:45 +0000636 llvm::ConstantInt::get(Int32Ty, I->Priority, false),
637 llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy),
638 (I->AssociatedData
639 ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy)
640 : llvm::Constant::getNullValue(VoidPtrTy))
Chris Lattner3def9ae2012-02-06 22:16:34 +0000641 };
Owen Anderson0e0189d2009-07-27 22:29:56 +0000642 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000643 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000644
645 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000646 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000647 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000648 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000649 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000650 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000651 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000652}
653
John McCalld4324142010-02-19 01:32:20 +0000654llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000655CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000656 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +0000657
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000658 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000659
Hans Wennborg275efb92014-05-28 01:52:23 +0000660 if (isa<CXXDestructorDecl>(D) &&
Reid Klecknera12cd282013-12-11 19:21:27 +0000661 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
Hans Wennborg275efb92014-05-28 01:52:23 +0000662 GD.getDtorType())) {
663 // Destructor variants in the Microsoft C++ ABI are always internal or
664 // linkonce_odr thunks emitted on an as-needed basis.
665 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
666 : llvm::GlobalValue::LinkOnceODRLinkage;
667 }
Reid Klecknera12cd282013-12-11 19:21:27 +0000668
Hans Wennborg275efb92014-05-28 01:52:23 +0000669 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +0000670}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000671
Rafael Espindolae033c8c2014-05-08 15:26:12 +0000672void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
673 llvm::Function *F) {
674 setNonAliasAttributes(D, F);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000675}
676
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000677void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000678 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000679 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000680 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000681 AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +0000682 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
Bill Wendling3087d022012-12-07 23:17:26 +0000683 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000684 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000685}
686
John McCall9b0a7ce2011-10-02 01:16:38 +0000687/// Determines whether the language options require us to model
688/// unwind exceptions. We treat -fexceptions as mandating this
689/// except under the fragile ObjC ABI with only ObjC exceptions
690/// enabled. This means, for example, that C with -fexceptions
691/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000692static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +0000693 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000694 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +0000695
696 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000697 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +0000698
699 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000700 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +0000701 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +0000702 }
703
704 return true;
705}
706
Daniel Dunbar38932572009-04-14 08:05:55 +0000707void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
708 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000709 llvm::AttrBuilder B;
710
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000711 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000712 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000713
David Blaikiebbafb8a2012-03-11 07:00:24 +0000714 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000715 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000716
Eli Friedmanc55efe42011-08-22 23:55:33 +0000717 if (D->hasAttr<NakedAttr>()) {
718 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000719 B.addAttribute(llvm::Attribute::Naked);
720 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +0000721 } else if (D->hasAttr<NoDuplicateAttr>()) {
722 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000723 } else if (D->hasAttr<NoInlineAttr>()) {
724 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +0000725 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000726 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
727 llvm::Attribute::NoInline)) {
728 // (noinline wins over always_inline, and we can't specify both in IR)
729 B.addAttribute(llvm::Attribute::AlwaysInline);
Eli Friedmanc55efe42011-08-22 23:55:33 +0000730 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000731
Diego Novillo5f2b1ce2013-05-24 20:18:15 +0000732 if (D->hasAttr<ColdAttr>()) {
Paul Robinson08556952014-12-11 20:14:04 +0000733 if (!D->hasAttr<OptimizeNoneAttr>())
734 B.addAttribute(llvm::Attribute::OptimizeForSize);
Diego Novillo5f2b1ce2013-05-24 20:18:15 +0000735 B.addAttribute(llvm::Attribute::Cold);
736 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +0000737
Quentin Colombet4e172062012-11-01 23:55:47 +0000738 if (D->hasAttr<MinSizeAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000739 B.addAttribute(llvm::Attribute::MinSize);
Richard Smithb555a762012-09-28 22:46:07 +0000740
David Blaikiebbafb8a2012-03-11 07:00:24 +0000741 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000742 B.addAttribute(llvm::Attribute::StackProtect);
Josh Mageee0fc1a82014-02-11 01:35:14 +0000743 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
744 B.addAttribute(llvm::Attribute::StackProtectStrong);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000745 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000746 B.addAttribute(llvm::Attribute::StackProtectReq);
Will Dietzf54319c2013-01-18 11:30:38 +0000747
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000748 // Add sanitizer attributes if function is not blacklisted.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000749 if (!isInSanitizerBlacklist(F, D->getLocation())) {
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000750 // When AddressSanitizer is enabled, set SanitizeAddress attribute
751 // unless __attribute__((no_sanitize_address)) is used.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000752 if (LangOpts.Sanitize.has(SanitizerKind::Address) &&
753 !D->hasAttr<NoSanitizeAddressAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000754 B.addAttribute(llvm::Attribute::SanitizeAddress);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000755 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000756 if (LangOpts.Sanitize.has(SanitizerKind::Thread) &&
757 !D->hasAttr<NoSanitizeThreadAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000758 B.addAttribute(llvm::Attribute::SanitizeThread);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000759 // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000760 if (LangOpts.Sanitize.has(SanitizerKind::Memory) &&
761 !D->hasAttr<NoSanitizeMemoryAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000762 B.addAttribute(llvm::Attribute::SanitizeMemory);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000763 }
Alexander Potapenkoef41fd32012-02-02 11:49:28 +0000764
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000765 F->addAttributes(llvm::AttributeSet::FunctionIndex,
766 llvm::AttributeSet::get(
767 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
768
Paul Robinson4ece6822014-11-24 20:51:42 +0000769 if (D->hasAttr<OptimizeNoneAttr>()) {
770 // OptimizeNone implies noinline; we should not be inlining such functions.
771 F->addFnAttr(llvm::Attribute::OptimizeNone);
772 F->addFnAttr(llvm::Attribute::NoInline);
773
774 // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
Paul Robinson08556952014-12-11 20:14:04 +0000775 assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) &&
776 "OptimizeNone and OptimizeForSize on same function!");
Paul Robinson30e41fb2014-12-15 18:57:28 +0000777 assert(!F->hasFnAttribute(llvm::Attribute::MinSize) &&
778 "OptimizeNone and MinSize on same function!");
779 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
780 "OptimizeNone and AlwaysInline on same function!");
Paul Robinson4ece6822014-11-24 20:51:42 +0000781
782 // Attribute 'inlinehint' has no effect on 'optnone' functions.
783 // Explicitly remove it from the set of function attributes.
784 F->removeFnAttr(llvm::Attribute::InlineHint);
785 }
786
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000787 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
788 F->setUnnamedAddr(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000789 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000790 if (MD->isVirtual())
791 F->setUnnamedAddr(true);
792
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000793 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
794 if (alignment)
795 F->setAlignment(alignment);
796
Mike Stump3472ae52009-10-05 22:49:20 +0000797 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000798 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
799 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000800}
801
Mike Stump11289f42009-09-09 15:08:12 +0000802void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000803 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000804 if (const auto *ND = dyn_cast<NamedDecl>(D))
Anders Carlsson072ef742011-01-29 19:41:00 +0000805 setGlobalVisibility(GV, ND);
John McCall457a04e2010-10-22 21:05:15 +0000806 else
807 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +0000808
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000809 if (D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000810 addUsedGlobal(GV);
Rafael Espindola502f65a2014-05-05 20:21:03 +0000811}
812
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +0000813void CodeGenModule::setAliasAttributes(const Decl *D,
814 llvm::GlobalValue *GV) {
815 SetCommonAttributes(D, GV);
816
817 // Process the dllexport attribute based on whether the original definition
818 // (not necessarily the aliasee) was exported.
819 if (D->hasAttr<DLLExportAttr>())
820 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
821}
822
Rafael Espindola502f65a2014-05-05 20:21:03 +0000823void CodeGenModule::setNonAliasAttributes(const Decl *D,
Rafael Espindolaee076a22014-05-13 18:45:53 +0000824 llvm::GlobalObject *GO) {
825 SetCommonAttributes(D, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +0000826
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000827 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Rafael Espindolaee076a22014-05-13 18:45:53 +0000828 GO->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000829
Rafael Espindolaee076a22014-05-13 18:45:53 +0000830 getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000831}
832
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000833void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
834 llvm::Function *F,
835 const CGFunctionInfo &FI) {
836 SetLLVMFunctionAttributes(D, FI, F);
837 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000838
839 F->setLinkage(llvm::Function::InternalLinkage);
840
Rafael Espindola502f65a2014-05-05 20:21:03 +0000841 setNonAliasAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000842}
843
David Majnemerf6acb762014-04-25 17:07:16 +0000844static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
845 const NamedDecl *ND) {
846 // Set linkage and visibility in case we never see a definition.
847 LinkageInfo LV = ND->getLinkageAndVisibility();
848 if (LV.getLinkage() != ExternalLinkage) {
849 // Don't set internal linkage on declarations.
850 } else {
851 if (ND->hasAttr<DLLImportAttr>()) {
852 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
853 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
854 } else if (ND->hasAttr<DLLExportAttr>()) {
855 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
856 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
857 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
858 // "extern_weak" is overloaded in LLVM; we probably should have
859 // separate linkage types for this.
860 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
861 }
862
863 // Set visibility on a declaration only if it's explicit.
864 if (LV.isVisibilityExplicit())
865 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
866 }
867}
868
David Majnemerb9bd6fb2014-11-01 05:42:23 +0000869void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
870 bool IsIncompleteFunction,
871 bool IsThunk) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000872 if (unsigned IID = F->getIntrinsicID()) {
873 // If this is an intrinsic function, set the function's attributes
874 // to the intrinsic's attributes.
Bill Wendling311c8322012-10-15 04:47:45 +0000875 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
876 (llvm::Intrinsic::ID)IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000877 return;
878 }
879
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000880 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +0000881
Eli Friedman895771a2009-05-26 01:22:57 +0000882 if (!IsIncompleteFunction)
John McCalla729c622012-02-17 03:33:10 +0000883 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000884
Bob Wilsonfc6297f2014-04-01 01:38:16 +0000885 // Add the Returned attribute for "this", except for iOS 5 and earlier
886 // where substantial code, including the libstdc++ dylib, was compiled with
887 // GCC and does not actually return "this".
David Majnemerb9bd6fb2014-11-01 05:42:23 +0000888 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Bob Wilsonfc6297f2014-04-01 01:38:16 +0000889 !(getTarget().getTriple().isiOS() &&
890 getTarget().getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000891 assert(!F->arg_empty() &&
892 F->arg_begin()->getType()
893 ->canLosslesslyBitCastTo(F->getReturnType()) &&
894 "unexpected this return");
895 F->addAttribute(1, llvm::Attribute::Returned);
896 }
897
Daniel Dunbar38932572009-04-14 08:05:55 +0000898 // Only a few attributes are set on declarations; these may later be
899 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000900
David Majnemerf6acb762014-04-25 17:07:16 +0000901 setLinkageAndVisibilityForGV(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +0000902
Hans Wennborg275efb92014-05-28 01:52:23 +0000903 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
904 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
905 // Don't dllexport/import destructor thunks.
906 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
907 }
908 }
909
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000910 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000911 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +0000912
913 // A replaceable global allocation function does not act like a builtin by
914 // default, only if it is invoked by a new-expression or delete-expression.
915 if (FD->isReplaceableGlobalAllocationFunction())
916 F->addAttribute(llvm::AttributeSet::FunctionIndex,
917 llvm::Attribute::NoBuiltin);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000918}
919
Rafael Espindola060062a2014-03-06 22:15:10 +0000920void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000921 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000922 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000923 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000924}
925
Rafael Espindola060062a2014-03-06 22:15:10 +0000926void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
927 assert(!GV->isDeclaration() &&
928 "Only globals with definition can force usage.");
929 LLVMCompilerUsed.push_back(GV);
930}
931
932static void emitUsed(CodeGenModule &CGM, StringRef Name,
933 std::vector<llvm::WeakVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000934 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +0000935 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000936 return;
937
Rafael Espindola060062a2014-03-06 22:15:10 +0000938 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000939 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +0000940 UsedArray.resize(List.size());
941 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000942 UsedArray[i] =
Justin Holewinskif37f3d32015-02-02 21:05:49 +0000943 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
944 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000945 }
Mike Stump11289f42009-09-09 15:08:12 +0000946
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000947 if (UsedArray.empty())
948 return;
Rafael Espindola060062a2014-03-06 22:15:10 +0000949 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000950
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000951 auto *GV = new llvm::GlobalVariable(
952 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
953 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000954
955 GV->setSection("llvm.metadata");
956}
957
Rafael Espindola060062a2014-03-06 22:15:10 +0000958void CodeGenModule::emitLLVMUsed() {
959 emitUsed(*this, "llvm.used", LLVMUsed);
960 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
961}
962
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000963void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000964 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000965 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
966}
967
Aaron Ballman5d041be2013-06-04 02:07:14 +0000968void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
969 llvm::SmallString<32> Opt;
970 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000971 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballman5d041be2013-06-04 02:07:14 +0000972 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
973}
974
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000975void CodeGenModule::AddDependentLib(StringRef Lib) {
976 llvm::SmallString<24> Opt;
977 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000978 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000979 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
980}
981
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000982/// \brief Add link options implied by the given module, including modules
983/// it depends on, using a postorder walk.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000984static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
985 SmallVectorImpl<llvm::Metadata *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000986 llvm::SmallPtrSet<Module *, 16> &Visited) {
987 // Import this module's parent.
David Blaikie82e95a32014-11-19 07:49:47 +0000988 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000989 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000990 }
991
992 // Import this module's dependencies.
993 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
David Blaikie82e95a32014-11-19 07:49:47 +0000994 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000995 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000996 }
997
998 // Add linker options to link against the libraries/frameworks
999 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001000 llvm::LLVMContext &Context = CGM.getLLVMContext();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001001 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001002 // Link against a framework. Frameworks are currently Darwin only, so we
1003 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001004 if (Mod->LinkLibraries[I-1].IsFramework) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001005 llvm::Metadata *Args[2] = {
1006 llvm::MDString::get(Context, "-framework"),
1007 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001008
1009 Metadata.push_back(llvm::MDNode::get(Context, Args));
1010 continue;
1011 }
1012
1013 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001014 llvm::SmallString<24> Opt;
1015 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1016 Mod->LinkLibraries[I-1].Library, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001017 auto *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001018 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1019 }
1020}
1021
1022void CodeGenModule::EmitModuleLinkOptions() {
1023 // Collect the set of all of the modules we want to visit to emit link
1024 // options, which is essentially the imported modules and all of their
1025 // non-explicit child modules.
1026 llvm::SetVector<clang::Module *> LinkModules;
1027 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1028 SmallVector<clang::Module *, 16> Stack;
1029
1030 // Seed the stack with imported modules.
1031 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
1032 MEnd = ImportedModules.end();
1033 M != MEnd; ++M) {
David Blaikie82e95a32014-11-19 07:49:47 +00001034 if (Visited.insert(*M).second)
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001035 Stack.push_back(*M);
1036 }
1037
1038 // Find all of the modules to import, making a little effort to prune
1039 // non-leaf modules.
1040 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001041 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001042
1043 bool AnyChildren = false;
1044
1045 // Visit the submodules of this module.
1046 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1047 SubEnd = Mod->submodule_end();
1048 Sub != SubEnd; ++Sub) {
1049 // Skip explicit children; they need to be explicitly imported to be
1050 // linked against.
1051 if ((*Sub)->IsExplicit)
1052 continue;
1053
David Blaikie82e95a32014-11-19 07:49:47 +00001054 if (Visited.insert(*Sub).second) {
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001055 Stack.push_back(*Sub);
1056 AnyChildren = true;
1057 }
1058 }
1059
1060 // We didn't find any children, so add this module to the list of
1061 // modules to link against.
1062 if (!AnyChildren) {
1063 LinkModules.insert(Mod);
1064 }
1065 }
1066
1067 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001068 // order. We don't do anything to try to order import link flags with respect
1069 // to linker options inserted by things like #pragma comment().
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001070 SmallVector<llvm::Metadata *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001071 Visited.clear();
1072 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
1073 MEnd = LinkModules.end();
1074 M != MEnd; ++M) {
David Blaikie82e95a32014-11-19 07:49:47 +00001075 if (Visited.insert(*M).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001076 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001077 }
Daniel Dunbar69e47462013-01-17 01:35:06 +00001078 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001079 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001080
Daniel Dunbar69e47462013-01-17 01:35:06 +00001081 // Add the linker options metadata flag.
1082 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001083 llvm::MDNode::get(getLLVMContext(),
1084 LinkerOptionsMetadata));
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001085}
1086
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001087void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +00001088 // Emit code for any potentially referenced deferred decls. Since a
1089 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001090 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001091
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001092 if (!DeferredVTables.empty()) {
1093 EmitDeferredVTables();
John McCall6bd2a892013-01-25 22:31:03 +00001094
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001095 // Emitting a v-table doesn't directly cause more v-tables to
1096 // become deferred, although it can cause functions to be
1097 // emitted that then need those v-tables.
1098 assert(DeferredVTables.empty());
1099 }
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001100
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001101 // Stop if we're out of both deferred v-tables and deferred declarations.
1102 if (DeferredDeclsToEmit.empty())
1103 return;
John McCall6bd2a892013-01-25 22:31:03 +00001104
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001105 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1106 // work, it will not interfere with this.
1107 std::vector<DeferredGlobal> CurDeclsToEmit;
1108 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1109
1110 for (DeferredGlobal &G : CurDeclsToEmit) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001111 GlobalDecl D = G.GD;
1112 llvm::GlobalValue *GV = G.GV;
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001113 G.GV = nullptr;
Chris Lattner45470942009-03-21 09:44:56 +00001114
Hans Wennborg43a0f992015-01-10 01:19:48 +00001115 assert(!GV || GV == GetGlobalValue(getMangledName(D)));
1116 if (!GV)
1117 GV = GetGlobalValue(getMangledName(D));
1118
John McCallc2af9392010-05-27 01:45:30 +00001119 // Check to see if we've already emitted this. This is necessary
1120 // for a couple of reasons: first, decls can end up in the
1121 // deferred-decls queue multiple times, and second, decls can end
1122 // up with definitions in unusual ways (e.g. by an extern inline
1123 // function acquiring a strong function redefinition). Just
1124 // ignore these cases.
Hans Wennborg43a0f992015-01-10 01:19:48 +00001125 if (GV && !GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001126 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001127
Chris Lattner45470942009-03-21 09:44:56 +00001128 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001129 EmitGlobalDefinition(D, GV);
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001130
1131 // If we found out that we need to emit more decls, do that recursively.
1132 // This has the advantage that the decls are emitted in a DFS and related
1133 // ones are close together, which is convenient for testing.
1134 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1135 EmitDeferred();
1136 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1137 }
Chris Lattner45470942009-03-21 09:44:56 +00001138 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001139}
Chris Lattner09153c02007-06-22 18:48:09 +00001140
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001141void CodeGenModule::EmitGlobalAnnotations() {
1142 if (Annotations.empty())
1143 return;
1144
1145 // Create a new global variable for the ConstantStruct in the Module.
1146 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1147 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001148 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1149 llvm::GlobalValue::AppendingLinkage,
1150 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001151 gv->setSection(AnnotationSection);
1152}
1153
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001154llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001155 llvm::Constant *&AStr = AnnotationStrings[Str];
1156 if (AStr)
1157 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001158
1159 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001160 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001161 auto *gv =
1162 new llvm::GlobalVariable(getModule(), s->getType(), true,
1163 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001164 gv->setSection(AnnotationSection);
1165 gv->setUnnamedAddr(true);
Benjamin Kramereed80612013-11-10 16:55:11 +00001166 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001167 return gv;
1168}
1169
1170llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1171 SourceManager &SM = getContext().getSourceManager();
1172 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1173 if (PLoc.isValid())
1174 return EmitAnnotationString(PLoc.getFilename());
1175 return EmitAnnotationString(SM.getBufferName(Loc));
1176}
1177
1178llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1179 SourceManager &SM = getContext().getSourceManager();
1180 PresumedLoc PLoc = SM.getPresumedLoc(L);
1181 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1182 SM.getExpansionLineNumber(L);
1183 return llvm::ConstantInt::get(Int32Ty, LineNo);
1184}
1185
Mike Stump11289f42009-09-09 15:08:12 +00001186llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001187 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001188 SourceLocation L) {
1189 // Get the globals for file name, annotation, and the line number.
1190 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1191 *UnitGV = EmitAnnotationUnit(L),
1192 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001193
Daniel Dunbar346892a2009-04-14 22:41:13 +00001194 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001195 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001196 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1197 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1198 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1199 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001200 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001201 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001202}
1203
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001204void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1205 llvm::GlobalValue *GV) {
1206 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1207 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001208 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1209 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001210}
1211
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001212bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1213 SourceLocation Loc) const {
1214 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1215 // Blacklist by function name.
1216 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1217 return true;
1218 // Blacklist by location.
1219 if (!Loc.isInvalid())
1220 return SanitizerBL.isBlacklistedLocation(Loc);
1221 // If location is unknown, this may be a compiler-generated function. Assume
1222 // it's located in the main file.
1223 auto &SM = Context.getSourceManager();
1224 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1225 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1226 }
1227 return false;
1228}
1229
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001230bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1231 SourceLocation Loc, QualType Ty,
1232 StringRef Category) const {
1233 // For now globals can be blacklisted only in ASan.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001234 if (!LangOpts.Sanitize.has(SanitizerKind::Address))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001235 return false;
1236 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1237 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1238 return true;
1239 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1240 return true;
1241 // Check global type.
1242 if (!Ty.isNull()) {
1243 // Drill down the array types: if global variable of a fixed type is
1244 // blacklisted, we also don't instrument arrays of them.
1245 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1246 Ty = AT->getElementType();
1247 Ty = Ty.getCanonicalType().getUnqualifiedType();
1248 // We allow to blacklist only record types (classes, structs etc.)
1249 if (Ty->isRecordType()) {
1250 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1251 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1252 return true;
1253 }
1254 }
1255 return false;
1256}
1257
Hans Wennborg43a0f992015-01-10 01:19:48 +00001258bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001259 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001260 if (LangOpts.EmitAllDecls)
Hans Wennborg43a0f992015-01-10 01:19:48 +00001261 return true;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001262
Hans Wennborg43a0f992015-01-10 01:19:48 +00001263 return getContext().DeclMustBeEmitted(Global);
1264}
1265
1266bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1267 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1268 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1269 // Implicit template instantiations may change linkage if they are later
1270 // explicitly instantiated, so they should not be emitted eagerly.
1271 return false;
1272
1273 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001274}
1275
Nico Webercf4ff5862012-10-11 10:13:44 +00001276llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1277 const CXXUuidofExpr* E) {
1278 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1279 // well-formed.
David Majnemer8eaab6f2013-08-13 06:32:20 +00001280 StringRef Uuid = E->getUuidAsStringRef(Context);
David Majnemercf963ce2013-08-09 08:35:59 +00001281 std::string Name = "_GUID_" + Uuid.lower();
1282 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00001283
1284 // Look for an existing global.
1285 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1286 return GV;
1287
Nico Weber17d3a2c2014-09-08 16:26:36 +00001288 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Webercf4ff5862012-10-11 10:13:44 +00001289 assert(Init && "failed to initialize as constant");
1290
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001291 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00001292 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00001293 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
David Majnemer740d59e2015-01-21 01:04:28 +00001294 if (supportsCOMDAT())
1295 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Nico Webercf4ff5862012-10-11 10:13:44 +00001296 return GV;
1297}
1298
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001299llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1300 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1301 assert(AA && "No alias?");
1302
Chris Lattner2192fe52011-07-18 04:24:23 +00001303 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001304
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001305 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00001306 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001307 if (Entry) {
1308 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1309 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1310 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001311
1312 llvm::Constant *Aliasee;
1313 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00001314 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1315 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00001316 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001317 else
John McCall7ec50432010-03-19 23:29:14 +00001318 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00001319 llvm::PointerType::getUnqual(DeclTy),
1320 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001321
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001322 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001323 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1324 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001325
1326 return Aliasee;
1327}
1328
Chris Lattnere0be0df2009-05-12 21:21:08 +00001329void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001330 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001331
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001332 // Weak references don't produce any output by themselves.
1333 if (Global->hasAttr<WeakRefAttr>())
1334 return;
1335
Chris Lattner54041692009-03-22 21:47:11 +00001336 // If this is an alias definition (which otherwise looks like a declaration)
1337 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001338 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00001339 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001340
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001341 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001342 if (LangOpts.CUDA) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00001343 if (LangOpts.CUDAIsDevice) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001344 if (!Global->hasAttr<CUDADeviceAttr>() &&
1345 !Global->hasAttr<CUDAGlobalAttr>() &&
1346 !Global->hasAttr<CUDAConstantAttr>() &&
1347 !Global->hasAttr<CUDASharedAttr>())
1348 return;
1349 } else {
1350 if (!Global->hasAttr<CUDAHostAttr>() && (
1351 Global->hasAttr<CUDADeviceAttr>() ||
1352 Global->hasAttr<CUDAConstantAttr>() ||
1353 Global->hasAttr<CUDASharedAttr>()))
1354 return;
1355 }
1356 }
1357
Chris Lattner45470942009-03-21 09:44:56 +00001358 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001359 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001360 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001361 if (!FD->doesThisDeclarationHaveABody()) {
1362 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1363 return;
1364
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001365 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00001366
1367 // Compute the function info and LLVM type.
1368 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1369 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1370
1371 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1372 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001373 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001374 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001375 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001376 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001377 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1378
Hans Wennborg56fc62b2014-07-17 20:25:23 +00001379 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1380 !Context.isMSStaticDataMemberInlineDefinition(VD))
Douglas Gregorbeecd582009-04-21 17:11:58 +00001381 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +00001382 }
1383
Hans Wennborg43a0f992015-01-10 01:19:48 +00001384 // Defer code generation to first use when possible, e.g. if this is an inline
1385 // function. If the global must always be emitted, do it eagerly if possible
1386 // to benefit from cache locality.
1387 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001388 // Emit the definition if it can't be deferred.
1389 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001390 return;
1391 }
John McCall70013b62010-07-15 23:40:35 +00001392
1393 // If we're deferring emission of a C++ variable with an
1394 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001395 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00001396 cast<VarDecl>(Global)->hasInit()) {
1397 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00001398 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00001399 }
Hans Wennborg43a0f992015-01-10 01:19:48 +00001400
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001401 StringRef MangledName = getMangledName(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001402 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1403 // The value has already been used and should therefore be emitted.
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001404 addDeferredDeclToEmit(GV, GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001405 } else if (MustBeEmitted(Global)) {
1406 // The value must be emitted, but cannot be emitted eagerly.
1407 assert(!MayBeEmittedEagerly(Global));
1408 addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1409 } else {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001410 // Otherwise, remember that we saw a deferred decl with this name. The
1411 // first use of the mangled name will cause it to move into
1412 // DeferredDeclsToEmit.
1413 DeferredDecls[MangledName] = GD;
1414 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00001415}
1416
Rafael Espindolac5941352011-10-26 20:41:06 +00001417namespace {
1418 struct FunctionIsDirectlyRecursive :
1419 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1420 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001421 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00001422 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001423 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1424 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001425 }
1426 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1427
1428 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001429 const FunctionDecl *FD = E->getDirectCallee();
1430 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00001431 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001432 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1433 if (Attr && Name == Attr->getLabel()) {
1434 Result = true;
1435 return false;
1436 }
1437 unsigned BuiltinID = FD->getBuiltinID();
1438 if (!BuiltinID)
Rafael Espindolac5941352011-10-26 20:41:06 +00001439 return true;
Nick Lewycky9ed5b152012-01-18 03:41:19 +00001440 StringRef BuiltinName = BI.GetName(BuiltinID);
1441 if (BuiltinName.startswith("__builtin_") &&
1442 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001443 Result = true;
1444 return false;
1445 }
1446 return true;
1447 }
1448 };
1449}
1450
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001451// isTriviallyRecursive - Check if this function calls another
1452// decl that, because of the asm attribute or the other decl being a builtin,
1453// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00001454bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001455CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1456 StringRef Name;
1457 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00001458 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001459 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1460 if (!Attr)
1461 return false;
1462 Name = Attr->getLabel();
1463 } else {
1464 Name = FD->getName();
1465 }
Rafael Espindolac5941352011-10-26 20:41:06 +00001466
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001467 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1468 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00001469 return Walker.Result;
1470}
1471
1472bool
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001473CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1474 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00001475 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001476 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00001477 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00001478 return false;
1479 // PR9614. Avoid cases where the source code is lying to us. An available
1480 // externally function should have an equivalent function somewhere else,
1481 // but a function that calls itself is clearly not equivalent to the real
1482 // implementation.
1483 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001484 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00001485}
1486
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001487/// If the type for the method's class was generated by
1488/// CGDebugInfo::createContextChain(), the cache contains only a
1489/// limited DIType without any declarations. Since EmitFunctionStart()
1490/// needs to find the canonical declaration for each method, we need
1491/// to construct the complete type prior to emitting the method.
1492void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1493 if (!D->isInstance())
1494 return;
1495
1496 if (CGDebugInfo *DI = getModuleDebugInfo())
1497 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001498 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001499 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1500 }
1501}
1502
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001503void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001504 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001505
Dan Gohman145f3f12010-04-19 16:39:44 +00001506 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00001507 Context.getSourceManager(),
1508 "Generating code for declaration");
1509
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001510 if (isa<FunctionDecl>(D)) {
Douglas Gregora700f682010-07-13 06:02:28 +00001511 // At -O0, don't generate IR for functions with available_externally
1512 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001513 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00001514 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00001515
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001516 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001517 CompleteDIClassType(Method);
Eli Friedman49a94b12011-05-06 17:27:27 +00001518 // Make sure to emit the definition(s) before we emit the thunks.
1519 // This is necessary for the generation of certain thunks.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001520 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00001521 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001522 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00001523 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Eli Friedman49a94b12011-05-06 17:27:27 +00001524 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001525 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00001526
Douglas Gregora700f682010-07-13 06:02:28 +00001527 if (Method->isVirtual())
1528 getVTables().EmitThunks(GD);
1529
Eli Friedman49a94b12011-05-06 17:27:27 +00001530 return;
Douglas Gregora700f682010-07-13 06:02:28 +00001531 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001532
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001533 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00001534 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001535
1536 if (const auto *VD = dyn_cast<VarDecl>(D))
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001537 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001538
David Blaikie83d382b2011-09-23 05:06:16 +00001539 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00001540}
1541
Chris Lattnerd4808922009-03-22 21:03:39 +00001542/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1543/// module, create and return an llvm Function with the specified type. If there
1544/// is something in the module with the specified name, return it potentially
1545/// bitcasted to the right type.
1546///
1547/// If D is non-null, it specifies a decl that correspond to this. This is used
1548/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001549llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001550CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001551 llvm::Type *Ty,
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001552 GlobalDecl GD, bool ForVTable,
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001553 bool DontDefer, bool IsThunk,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001554 llvm::AttributeSet ExtraAttrs) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001555 const Decl *D = GD.getDecl();
1556
Chris Lattnera85d68e2009-03-21 09:25:43 +00001557 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001558 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001559 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001560 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001561 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001562 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001563 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001564 }
1565
Hans Wennborg0a20f542014-08-29 00:16:06 +00001566 // Handle dropped DLL attributes.
1567 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1568 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1569
Chris Lattnera85d68e2009-03-21 09:25:43 +00001570 if (Entry->getType()->getElementType() == Ty)
1571 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001572
Chris Lattnera85d68e2009-03-21 09:25:43 +00001573 // Make sure the result is of the correct type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001574 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00001575 }
Mike Stump11289f42009-09-09 15:08:12 +00001576
Eli Friedmancc522d92009-11-09 05:07:37 +00001577 // This function doesn't have a complete type (for example, the return
1578 // type is an incomplete struct). Use a fake type instead, and make
1579 // sure not to try to set attributes.
1580 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00001581
Chris Lattner2192fe52011-07-18 04:24:23 +00001582 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00001583 if (isa<llvm::FunctionType>(Ty)) {
1584 FTy = cast<llvm::FunctionType>(Ty);
1585 } else {
John McCall9dc0db22011-05-15 01:53:33 +00001586 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00001587 IsIncompleteFunction = true;
1588 }
Chris Lattner5c740f12010-06-30 19:14:05 +00001589
John McCalld06fb862010-04-28 00:00:30 +00001590 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +00001591 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +00001592 MangledName, &getModule());
1593 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001594 if (D)
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001595 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Bill Wendling8594fcb2013-01-31 00:30:05 +00001596 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1597 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
Bill Wendling9a677922013-01-23 00:21:06 +00001598 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1599 llvm::AttributeSet::get(VMContext,
1600 llvm::AttributeSet::FunctionIndex,
1601 B));
1602 }
Eli Friedmancc522d92009-11-09 05:07:37 +00001603
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001604 if (!DontDefer) {
1605 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1606 // each other bottoming out with the base dtor. Therefore we emit non-base
1607 // dtors on usage, even if there is no dtor definition in the TU.
1608 if (D && isa<CXXDestructorDecl>(D) &&
1609 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1610 GD.getDtorType()))
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001611 addDeferredDeclToEmit(F, GD);
John McCall357d0f32010-12-15 04:00:32 +00001612
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001613 // This is the first use or definition of a mangled name. If there is a
1614 // deferred decl with this name, remember that we need to emit it at the end
1615 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001616 auto DDI = DeferredDecls.find(MangledName);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001617 if (DDI != DeferredDecls.end()) {
1618 // Move the potentially referenced deferred decl to the
1619 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1620 // don't need it anymore).
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001621 addDeferredDeclToEmit(F, DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001622 DeferredDecls.erase(DDI);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001623
1624 // Otherwise, there are cases we have to worry about where we're
1625 // using a declaration for which we must emit a definition but where
1626 // we might not find a top-level definition:
1627 // - member functions defined inline in their classes
1628 // - friend functions defined inline in some class
1629 // - special member functions with implicit definitions
1630 // If we ever change our AST traversal to walk into class methods,
1631 // this will be unnecessary.
1632 //
1633 // We also don't emit a definition for a function if it's going to be an
Richard Smith46bb5812014-08-01 01:56:39 +00001634 // entry in a vtable, unless it's already marked as used.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001635 } else if (getLangOpts().CPlusPlus && D) {
1636 // Look for a declaration that's lexically in a record.
Richard Smith46bb5812014-08-01 01:56:39 +00001637 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1638 FD = FD->getPreviousDecl()) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001639 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Richard Smith46bb5812014-08-01 01:56:39 +00001640 if (FD->doesThisDeclarationHaveABody()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001641 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001642 break;
1643 }
John McCall357d0f32010-12-15 04:00:32 +00001644 }
Richard Smith46bb5812014-08-01 01:56:39 +00001645 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001646 }
Chris Lattner45470942009-03-21 09:44:56 +00001647 }
Mike Stump11289f42009-09-09 15:08:12 +00001648
John McCalld06fb862010-04-28 00:00:30 +00001649 // Make sure the result is of the requested type.
1650 if (!IsIncompleteFunction) {
1651 assert(F->getType()->getElementType() == Ty);
1652 return F;
1653 }
1654
Chris Lattnera5f58b02011-07-09 17:41:47 +00001655 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00001656 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001657}
1658
Chris Lattnerd4808922009-03-22 21:03:39 +00001659/// GetAddrOfFunction - Return the address of the given function. If Ty is
1660/// non-null, then this function will use the specified type if it has to
1661/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00001662llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00001663 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001664 bool ForVTable,
1665 bool DontDefer) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001666 // If there was no specific requested type, just convert it now.
1667 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +00001668 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +00001669
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001670 StringRef MangledName = getMangledName(GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001671 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
Chris Lattnerd4808922009-03-22 21:03:39 +00001672}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001673
Chris Lattnerd4808922009-03-22 21:03:39 +00001674/// CreateRuntimeFunction - Create a new runtime function with the specified
1675/// type and name.
1676llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001677CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001678 StringRef Name,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001679 llvm::AttributeSet ExtraAttrs) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001680 llvm::Constant *C =
1681 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001682 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001683 if (auto *F = dyn_cast<llvm::Function>(C))
John McCall882987f2013-02-28 19:01:20 +00001684 if (F->empty())
1685 F->setCallingConv(getRuntimeCC());
1686 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00001687}
Daniel Dunbar9c426522008-07-29 23:18:29 +00001688
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00001689/// CreateBuiltinFunction - Create a new builtin function with the specified
1690/// type and name.
1691llvm::Constant *
1692CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
1693 StringRef Name,
1694 llvm::AttributeSet ExtraAttrs) {
1695 llvm::Constant *C =
1696 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1697 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1698 if (auto *F = dyn_cast<llvm::Function>(C))
1699 if (F->empty())
1700 F->setCallingConv(getBuiltinCC());
1701 return C;
1702}
1703
Richard Smithe070fd22012-02-17 06:48:11 +00001704/// isTypeConstant - Determine whether an object of this type can be emitted
1705/// as a constant.
1706///
1707/// If ExcludeCtor is true, the duration when the object's constructor runs
1708/// will not be considered. The caller will need to verify that the object is
1709/// not written to during its construction.
1710bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1711 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00001712 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00001713
David Blaikiebbafb8a2012-03-11 07:00:24 +00001714 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00001715 if (const CXXRecordDecl *Record
1716 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1717 return ExcludeCtor && !Record->hasMutableFields() &&
1718 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00001719 }
Richard Smithe070fd22012-02-17 06:48:11 +00001720
Eli Friedmanb095e152009-12-11 21:23:03 +00001721 return true;
1722}
1723
Chris Lattnerd4808922009-03-22 21:03:39 +00001724/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1725/// create and return an llvm GlobalVariable with the specified type. If there
1726/// is something in the module with the specified name, return it potentially
1727/// bitcasted to the right type.
1728///
1729/// If D is non-null, it specifies a decl that correspond to this. This is used
1730/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001731llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001732CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001733 llvm::PointerType *Ty,
Rafael Espindolab73c9732014-05-22 23:33:27 +00001734 const VarDecl *D) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00001735 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001736 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00001737 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001738 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001739 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001740 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001741 }
1742
Hans Wennborg0a20f542014-08-29 00:16:06 +00001743 // Handle dropped DLL attributes.
1744 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1745 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1746
Chris Lattnerd4808922009-03-22 21:03:39 +00001747 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00001748 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001749
Chris Lattner3bfce182009-03-21 08:03:33 +00001750 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00001751 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1752 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1753
Owen Andersonade90fd2009-07-29 18:54:39 +00001754 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00001755 }
Mike Stump11289f42009-09-09 15:08:12 +00001756
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001757 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001758 auto *GV = new llvm::GlobalVariable(
1759 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00001760 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001761 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001762
Chris Lattner45470942009-03-21 09:44:56 +00001763 // This is the first use or definition of a mangled name. If there is a
1764 // deferred decl with this name, remember that we need to emit it at the end
1765 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001766 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00001767 if (DDI != DeferredDecls.end()) {
1768 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1769 // list, and remove it from DeferredDecls (since we don't need it anymore).
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001770 addDeferredDeclToEmit(GV, DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00001771 DeferredDecls.erase(DDI);
1772 }
Mike Stump11289f42009-09-09 15:08:12 +00001773
Chris Lattner3bfce182009-03-21 08:03:33 +00001774 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00001775 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00001776 // FIXME: This code is overly simple and should be merged with other global
1777 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00001778 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00001779
David Majnemerf6acb762014-04-25 17:07:16 +00001780 setLinkageAndVisibilityForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00001781
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001782 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00001783 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1784 CXXThreadLocals.push_back(std::make_pair(D, GV));
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001785 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001786 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00001787
1788 // If required by the ABI, treat declarations of static data members with
1789 // inline initializers as definitions.
Hans Wennborg56fc62b2014-07-17 20:25:23 +00001790 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Hans Wennborgfeedf852013-11-21 00:15:56 +00001791 EmitGlobalVarDefinition(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +00001792 }
Robert Lyttonf80d6882014-05-02 09:33:30 +00001793
1794 // Handle XCore specific ABI requirements.
1795 if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1796 D->getLanguageLinkage() == CLanguageLinkage &&
1797 D->getType().isConstant(Context) &&
1798 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1799 GV->setSection(".cp.rodata");
Chris Lattnerd4808922009-03-22 21:03:39 +00001800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001802 if (AddrSpace != Ty->getAddressSpace())
Matt Arsenault00e65b22013-11-15 02:19:52 +00001803 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1804
1805 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001806}
1807
Chris Lattnerd4808922009-03-22 21:03:39 +00001808
Anders Carlssonda80af32011-01-29 18:20:20 +00001809llvm::GlobalVariable *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001810CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00001811 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00001812 llvm::GlobalValue::LinkageTypes Linkage) {
1813 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00001814 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00001815
Anders Carlssonda80af32011-01-29 18:20:20 +00001816 if (GV) {
1817 // Check if the variable has the right type.
1818 if (GV->getType()->getElementType() == Ty)
1819 return GV;
1820
1821 // Because C++ name mangling, the only way we can end up with an already
1822 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00001823 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00001824 OldGV = GV;
1825 }
1826
1827 // Create a new variable.
1828 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00001829 Linkage, nullptr, Name);
1830
Anders Carlssonda80af32011-01-29 18:20:20 +00001831 if (OldGV) {
1832 // Replace occurrences of the old variable if needed.
1833 GV->takeName(OldGV);
1834
1835 if (!OldGV->use_empty()) {
1836 llvm::Constant *NewPtrForOldDecl =
1837 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1838 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1839 }
1840
1841 OldGV->eraseFromParent();
1842 }
Rafael Espindolacb92c192015-01-15 23:18:01 +00001843
David Majnemera03849b2015-03-18 22:04:43 +00001844 if (supportsCOMDAT() && GV->isWeakForLinker() &&
1845 !GV->hasAvailableExternallyLinkage())
Rafael Espindolacb92c192015-01-15 23:18:01 +00001846 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1847
Anders Carlssonda80af32011-01-29 18:20:20 +00001848 return GV;
1849}
1850
Chris Lattnerd4808922009-03-22 21:03:39 +00001851/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1852/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00001853/// then it will be created with the specified type instead of whatever the
Chris Lattnerd4808922009-03-22 21:03:39 +00001854/// normal requested type would be.
1855llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2192fe52011-07-18 04:24:23 +00001856 llvm::Type *Ty) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001857 assert(D->hasGlobalStorage() && "Not a global variable");
1858 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00001859 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00001860 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Chris Lattner2192fe52011-07-18 04:24:23 +00001862 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001863 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00001864
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001865 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001866 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001867}
1868
1869/// CreateRuntimeVariable - Create a new runtime global variable with the
1870/// specified type and name.
1871llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001872CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001873 StringRef Name) {
Rafael Espindolab73c9732014-05-22 23:33:27 +00001874 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
Chris Lattnerd4808922009-03-22 21:03:39 +00001875}
1876
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001877void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1878 assert(!D->getInit() && "Cannot emit definite definitions here!");
1879
Hans Wennborg43a0f992015-01-10 01:19:48 +00001880 if (!MustBeEmitted(D)) {
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001881 // If we have not seen a reference to this variable yet, place it
1882 // into the deferred declarations table to be emitted if needed
1883 // later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001884 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001885 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001886 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001887 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001888 }
1889 }
1890
1891 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001892 EmitGlobalVarDefinition(D);
1893}
1894
Chris Lattner2192fe52011-07-18 04:24:23 +00001895CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck9a648692011-01-18 02:01:14 +00001896 return Context.toCharUnitsFromBits(
Micah Villmowdd31ca12012-10-08 16:25:52 +00001897 TheDataLayout.getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00001898}
1899
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001900unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1901 unsigned AddrSpace) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00001902 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001903 if (D->hasAttr<CUDAConstantAttr>())
1904 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1905 else if (D->hasAttr<CUDASharedAttr>())
1906 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1907 else
1908 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1909 }
1910
1911 return AddrSpace;
1912}
1913
Richard Smithdf931ce2013-04-06 05:00:46 +00001914template<typename SomeDecl>
1915void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1916 llvm::GlobalValue *GV) {
1917 if (!getLangOpts().CPlusPlus)
1918 return;
1919
1920 // Must have 'used' attribute, or else inline assembly can't rely on
1921 // the name existing.
1922 if (!D->template hasAttr<UsedAttr>())
1923 return;
1924
1925 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001926 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00001927 return;
1928
1929 // Must be in an extern "C" context. Entities declared directly within
1930 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001931 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00001932 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00001933 return;
1934
1935 // OK, this is an internal linkage entity inside an extern "C" linkage
1936 // specification. Make a note of that so we can give it the "expected"
1937 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00001938 std::pair<StaticExternCMap::iterator, bool> R =
1939 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00001940
1941 // If we have multiple internal linkage entities with the same name
1942 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00001943 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00001944 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00001945}
1946
Rafael Espindola0d4fb982015-01-12 22:13:53 +00001947static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
1948 if (!CGM.supportsCOMDAT())
1949 return false;
1950
1951 if (D.hasAttr<SelectAnyAttr>())
1952 return true;
1953
1954 GVALinkage Linkage;
1955 if (auto *VD = dyn_cast<VarDecl>(&D))
1956 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
1957 else
1958 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
1959
1960 switch (Linkage) {
1961 case GVA_Internal:
1962 case GVA_AvailableExternally:
1963 case GVA_StrongExternal:
1964 return false;
1965 case GVA_DiscardableODR:
1966 case GVA_StrongODR:
1967 return true;
1968 }
1969 llvm_unreachable("No such linkage");
1970}
1971
Rafael Espindoladbee8a72015-01-15 21:36:08 +00001972void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
1973 llvm::GlobalObject &GO) {
1974 if (!shouldBeInCOMDAT(*this, D))
1975 return;
1976 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
1977}
1978
Daniel Dunbar9c426522008-07-29 23:18:29 +00001979void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Craig Topper8a13c412014-05-21 05:09:00 +00001980 llvm::Constant *Init = nullptr;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001981 QualType ASTTy = D->getType();
Richard Smith6331c402012-02-13 22:16:19 +00001982 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1983 bool NeedsGlobalCtor = false;
1984 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00001985
Richard Smithdafff942012-01-14 04:30:29 +00001986 const VarDecl *InitDecl;
1987 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001988
Anders Carlssonca4a5452010-01-26 17:43:42 +00001989 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001990 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001991 // implicitly initialized with { 0 }.
1992 //
1993 // Note that tentative definitions are only emitted at the end of
1994 // a translation unit, so they should never have incomplete
1995 // type. In addition, EmitTentativeDefinition makes sure that we
1996 // never attempt to emit a tentative definition if a real one
1997 // exists. A use may still exists, however, so we still may need
1998 // to do a RAUW.
1999 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00002000 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002001 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00002002 initializedGlobalDecl = GlobalDecl(D);
2003 Init = EmitConstantInit(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00002004
Fariborz Jahanian63628032012-06-26 16:06:38 +00002005 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00002006 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00002007 if (D->getType()->isReferenceType())
2008 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00002009
David Blaikiebbafb8a2012-03-11 07:00:24 +00002010 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00002011 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00002012 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00002013 } else {
2014 ErrorUnsupported(D, "static initializer");
2015 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2016 }
John McCall70013b62010-07-15 23:40:35 +00002017 } else {
2018 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00002019 // initializer position (just in case this entry was delayed) if we
2020 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002021 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00002022 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00002023 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002024 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002025
Chris Lattner2192fe52011-07-18 04:24:23 +00002026 llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00002027 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00002028
Chris Lattner149927c2009-03-21 09:16:30 +00002029 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002030 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00002031 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00002032 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2033 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00002034 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00002035 Entry = CE->getOperand(0);
2036 }
Mike Stump11289f42009-09-09 15:08:12 +00002037
Chris Lattner149927c2009-03-21 09:16:30 +00002038 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002039 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002040
Chris Lattner149927c2009-03-21 09:16:30 +00002041 // We have a definition after a declaration with the wrong type.
2042 // We must make a new GlobalVariable* and update everything that used OldGV
2043 // (a declaration or tentative definition) with the new GlobalVariable*
2044 // (which will be a definition).
2045 //
2046 // This happens if there is a prototype for a global (e.g.
2047 // "extern int x[];") and then a definition of a different type (e.g.
2048 // "int x[10];"). This also happens when an initializer has a different type
2049 // from the type of the global (this happens with unions).
Craig Topper8a13c412014-05-21 05:09:00 +00002050 if (!GV ||
Chris Lattner149927c2009-03-21 09:16:30 +00002051 GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00002052 GV->getType()->getAddressSpace() !=
Peter Collingbournef44bdf92012-05-20 21:08:35 +00002053 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump11289f42009-09-09 15:08:12 +00002054
John McCall7ec50432010-03-19 23:29:14 +00002055 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002056 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00002057
Chris Lattner149927c2009-03-21 09:16:30 +00002058 // Make a new global with the correct type, this is now guaranteed to work.
2059 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00002060
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002061 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00002062 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00002063 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00002064 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002065
2066 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00002067 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00002068 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00002069
Richard Smithdf931ce2013-04-06 05:00:46 +00002070 MaybeHandleStaticInExternC(D, GV);
2071
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002072 if (D->hasAttr<AnnotateAttr>())
2073 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00002074
Chris Lattnerd14bfa92007-07-13 05:13:43 +00002075 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00002076
2077 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00002078 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2079 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00002080
Hans Wennborg899ded92014-10-16 20:52:46 +00002081 // If it is in a read-only section, mark it 'constant'.
2082 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2083 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2084 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2085 GV->setConstant(true);
2086 }
2087
Ken Dyck160146e2010-01-27 17:10:57 +00002088 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00002089
Chris Lattnerd14bfa92007-07-13 05:13:43 +00002090 // Set the llvm linkage type as appropriate.
David Majnemer27d69db2014-04-28 22:17:59 +00002091 llvm::GlobalValue::LinkageTypes Linkage =
2092 getLLVMLinkageVarDefinition(D, GV->isConstant());
David Majnemer35ab3282014-06-11 04:08:55 +00002093
2094 // On Darwin, the backing variable for a C++11 thread_local variable always
2095 // has internal linkage; all accesses should just be calls to the
2096 // Itanium-specified entry point, which has the normal linkage of the
2097 // variable.
David Majnemerbb525f7c2014-10-15 22:38:23 +00002098 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2099 Context.getTargetInfo().getTriple().isMacOSX())
2100 Linkage = llvm::GlobalValue::InternalLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002101
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002102 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00002103 if (D->hasAttr<DLLImportAttr>())
2104 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2105 else if (D->hasAttr<DLLExportAttr>())
2106 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00002107 else
2108 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00002109
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002110 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnerf49573d2009-08-05 05:20:29 +00002111 // common vars aren't constant even if declared const.
2112 GV->setConstant(false);
Daniel Dunbard272cca2009-04-10 20:26:50 +00002113
Rafael Espindola502f65a2014-05-05 20:21:03 +00002114 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00002115
David Majnemerbb525f7c2014-10-15 22:38:23 +00002116 if (D->getTLSKind() && !GV->isThreadLocal()) {
2117 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2118 CXXThreadLocals.push_back(std::make_pair(D, GV));
2119 setTLSMode(GV, *D);
2120 }
2121
Rafael Espindoladbee8a72015-01-15 21:36:08 +00002122 maybeSetTrivialComdat(*D, *GV);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002123
John McCallcdf7ef52010-11-06 09:44:32 +00002124 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00002125 if (NeedsGlobalCtor || NeedsGlobalDtor)
2126 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00002127
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002128 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany28a26c82012-08-21 06:53:28 +00002129
Sanjiv Gupta158143a2008-06-05 08:59:10 +00002130 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00002131 if (CGDebugInfo *DI = getModuleDebugInfo())
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00002132 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00002133 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00002134}
Chris Lattner09153c02007-06-22 18:48:09 +00002135
David Majnemerc017d362014-08-05 00:01:13 +00002136static bool isVarDeclStrongDefinition(const ASTContext &Context,
2137 const VarDecl *D, bool NoCommon) {
David Majnemer9832a3d2014-04-10 16:53:16 +00002138 // Don't give variables common linkage if -fno-common was specified unless it
2139 // was overridden by a NoCommon attribute.
2140 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2141 return true;
2142
2143 // C11 6.9.2/2:
2144 // A declaration of an identifier for an object that has file scope without
2145 // an initializer, and without a storage-class specifier or with the
2146 // storage-class specifier static, constitutes a tentative definition.
2147 if (D->getInit() || D->hasExternalStorage())
2148 return true;
2149
2150 // A variable cannot be both common and exist in a section.
2151 if (D->hasAttr<SectionAttr>())
2152 return true;
2153
2154 // Thread local vars aren't considered common linkage.
2155 if (D->getTLSKind())
2156 return true;
2157
2158 // Tentative definitions marked with WeakImportAttr are true definitions.
2159 if (D->hasAttr<WeakImportAttr>())
2160 return true;
2161
David Majnemerc017d362014-08-05 00:01:13 +00002162 // Declarations with a required alignment do not have common linakge in MSVC
2163 // mode.
David Majnemere1a0b2e2015-02-03 08:49:32 +00002164 if (Context.getLangOpts().MSVCCompat) {
2165 if (D->hasAttr<AlignedAttr>())
2166 return true;
2167 QualType VarType = D->getType();
2168 if (Context.isAlignmentRequired(VarType))
2169 return true;
2170
2171 if (const auto *RT = VarType->getAs<RecordType>()) {
2172 const RecordDecl *RD = RT->getDecl();
2173 for (const FieldDecl *FD : RD->fields()) {
2174 if (FD->isBitField())
2175 continue;
2176 if (FD->hasAttr<AlignedAttr>())
2177 return true;
2178 if (Context.isAlignmentRequired(FD->getType()))
2179 return true;
2180 }
2181 }
2182 }
David Majnemerc017d362014-08-05 00:01:13 +00002183
David Majnemer9832a3d2014-04-10 16:53:16 +00002184 return false;
2185}
2186
Hans Wennborg1a3a0742014-05-14 19:54:53 +00002187llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00002188 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002189 if (Linkage == GVA_Internal)
2190 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00002191
2192 if (D->hasAttr<WeakAttr>()) {
2193 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002194 return llvm::GlobalVariable::WeakODRLinkage;
2195 else
2196 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00002197 }
2198
2199 // We are guaranteed to have a strong definition somewhere else,
2200 // so we can use available_externally linkage.
2201 if (Linkage == GVA_AvailableExternally)
2202 return llvm::Function::AvailableExternallyLinkage;
2203
David Majnemer27d69db2014-04-28 22:17:59 +00002204 // Note that Apple's kernel linker doesn't support symbol
2205 // coalescing, so we need to avoid linkonce and weak linkages there.
2206 // Normally, this means we just map to internal, but for explicit
2207 // instantiations we'll map to external.
2208
2209 // In C++, the compiler has to emit a definition in every translation unit
2210 // that references the function. We should use linkonce_odr because
2211 // a) if all references in this translation unit are optimized away, we
2212 // don't need to codegen it. b) if the function persists, it needs to be
2213 // merged with other definitions. c) C++ has the ODR, so we know the
2214 // definition is dependable.
2215 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00002216 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00002217 : llvm::Function::InternalLinkage;
2218
2219 // An explicit instantiation of a template has weak linkage, since
2220 // explicit instantiations can occur in multiple translation units
2221 // and must all be equivalent. However, we are not allowed to
2222 // throw away these explicit instantiations.
2223 if (Linkage == GVA_StrongODR)
2224 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2225 : llvm::Function::ExternalLinkage;
2226
David Majnemer27d69db2014-04-28 22:17:59 +00002227 // C++ doesn't have tentative definitions and thus cannot have common
2228 // linkage.
2229 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
David Majnemerc017d362014-08-05 00:01:13 +00002230 !isVarDeclStrongDefinition(Context, cast<VarDecl>(D),
2231 CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00002232 return llvm::GlobalVariable::CommonLinkage;
2233
David Majnemer27d69db2014-04-28 22:17:59 +00002234 // selectany symbols are externally visible, so use weak instead of
2235 // linkonce. MSVC optimizes away references to const selectany globals, so
2236 // all definitions should be the same and ODR linkage should be used.
2237 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2238 if (D->hasAttr<SelectAnyAttr>())
2239 return llvm::GlobalVariable::WeakODRLinkage;
2240
2241 // Otherwise, we have strong external linkage.
2242 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002243 return llvm::GlobalVariable::ExternalLinkage;
2244}
2245
David Majnemer27d69db2014-04-28 22:17:59 +00002246llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2247 const VarDecl *VD, bool IsConstant) {
2248 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00002249 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00002250}
2251
John McCall49954ca2012-12-12 22:21:47 +00002252/// Replace the uses of a function that was declared with a non-proto type.
2253/// We want to silently drop extra arguments from call sites
2254static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2255 llvm::Function *newFn) {
2256 // Fast path.
2257 if (old->use_empty()) return;
2258
2259 llvm::Type *newRetTy = newFn->getReturnType();
2260 SmallVector<llvm::Value*, 4> newArgs;
2261
2262 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2263 ui != ue; ) {
2264 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002265 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00002266
2267 // Recognize and replace uses of bitcasts. Most calls to
2268 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002269 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00002270 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2271 replaceUsesOfNonProtoConstant(bitcast, newFn);
2272 continue;
2273 }
2274
2275 // Recognize calls to the function.
2276 llvm::CallSite callSite(user);
2277 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002278 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00002279
2280 // If the return types don't match exactly, then we can't
2281 // transform this call unless it's dead.
2282 if (callSite->getType() != newRetTy && !callSite->use_empty())
2283 continue;
2284
2285 // Get the call site's attribute list.
Bill Wendling290d9522013-01-27 02:46:53 +00002286 SmallVector<llvm::AttributeSet, 8> newAttrs;
John McCall49954ca2012-12-12 22:21:47 +00002287 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2288
2289 // Collect any return attributes from the call.
Bill Wendling304f6f02013-01-21 21:57:40 +00002290 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
Bill Wendlingb7abb302013-01-21 22:45:00 +00002291 newAttrs.push_back(
Bill Wendling290d9522013-01-27 02:46:53 +00002292 llvm::AttributeSet::get(newFn->getContext(),
2293 oldAttrs.getRetAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00002294
2295 // If the function was passed too few arguments, don't transform.
2296 unsigned newNumArgs = newFn->arg_size();
2297 if (callSite.arg_size() < newNumArgs) continue;
2298
2299 // If extra arguments were passed, we silently drop them.
2300 // If any of the types mismatch, we don't transform.
2301 unsigned argNo = 0;
2302 bool dontTransform = false;
2303 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2304 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2305 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2306 dontTransform = true;
2307 break;
2308 }
2309
2310 // Add any parameter attributes.
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002311 if (oldAttrs.hasAttributes(argNo + 1))
2312 newAttrs.
Bill Wendling290d9522013-01-27 02:46:53 +00002313 push_back(llvm::
2314 AttributeSet::get(newFn->getContext(),
2315 oldAttrs.getParamAttributes(argNo + 1)));
John McCall49954ca2012-12-12 22:21:47 +00002316 }
2317 if (dontTransform)
2318 continue;
2319
Bill Wendling63ffde52013-01-18 21:26:07 +00002320 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
Bill Wendling290d9522013-01-27 02:46:53 +00002321 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2322 oldAttrs.getFnAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00002323
2324 // Okay, we can transform this. Create the new call instruction and copy
2325 // over the required information.
2326 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2327
2328 llvm::CallSite newCall;
2329 if (callSite.isCall()) {
2330 newCall = llvm::CallInst::Create(newFn, newArgs, "",
2331 callSite.getInstruction());
2332 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002333 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCall49954ca2012-12-12 22:21:47 +00002334 newCall = llvm::InvokeInst::Create(newFn,
2335 oldInvoke->getNormalDest(),
2336 oldInvoke->getUnwindDest(),
2337 newArgs, "",
2338 callSite.getInstruction());
2339 }
2340 newArgs.clear(); // for the next iteration
2341
2342 if (!newCall->getType()->isVoidTy())
2343 newCall->takeName(callSite.getInstruction());
2344 newCall.setAttributes(
2345 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2346 newCall.setCallingConv(callSite.getCallingConv());
2347
2348 // Finally, remove the old call, replacing any uses with the new one.
2349 if (!callSite->use_empty())
2350 callSite->replaceAllUsesWith(newCall.getInstruction());
2351
2352 // Copy debug location attached to CI.
2353 if (!callSite->getDebugLoc().isUnknown())
2354 newCall->setDebugLoc(callSite->getDebugLoc());
2355 callSite->eraseFromParent();
2356 }
2357}
2358
Chris Lattner36797ab2009-05-05 06:16:31 +00002359/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2360/// implement a function with no prototype, e.g. "int foo() {}". If there are
2361/// existing call uses of the old function in the module, this adjusts them to
2362/// call the new function directly.
2363///
2364/// This is not just a cleanup: the always_inline pass requires direct calls to
2365/// functions to be able to inline them. If there is a bitcast in the way, it
2366/// won't inline them. Instcombine normally deletes these calls, but it isn't
2367/// run at -O0.
2368static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2369 llvm::Function *NewFn) {
2370 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00002371 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00002372
John McCall49954ca2012-12-12 22:21:47 +00002373 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00002374}
2375
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00002376void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2377 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2378 // If we have a definition, this might be a deferred decl. If the
2379 // instantiation is explicit, make sure we emit it at the end.
2380 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2381 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00002382
2383 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00002384}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002385
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002386void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2387 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002388 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00002389
John McCall46288ef2011-03-09 08:12:35 +00002390 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00002391 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2392 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00002393
Chris Lattnereb7466d2009-05-12 20:58:15 +00002394 // Get or create the prototype for the function.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002395 if (!GV) {
2396 llvm::Constant *C =
2397 GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
Mike Stump11289f42009-09-09 15:08:12 +00002398
Rafael Espindola489c66b2014-05-08 14:33:38 +00002399 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002400 if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
Rafael Espindola489c66b2014-05-08 14:33:38 +00002401 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2402 GV = cast<llvm::GlobalValue>(CE->getOperand(0));
2403 } else {
2404 GV = cast<llvm::GlobalValue>(C);
2405 }
Chris Lattnera85d68e2009-03-21 09:25:43 +00002406 }
Mike Stump11289f42009-09-09 15:08:12 +00002407
Rafael Espindola489c66b2014-05-08 14:33:38 +00002408 if (!GV->isDeclaration()) {
Argyrios Kyrtzidisf405dd62013-11-23 18:41:35 +00002409 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
Richard Smith6d0e97a2014-08-02 00:50:16 +00002410 GlobalDecl OldGD = Manglings.lookup(GV->getName());
2411 if (auto *Prev = OldGD.getDecl())
2412 getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisf405dd62013-11-23 18:41:35 +00002413 return;
2414 }
Mike Stump11289f42009-09-09 15:08:12 +00002415
Rafael Espindola489c66b2014-05-08 14:33:38 +00002416 if (GV->getType()->getElementType() != Ty) {
Daniel Dunbar99d28352009-03-09 23:53:08 +00002417 // If the types mismatch then we have to rewrite the definition.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002418 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00002419
Chris Lattner5eaee562009-03-21 08:38:50 +00002420 // F is the Function* for the one with the wrong type, we must make a new
2421 // Function* and update everything that used F (a declaration) with the new
2422 // Function* (which will be a definition).
2423 //
2424 // This happens if there is a prototype for a function
2425 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00002426 // (e.g. "int f(int x)"). Move the old function aside so that it
2427 // doesn't interfere with GetAddrOfFunction.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002428 GV->setName(StringRef());
2429 auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00002430
John McCall49954ca2012-12-12 22:21:47 +00002431 // This might be an implementation of a function without a
2432 // prototype, in which case, try to do special replacement of
2433 // calls which match the new prototype. The really key thing here
2434 // is that we also potentially drop arguments from the call site
2435 // so as to make a direct call, which makes the inliner happier
2436 // and suppresses a number of optimizer warnings (!) about
2437 // dropping arguments.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002438 if (!GV->use_empty()) {
2439 ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
2440 GV->removeDeadConstantUsers();
Chris Lattnereb7466d2009-05-12 20:58:15 +00002441 }
Mike Stump11289f42009-09-09 15:08:12 +00002442
Chris Lattner5eaee562009-03-21 08:38:50 +00002443 // Replace uses of F with the Function we will endow with a body.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002444 if (!GV->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00002445 llvm::Constant *NewPtrForOldDecl =
Rafael Espindola489c66b2014-05-08 14:33:38 +00002446 llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
2447 GV->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattner36797ab2009-05-05 06:16:31 +00002448 }
Mike Stump11289f42009-09-09 15:08:12 +00002449
Chris Lattner5eaee562009-03-21 08:38:50 +00002450 // Ok, delete the old function now, which is dead.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002451 GV->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00002452
Rafael Espindola489c66b2014-05-08 14:33:38 +00002453 GV = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002454 }
Mike Stump11289f42009-09-09 15:08:12 +00002455
John McCall8e7cb6d2010-11-02 21:04:24 +00002456 // We need to set linkage and visibility on the function before
2457 // generating code for it because various parts of IR generation
2458 // want to propagate this information down (e.g. to local static
2459 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002460 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002461 setFunctionLinkage(GD, Fn);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00002462 if (D->hasAttr<DLLImportAttr>())
2463 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2464 else if (D->hasAttr<DLLExportAttr>())
2465 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2466 else
2467 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002468
Rafael Espindolae033c8c2014-05-08 15:26:12 +00002469 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00002470 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00002471
Richard Smithdf931ce2013-04-06 05:00:46 +00002472 MaybeHandleStaticInExternC(D, Fn);
2473
Rafael Espindoladbee8a72015-01-15 21:36:08 +00002474 maybeSetTrivialComdat(*D, *Fn);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002475
John McCalla738c252011-03-09 04:27:21 +00002476 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00002477
Rafael Espindolae033c8c2014-05-08 15:26:12 +00002478 setFunctionDefinitionAttributes(D, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00002479 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00002480
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002481 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002482 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002483 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002484 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002485 if (D->hasAttr<AnnotateAttr>())
2486 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002487}
2488
John McCall7ec50432010-03-19 23:29:14 +00002489void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002490 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002491 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00002492 assert(AA && "Not an alias?");
2493
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002494 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00002495
John McCall7ec50432010-03-19 23:29:14 +00002496 // If there is a definition in the module, then it wins over the alias.
2497 // This is dubious, but allow it to be safe. Just ignore the alias.
2498 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2499 if (Entry && !Entry->isDeclaration())
2500 return;
2501
Rafael Espindola208b5c02013-10-22 19:26:13 +00002502 Aliases.push_back(GD);
2503
Chris Lattner2192fe52011-07-18 04:24:23 +00002504 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00002505
2506 // Create a reference to the named value. This ensures that it is emitted
2507 // if a deferred decl.
2508 llvm::Constant *Aliasee;
2509 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002510 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00002511 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00002512 else
John McCall7ec50432010-03-19 23:29:14 +00002513 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00002514 llvm::PointerType::getUnqual(DeclTy),
David Majnemerbb525f7c2014-10-15 22:38:23 +00002515 /*D=*/nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00002516
2517 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00002518 auto *GA = llvm::GlobalAlias::create(
Rafael Espindola61722772014-05-17 19:58:16 +00002519 cast<llvm::PointerType>(Aliasee->getType())->getElementType(), 0,
Rafael Espindola27c60b52014-06-03 02:42:01 +00002520 llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00002521
Chris Lattner54041692009-03-22 21:47:11 +00002522 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00002523 if (GA->getAliasee() == Entry) {
2524 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2525 return;
2526 }
2527
John McCall7ec50432010-03-19 23:29:14 +00002528 assert(Entry->isDeclaration());
2529
Chris Lattner54041692009-03-22 21:47:11 +00002530 // If there is a declaration in the module, then we had an extern followed
2531 // by the alias, as in:
2532 // extern int test6();
2533 // ...
2534 // int test6() __attribute__((alias("test7")));
2535 //
2536 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00002537 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002538
Owen Andersonade90fd2009-07-29 18:54:39 +00002539 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00002540 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00002541 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00002542 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00002543 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00002544 }
Mike Stump11289f42009-09-09 15:08:12 +00002545
Daniel Dunbar38932572009-04-14 08:05:55 +00002546 // Set attributes which are particular to an alias; this is a
2547 // specialization of the attributes which may be set on a global
2548 // variable/function.
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00002549 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2550 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00002551 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2552 }
2553
David Majnemerbb525f7c2014-10-15 22:38:23 +00002554 if (const auto *VD = dyn_cast<VarDecl>(D))
2555 if (VD->getTLSKind())
2556 setTLSMode(GA, *VD);
2557
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00002558 setAliasAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00002559}
2560
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002561llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00002562 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00002563 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002564 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00002565}
Chris Lattner1eec6602007-08-31 04:31:45 +00002566
Daniel Dunbar64509b22009-07-23 22:52:48 +00002567static llvm::StringMapEntry<llvm::Constant*> &
2568GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2569 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00002570 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00002571 bool &IsUTF16,
2572 unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002573 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002574 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002575
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002576 // Check for simple case.
2577 if (!Literal->containsNonAsciiOrNull()) {
2578 StringLength = NumBytes;
David Blaikie13156b62014-11-19 03:06:06 +00002579 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002580 }
2581
Bill Wendling82b87f12012-03-30 00:26:17 +00002582 // Otherwise, convert the UTF8 literals into a string of shorts.
2583 IsUTF16 = true;
2584
2585 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divackye6377112012-09-06 15:59:27 +00002586 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002587 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00002588
Fariborz Jahanian535618b2010-09-07 19:57:04 +00002589 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2590 &ToPtr, ToPtr + NumBytes,
2591 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00002592
Daniel Dunbar91ade142009-07-23 23:41:22 +00002593 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00002594 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00002595
Bill Wendling82b87f12012-03-30 00:26:17 +00002596 // Add an explicit null.
2597 *ToPtr = 0;
David Blaikie13156b62014-11-19 03:06:06 +00002598 return *Map.insert(std::make_pair(
2599 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2600 (StringLength + 1) * 2),
2601 nullptr)).first;
Daniel Dunbar64509b22009-07-23 22:52:48 +00002602}
2603
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002604static llvm::StringMapEntry<llvm::Constant*> &
2605GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling07635cc2012-03-29 22:12:09 +00002606 const StringLiteral *Literal,
2607 unsigned &StringLength) {
2608 StringRef String = Literal->getString();
2609 StringLength = String.size();
David Blaikie13156b62014-11-19 03:06:06 +00002610 return *Map.insert(std::make_pair(String, nullptr)).first;
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002611}
2612
Daniel Dunbar64509b22009-07-23 22:52:48 +00002613llvm::Constant *
2614CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2615 unsigned StringLength = 0;
2616 bool isUTF16 = false;
2617 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00002618 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002619 getDataLayout().isLittleEndian(),
Daniel Dunbar91ade142009-07-23 23:41:22 +00002620 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002621
David Blaikie13156b62014-11-19 03:06:06 +00002622 if (auto *C = Entry.second)
Daniel Dunbar64509b22009-07-23 22:52:48 +00002623 return C;
Mike Stump11289f42009-09-09 15:08:12 +00002624
Chris Lattnerece04092012-02-07 00:39:47 +00002625 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00002626 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002627 llvm::Value *V;
2628
Chris Lattneraa64ca22009-07-16 16:48:25 +00002629 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00002630 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002631 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002632 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002633 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00002634 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00002635 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002636 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2637 CFConstantStringClassRef = V;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002638 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002639 else
2640 V = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00002641
Anders Carlssonc2480a52008-11-15 18:54:24 +00002642 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00002643
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002644 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00002645
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002646 llvm::Constant *Fields[4];
Douglas Gregor91f84212008-12-11 16:49:14 +00002647
Anders Carlssonb04ea612007-08-21 00:21:21 +00002648 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002649 Fields[0] = cast<llvm::ConstantExpr>(V);
Mike Stump11289f42009-09-09 15:08:12 +00002650
Anders Carlssonb04ea612007-08-21 00:21:21 +00002651 // Flags.
Chris Lattner2192fe52011-07-18 04:24:23 +00002652 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00002653 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00002654 llvm::ConstantInt::get(Ty, 0x07C8);
2655
Anders Carlssonb04ea612007-08-21 00:21:21 +00002656 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00002657 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00002658 if (isUTF16) {
David Blaikie13156b62014-11-19 03:06:06 +00002659 ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
2660 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
2661 Entry.first().size() / 2);
Bill Wendling82b87f12012-03-30 00:26:17 +00002662 C = llvm::ConstantDataArray::get(VMContext, Arr);
2663 } else {
David Blaikie13156b62014-11-19 03:06:06 +00002664 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling82b87f12012-03-30 00:26:17 +00002665 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002666
Bill Wendling86131f22012-01-10 08:46:39 +00002667 // Note: -fwritable-strings doesn't make the backing store strings of
2668 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002669 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00002670 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2671 llvm::GlobalValue::PrivateLinkage, C, ".str");
Rafael Espindolae79d43da2011-01-17 16:31:00 +00002672 GV->setUnnamedAddr(true);
Ulrich Weigandfa806422013-05-06 16:23:57 +00002673 // Don't enforce the target's minimum global alignment, since the only use
2674 // of the string is via this class initializer.
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002675 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2676 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2677 // that changes the section it ends in, which surprises ld64.
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002678 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00002679 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2680 GV->setAlignment(Align.getQuantity());
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002681 GV->setSection("__TEXT,__ustring");
Daniel Dunbar9c8cd4c2011-04-12 23:30:52 +00002682 } else {
2683 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2684 GV->setAlignment(Align.getQuantity());
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002685 GV->setSection("__TEXT,__cstring,cstring_literals");
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002686 }
Bill Wendling82b87f12012-03-30 00:26:17 +00002687
2688 // String.
Jay Foaded8db7d2011-07-21 14:31:17 +00002689 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00002690
Bill Wendling82b87f12012-03-30 00:26:17 +00002691 if (isUTF16)
2692 // Cast the UTF16 string to the correct type.
2693 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2694
Anders Carlssonb04ea612007-08-21 00:21:21 +00002695 // String length.
2696 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00002697 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002698
Anders Carlssonb04ea612007-08-21 00:21:21 +00002699 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00002700 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00002701 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2702 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00002703 "_unnamed_cfstring_");
Rafael Espindola8ff16102014-01-20 20:13:11 +00002704 GV->setSection("__DATA,__cfstring");
David Blaikie13156b62014-11-19 03:06:06 +00002705 Entry.second = GV;
Mike Stump11289f42009-09-09 15:08:12 +00002706
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00002707 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002708}
Chris Lattnerfb300092007-11-28 05:34:05 +00002709
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002710llvm::Constant *
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002711CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002712 unsigned StringLength = 0;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002713 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002714 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
David Blaikie3c8c46e2014-11-19 05:48:40 +00002715
David Blaikie13156b62014-11-19 03:06:06 +00002716 if (auto *C = Entry.second)
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002717 return C;
2718
Chris Lattner00a10ca2012-02-06 22:47:00 +00002719 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002720 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002721 llvm::Value *V;
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00002722 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002723 if (!ConstantStringClassRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002724 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2192fe52011-07-18 04:24:23 +00002725 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002726 llvm::Constant *GV;
John McCall5fb5df92012-06-20 06:18:46 +00002727 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002728 std::string str =
2729 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2730 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002731 GV = getObjCRuntime().GetClassGlobal(str);
2732 // Make sure the result is of the correct type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002733 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002734 V = llvm::ConstantExpr::getBitCast(GV, PTy);
2735 ConstantStringClassRef = V;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002736 } else {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002737 std::string str =
2738 StringClass.empty() ? "_NSConstantStringClassReference"
2739 : "_" + StringClass + "ClassReference";
Chris Lattner2192fe52011-07-18 04:24:23 +00002740 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002741 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002742 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002743 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2744 ConstantStringClassRef = V;
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002745 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002746 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002747 else
2748 V = ConstantStringClassRef;
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002749
2750 if (!NSConstantStringType) {
2751 // Construct the type for a constant NSString.
Alp Toker2dea15b2013-12-17 01:22:38 +00002752 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002753 D->startDefinition();
2754
2755 QualType FieldTypes[3];
2756
2757 // const int *isa;
2758 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2759 // const char *str;
2760 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2761 // unsigned int length;
2762 FieldTypes[2] = Context.UnsignedIntTy;
2763
2764 // Create fields
2765 for (unsigned i = 0; i < 3; ++i) {
2766 FieldDecl *Field = FieldDecl::Create(Context, D,
2767 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002768 SourceLocation(), nullptr,
2769 FieldTypes[i], /*TInfo=*/nullptr,
2770 /*BitWidth=*/nullptr,
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002771 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002772 ICIS_NoInit);
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002773 Field->setAccess(AS_public);
2774 D->addDecl(Field);
2775 }
2776
2777 D->completeDefinition();
2778 QualType NSTy = Context.getTagDeclType(D);
2779 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2780 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002781
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002782 llvm::Constant *Fields[3];
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002783
2784 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002785 Fields[0] = cast<llvm::ConstantExpr>(V);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002786
2787 // String pointer.
Chris Lattner9c818332012-02-05 02:30:40 +00002788 llvm::Constant *C =
David Blaikie3c8c46e2014-11-19 05:48:40 +00002789 llvm::ConstantDataArray::getString(VMContext, Entry.first());
2790
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002791 llvm::GlobalValue::LinkageTypes Linkage;
2792 bool isConstant;
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002793 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002794 isConstant = !LangOpts.WritableStrings;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002795
2796 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
2797 Linkage, C, ".str");
Rafael Espindolade089d42011-01-17 22:11:21 +00002798 GV->setUnnamedAddr(true);
Ulrich Weigandfa806422013-05-06 16:23:57 +00002799 // Don't enforce the target's minimum global alignment, since the only use
2800 // of the string is via this class initializer.
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002801 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2802 GV->setAlignment(Align.getQuantity());
Jay Foaded8db7d2011-07-21 14:31:17 +00002803 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002804
2805 // String length.
Chris Lattner2192fe52011-07-18 04:24:23 +00002806 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002807 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2808
2809 // The struct.
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002810 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002811 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2812 llvm::GlobalVariable::PrivateLinkage, C,
2813 "_unnamed_nsstring_");
Rafael Espindola63582d62014-01-20 15:19:43 +00002814 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2815 const char *NSStringNonFragileABISection =
Rafael Espindola8ff16102014-01-20 20:13:11 +00002816 "__DATA,__objc_stringobj,regular,no_dead_strip";
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002817 // FIXME. Fix section.
Rafael Espindola8ff16102014-01-20 20:13:11 +00002818 GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2819 ? NSStringNonFragileABISection
2820 : NSStringSection);
David Blaikie13156b62014-11-19 03:06:06 +00002821 Entry.second = GV;
David Blaikie3c8c46e2014-11-19 05:48:40 +00002822
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002823 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002824}
2825
Douglas Gregor636e2002011-08-09 17:23:49 +00002826QualType CodeGenModule::getObjCFastEnumerationStateType() {
2827 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00002828 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00002829 D->startDefinition();
2830
2831 QualType FieldTypes[] = {
2832 Context.UnsignedLongTy,
2833 Context.getPointerType(Context.getObjCIdType()),
2834 Context.getPointerType(Context.UnsignedLongTy),
2835 Context.getConstantArrayType(Context.UnsignedLongTy,
2836 llvm::APInt(32, 5), ArrayType::Normal, 0)
2837 };
2838
2839 for (size_t i = 0; i < 4; ++i) {
2840 FieldDecl *Field = FieldDecl::Create(Context,
2841 D,
2842 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002843 SourceLocation(), nullptr,
2844 FieldTypes[i], /*TInfo=*/nullptr,
2845 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00002846 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002847 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00002848 Field->setAccess(AS_public);
2849 D->addDecl(Field);
2850 }
2851
2852 D->completeDefinition();
2853 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2854 }
2855
2856 return ObjCFastEnumerationStateType;
2857}
2858
Eli Friedmanfcec6302011-11-01 02:23:42 +00002859llvm::Constant *
2860CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2861 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2862
2863 // Don't emit it as the address of the string, emit the string data itself
2864 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002865 if (E->getCharByteWidth() == 1) {
2866 SmallString<64> Str(E->getString());
2867
2868 // Resize the string to the right size, which is indicated by its type.
2869 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2870 Str.resize(CAT->getSize().getZExtValue());
2871 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2872 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002873
2874 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00002875 llvm::Type *ElemTy = AType->getElementType();
2876 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00002877
2878 // Wide strings have either 2-byte or 4-byte elements.
2879 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2880 SmallVector<uint16_t, 32> Elements;
2881 Elements.reserve(NumElements);
2882
2883 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2884 Elements.push_back(E->getCodeUnit(i));
2885 Elements.resize(NumElements);
2886 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00002887 }
2888
Chris Lattner02cb1712012-02-06 22:52:04 +00002889 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2890 SmallVector<uint32_t, 32> Elements;
2891 Elements.reserve(NumElements);
2892
2893 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2894 Elements.push_back(E->getCodeUnit(i));
2895 Elements.resize(NumElements);
2896 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00002897}
2898
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002899static llvm::GlobalVariable *
2900GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
2901 CodeGenModule &CGM, StringRef GlobalName,
2902 unsigned Alignment) {
2903 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2904 unsigned AddrSpace = 0;
2905 if (CGM.getLangOpts().OpenCL)
2906 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2907
Rafael Espindolad9b26d52015-01-16 20:32:35 +00002908 llvm::Module &M = CGM.getModule();
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002909 // Create a global variable for this string
2910 auto *GV = new llvm::GlobalVariable(
Rafael Espindolad9b26d52015-01-16 20:32:35 +00002911 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
2912 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002913 GV->setAlignment(Alignment);
2914 GV->setUnnamedAddr(true);
Rafael Espindolad9b26d52015-01-16 20:32:35 +00002915 if (GV->isWeakForLinker()) {
2916 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
2917 GV->setComdat(M.getOrInsertComdat(GV->getName()));
2918 }
2919
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002920 return GV;
2921}
2922
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002923/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2924/// constant array for the given string literal.
Alexey Samsonovb2cc23d2014-07-10 22:18:36 +00002925llvm::GlobalVariable *
Alexey Bataevec474782014-10-09 08:45:04 +00002926CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
2927 StringRef Name) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002928 auto Alignment =
2929 getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
James Molloye735b2b2014-05-09 16:28:56 +00002930
Richard Smith00db2f12014-07-29 21:20:12 +00002931 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2932 llvm::GlobalVariable **Entry = nullptr;
David Majnemer58e5bee2014-03-24 21:43:36 +00002933 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00002934 Entry = &ConstantStringMap[C];
2935 if (auto GV = *Entry) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002936 if (Alignment > GV->getAlignment())
2937 GV->setAlignment(Alignment);
2938 return GV;
David Majnemer58e5bee2014-03-24 21:43:36 +00002939 }
Eli Friedman49ddc5f2009-11-16 05:55:46 +00002940 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00002941
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002942 SmallString<256> MangledNameBuffer;
2943 StringRef GlobalVariableName;
2944 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00002945
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002946 // Mangle the string literal if the ABI allows for it. However, we cannot
2947 // do this if we are compiling with ASan or -fwritable-strings because they
2948 // rely on strings having normal linkage.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002949 if (!LangOpts.WritableStrings &&
2950 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002951 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2952 llvm::raw_svector_ostream Out(MangledNameBuffer);
2953 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2954 Out.flush();
David Majnemer58e5bee2014-03-24 21:43:36 +00002955
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002956 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2957 GlobalVariableName = MangledNameBuffer;
2958 } else {
2959 LT = llvm::GlobalValue::PrivateLinkage;
Alexey Bataevec474782014-10-09 08:45:04 +00002960 GlobalVariableName = Name;
David Majnemer58e5bee2014-03-24 21:43:36 +00002961 }
2962
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002963 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
2964 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00002965 *Entry = GV;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002966
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00002967 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
2968 QualType());
Eli Friedmanfcec6302011-11-01 02:23:42 +00002969 return GV;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002970}
2971
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002972/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2973/// array for the given ObjCEncodeExpr node.
Alexey Samsonovb2cc23d2014-07-10 22:18:36 +00002974llvm::GlobalVariable *
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002975CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2976 std::string Str;
2977 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00002978
2979 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002980}
2981
Alexey Samsonovadc90372014-06-04 20:25:57 +00002982/// GetAddrOfConstantCString - Returns a pointer to a character array containing
2983/// the literal and a terminating '\0' character.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002984/// The result has pointer to array type.
Alexey Samsonovb2cc23d2014-07-10 22:18:36 +00002985llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
2986 const std::string &Str, const char *GlobalName, unsigned Alignment) {
Alexey Samsonovadc90372014-06-04 20:25:57 +00002987 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002988 if (Alignment == 0) {
2989 Alignment = getContext()
2990 .getAlignOfGlobalVarInChars(getContext().CharTy)
2991 .getQuantity();
2992 }
2993
Richard Smith00db2f12014-07-29 21:20:12 +00002994 llvm::Constant *C =
2995 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
2996
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002997 // Don't share any string literals if strings aren't constant.
Richard Smith00db2f12014-07-29 21:20:12 +00002998 llvm::GlobalVariable **Entry = nullptr;
Alexey Samsonov175e52f2014-06-04 19:56:57 +00002999 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00003000 Entry = &ConstantStringMap[C];
3001 if (auto GV = *Entry) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003002 if (Alignment > GV->getAlignment())
3003 GV->setAlignment(Alignment);
3004 return GV;
3005 }
3006 }
3007
Daniel Dunbar08b216a2009-03-31 23:42:16 +00003008 // Get the default prefix if a name wasn't specified.
3009 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00003010 GlobalName = ".str";
Chris Lattnerfb300092007-11-28 05:34:05 +00003011 // Create a global variable for this.
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003012 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3013 GlobalName, Alignment);
3014 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00003015 *Entry = GV;
John McCall9b24df42011-08-04 01:03:22 +00003016 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00003017}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00003018
Richard Smithe6c01442013-06-05 00:46:14 +00003019llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00003020 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00003021 assert((E->getStorageDuration() == SD_Static ||
3022 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003023 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00003024
3025 // If we're not materializing a subobject of the temporary, keep the
3026 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00003027 QualType MaterializedType = Init->getType();
3028 if (Init == E->GetTemporaryExpr())
3029 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00003030
3031 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
3032 if (Slot)
3033 return Slot;
3034
3035 // FIXME: If an externally-visible declaration extends multiple temporaries,
3036 // we need to give each temporary the same name in every translation unit (and
3037 // we also need to make the temporaries externally-visible).
3038 SmallString<256> Name;
3039 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00003040 getCXXABI().getMangleContext().mangleReferenceTemporary(
3041 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00003042 Out.flush();
3043
Craig Topper8a13c412014-05-21 05:09:00 +00003044 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00003045 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00003046 // We might have a cached constant initializer for this temporary. Note
3047 // that this might have a different value from the value computed by
3048 // evaluating the initializer if the surrounding constant expression
3049 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00003050 Value = getContext().getMaterializedTemporaryValue(E, false);
3051 if (Value && Value->isUninit())
Craig Topper8a13c412014-05-21 05:09:00 +00003052 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00003053 }
3054
Richard Smitha509f2f2013-06-14 03:07:01 +00003055 // Try evaluating it now, it might have a constant initializer.
3056 Expr::EvalResult EvalResult;
3057 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3058 !EvalResult.hasSideEffects())
3059 Value = &EvalResult.Val;
3060
Craig Topper8a13c412014-05-21 05:09:00 +00003061 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00003062 bool Constant = false;
3063 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00003064 if (Value) {
3065 // The temporary has a constant initializer, use it.
Craig Topper8a13c412014-05-21 05:09:00 +00003066 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
Richard Smitha509f2f2013-06-14 03:07:01 +00003067 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3068 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00003069 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00003070 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00003071 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00003072 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00003073 }
3074
3075 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00003076 llvm::GlobalValue::LinkageTypes Linkage =
3077 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemerc9a9c7a2015-02-19 19:25:17 +00003078 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3079 const VarDecl *InitVD;
3080 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3081 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3082 // Temporaries defined inside a class get linkonce_odr linkage because the
3083 // class can be defined in multipe translation units.
3084 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3085 } else {
3086 // There is no need for this temporary to have external linkage if the
3087 // VarDecl has external linkage.
3088 Linkage = llvm::GlobalVariable::InternalLinkage;
3089 }
3090 }
David Majnemer27d69db2014-04-28 22:17:59 +00003091 unsigned AddrSpace = GetGlobalVarAddressSpace(
3092 VD, getContext().getTargetAddressSpace(MaterializedType));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003093 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00003094 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3095 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3096 AddrSpace);
David Majnemer846c2832014-04-29 06:18:53 +00003097 setGlobalVisibility(GV, VD);
Richard Smithe6c01442013-06-05 00:46:14 +00003098 GV->setAlignment(
Richard Smitha509f2f2013-06-14 03:07:01 +00003099 getContext().getTypeAlignInChars(MaterializedType).getQuantity());
David Majnemerf63bcaa2015-02-19 19:35:18 +00003100 if (supportsCOMDAT() && GV->isWeakForLinker())
3101 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smithe6c01442013-06-05 00:46:14 +00003102 if (VD->getTLSKind())
3103 setTLSMode(GV, *VD);
3104 Slot = GV;
3105 return GV;
3106}
3107
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003108/// EmitObjCPropertyImplementations - Emit information for synthesized
3109/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00003110void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003111 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00003112 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003113 // Dynamic is just for type-checking.
3114 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3115 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3116
3117 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00003118 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003119 // we want, that just indicates if the decl came from a
3120 // property. What we want to know is if the method is defined in
3121 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003122 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00003123 CodeGenFunction(*this).GenerateObjCGetter(
3124 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003125 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003126 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00003127 CodeGenFunction(*this).GenerateObjCSetter(
3128 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003129 }
3130 }
3131}
3132
John McCall6a4fa522011-03-22 07:05:39 +00003133static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00003134 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3135 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00003136 ivar; ivar = ivar->getNextIvar())
3137 if (ivar->getType().isDestructedType())
3138 return true;
3139
3140 return false;
3141}
3142
Fariborz Jahanian800821a2014-11-12 22:37:43 +00003143static bool AllTrivialInitializers(CodeGenModule &CGM,
3144 ObjCImplementationDecl *D) {
3145 CodeGenFunction CGF(CGM);
3146 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3147 E = D->init_end(); B != E; ++B) {
3148 CXXCtorInitializer *CtorInitExp = *B;
3149 Expr *Init = CtorInitExp->getInit();
3150 if (!CGF.isTrivialInitializer(Init))
3151 return false;
3152 }
3153 return true;
3154}
3155
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003156/// EmitObjCIvarInitializations - Emit information for ivar initialization
3157/// for an implementation.
3158void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00003159 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3160 if (needsDestructMethod(D)) {
3161 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3162 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3163 ObjCMethodDecl *DTORMethod =
3164 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00003165 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003166 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00003167 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003168 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00003169 D->addInstanceMethod(DTORMethod);
3170 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00003171 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00003172 }
3173
3174 // If the implementation doesn't have any ivar initializers, we don't need
3175 // a .cxx_construct.
Fariborz Jahanian800821a2014-11-12 22:37:43 +00003176 if (D->getNumIvarInitializers() == 0 ||
3177 AllTrivialInitializers(*this, D))
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003178 return;
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003179
John McCall6a4fa522011-03-22 07:05:39 +00003180 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3181 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003182 // The constructor returns 'self'.
3183 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3184 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00003185 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00003186 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003187 getContext().getObjCIdType(),
3188 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003189 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00003190 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003191 /*isImplicitlyDeclared=*/true,
3192 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003193 ObjCMethodDecl::Required);
3194 D->addInstanceMethod(CTORMethod);
3195 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00003196 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003197}
3198
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003199/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00003200void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Aaron Ballman629afae2014-03-07 19:56:05 +00003201 for (auto *I : ND->decls()) {
3202 if (const auto *VD = dyn_cast<VarDecl>(I))
David Blaikieb00f3602013-09-04 21:07:37 +00003203 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3204 VD->getTemplateSpecializationKind() != TSK_Undeclared)
3205 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00003206 EmitTopLevelDecl(I);
David Blaikieb00f3602013-09-04 21:07:37 +00003207 }
Anders Carlsson237f3492009-04-01 00:58:25 +00003208}
3209
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003210// EmitLinkageSpec - Emit all declarations in a linkage spec.
3211void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00003212 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3213 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003214 ErrorUnsupported(LSD, "linkage spec");
3215 return;
3216 }
3217
Aaron Ballman629afae2014-03-07 19:56:05 +00003218 for (auto *I : LSD->decls()) {
Fariborz Jahanian9dd2e082012-10-26 22:20:25 +00003219 // Meta-data for ObjC class includes references to implemented methods.
3220 // Generate class's method definitions first.
Aaron Ballman629afae2014-03-07 19:56:05 +00003221 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003222 for (auto *M : OID->methods())
3223 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00003224 }
Aaron Ballman629afae2014-03-07 19:56:05 +00003225 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00003226 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003227}
3228
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003229/// EmitTopLevelDecl - Emit code for a single top level declaration.
3230void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003231 // Ignore dependent declarations.
3232 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3233 return;
Mike Stump11289f42009-09-09 15:08:12 +00003234
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003235 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00003236 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00003237 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003238 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00003239 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00003240 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3241 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor70d83e22009-06-29 17:30:29 +00003242 return;
Mike Stump11289f42009-09-09 15:08:12 +00003243
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003244 EmitGlobal(cast<FunctionDecl>(D));
Alex Lorenzee024992014-08-04 18:41:51 +00003245 // Always provide some coverage mapping
3246 // even for the functions that aren't emitted.
3247 AddDeferredUnusedCoverageMapping(D);
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003248 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003249
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003250 case Decl::Var:
Larisse Voufo39a1e502013-08-06 01:03:05 +00003251 // Skip variable templates
3252 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3253 return;
3254 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003255 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003256 break;
3257
John McCall32f44bd2011-04-12 01:01:22 +00003258 // Indirect fields from global anonymous structs and unions can be
3259 // ignored; only the actual variable requires IR gen support.
3260 case Decl::IndirectField:
3261 break;
3262
Anders Carlssonf7475242009-04-15 15:55:24 +00003263 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003264 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00003265 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003266 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00003267 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00003268 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003269 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00003270 case Decl::VarTemplate:
3271 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003272 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00003273 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003274 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00003275 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00003276 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00003277 case Decl::Using: // using X; [C++]
3278 if (CGDebugInfo *DI = getModuleDebugInfo())
3279 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3280 return;
David Blaikief121b932013-05-20 22:50:41 +00003281 case Decl::NamespaceAlias:
3282 if (CGDebugInfo *DI = getModuleDebugInfo())
3283 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3284 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00003285 case Decl::UsingDirective: // using namespace X; [C++]
3286 if (CGDebugInfo *DI = getModuleDebugInfo())
3287 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3288 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00003289 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00003290 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00003291 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3292 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson0ade9712009-11-24 05:16:24 +00003293 return;
3294
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00003295 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00003296 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00003297 case Decl::CXXDestructor:
Francois Pichet1c229c02011-04-22 22:18:13 +00003298 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3299 return;
Reid Klecknere7de47e2013-07-22 13:51:44 +00003300 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00003301 break;
Anders Carlsson87835432009-06-11 21:22:55 +00003302
3303 case Decl::StaticAssert:
3304 // Nothing to do.
3305 break;
3306
Anders Carlssonf7475242009-04-15 15:55:24 +00003307 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00003308
Fariborz Jahanian3654e652009-03-18 22:33:24 +00003309 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00003310 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00003311 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00003312 break;
3313
Douglas Gregorf6102672012-01-01 21:23:57 +00003314 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003315 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00003316 if (Proto->isThisDeclarationADefinition())
3317 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003318 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00003319 }
3320
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003321 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003322 // Categories have properties but don't support synthesize so we
3323 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00003324 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003325 break;
3326
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003327 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003328 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003329 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003330 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00003331 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00003332 // Emit global variable debug information.
3333 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00003334 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3335 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3336 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003337 break;
Mike Stump11289f42009-09-09 15:08:12 +00003338 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003339 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003340 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003341 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003342 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003343 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3344 break;
3345 }
Mike Stump11289f42009-09-09 15:08:12 +00003346 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00003347 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003348 break;
3349
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003350 case Decl::LinkageSpec:
3351 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003352 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003353
3354 case Decl::FileScopeAsm: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003355 auto *AD = cast<FileScopeAsmDecl>(D);
Joerg Sonnenbergerdfd511e2015-03-13 00:54:30 +00003356 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003357 break;
3358 }
Mike Stump11289f42009-09-09 15:08:12 +00003359
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003360 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003361 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003362
3363 // Ignore import declarations that come from imported modules.
3364 if (clang::Module *Owner = Import->getOwningModule()) {
3365 if (getLangOpts().CurrentModule.empty() ||
3366 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3367 break;
3368 }
3369
Douglas Gregorbc25ff42013-01-14 20:53:57 +00003370 ImportedModules.insert(Import->getImportedModule());
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003371 break;
David Blaikie0e716b42014-03-03 23:48:23 +00003372 }
3373
Alexey Bataev97720002014-11-11 04:05:39 +00003374 case Decl::OMPThreadPrivate:
3375 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3376 break;
3377
David Blaikie0e716b42014-03-03 23:48:23 +00003378 case Decl::ClassTemplateSpecialization: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003379 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
David Blaikie0e716b42014-03-03 23:48:23 +00003380 if (DebugInfo &&
David Blaikie0317bc92014-12-16 23:49:18 +00003381 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3382 Spec->hasDefinition())
David Blaikie0e716b42014-03-03 23:48:23 +00003383 DebugInfo->completeTemplateDefinition(*Spec);
Richard Smitha634ff22014-12-01 18:59:10 +00003384 break;
David Blaikie0e716b42014-03-03 23:48:23 +00003385 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003386
Mike Stump11289f42009-09-09 15:08:12 +00003387 default:
Mike Stump18bb9282009-05-16 07:57:57 +00003388 // Make sure we handled everything we should, every other kind is a
3389 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3390 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003391 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Richard Smitha634ff22014-12-01 18:59:10 +00003392 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003393 }
3394}
John McCall09ae0322010-07-06 23:57:41 +00003395
Alex Lorenzee024992014-08-04 18:41:51 +00003396void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3397 // Do we need to generate coverage mapping?
3398 if (!CodeGenOpts.CoverageMapping)
3399 return;
3400 switch (D->getKind()) {
3401 case Decl::CXXConversion:
3402 case Decl::CXXMethod:
3403 case Decl::Function:
3404 case Decl::ObjCMethod:
3405 case Decl::CXXConstructor:
3406 case Decl::CXXDestructor: {
3407 if (!cast<FunctionDecl>(D)->hasBody())
3408 return;
3409 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3410 if (I == DeferredEmptyCoverageMappingDecls.end())
3411 DeferredEmptyCoverageMappingDecls[D] = true;
3412 break;
3413 }
3414 default:
3415 break;
3416 };
3417}
3418
3419void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3420 // Do we need to generate coverage mapping?
3421 if (!CodeGenOpts.CoverageMapping)
3422 return;
3423 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3424 if (Fn->isTemplateInstantiation())
3425 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3426 }
3427 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3428 if (I == DeferredEmptyCoverageMappingDecls.end())
3429 DeferredEmptyCoverageMappingDecls[D] = false;
3430 else
3431 I->second = false;
3432}
3433
3434void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00003435 std::vector<const Decl *> DeferredDecls;
Alex Lorenzee024992014-08-04 18:41:51 +00003436 for (const auto I : DeferredEmptyCoverageMappingDecls) {
3437 if (!I.second)
3438 continue;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00003439 DeferredDecls.push_back(I.first);
3440 }
3441 // Sort the declarations by their location to make sure that the tests get a
3442 // predictable order for the coverage mapping for the unused declarations.
3443 if (CodeGenOpts.DumpCoverageMapping)
3444 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3445 [] (const Decl *LHS, const Decl *RHS) {
3446 return LHS->getLocStart() < RHS->getLocStart();
3447 });
3448 for (const auto *D : DeferredDecls) {
Alex Lorenzee024992014-08-04 18:41:51 +00003449 switch (D->getKind()) {
3450 case Decl::CXXConversion:
3451 case Decl::CXXMethod:
3452 case Decl::Function:
3453 case Decl::ObjCMethod: {
3454 CodeGenPGO PGO(*this);
3455 GlobalDecl GD(cast<FunctionDecl>(D));
3456 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3457 getFunctionLinkage(GD));
3458 break;
3459 }
3460 case Decl::CXXConstructor: {
3461 CodeGenPGO PGO(*this);
3462 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3463 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3464 getFunctionLinkage(GD));
3465 break;
3466 }
3467 case Decl::CXXDestructor: {
3468 CodeGenPGO PGO(*this);
3469 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3470 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3471 getFunctionLinkage(GD));
3472 break;
3473 }
3474 default:
3475 break;
3476 };
3477 }
3478}
3479
John McCall09ae0322010-07-06 23:57:41 +00003480/// Turns the given pointer into a constant.
3481static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3482 const void *Ptr) {
3483 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00003484 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00003485 return llvm::ConstantInt::get(i64, PtrInt);
3486}
3487
3488static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3489 llvm::NamedMDNode *&GlobalMetadata,
3490 GlobalDecl D,
3491 llvm::GlobalValue *Addr) {
3492 if (!GlobalMetadata)
3493 GlobalMetadata =
3494 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3495
3496 // TODO: should we report variant information for ctors/dtors?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003497 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3498 llvm::ConstantAsMetadata::get(GetPointerConstant(
3499 CGM.getLLVMContext(), D.getDecl()))};
Jay Foadea324f12011-04-21 19:59:12 +00003500 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00003501}
3502
Richard Smithdf931ce2013-04-06 05:00:46 +00003503/// For each function which is declared within an extern "C" region and marked
3504/// as 'used', but has internal linkage, create an alias from the unmangled
3505/// name to the mangled name if possible. People expect to be able to refer
3506/// to such functions with an unmangled name from inline assembly within the
3507/// same translation unit.
3508void CodeGenModule::EmitStaticExternCAliases() {
Richard Smithf21c9612013-04-13 01:28:18 +00003509 for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3510 E = StaticExternCValues.end();
3511 I != E; ++I) {
3512 IdentifierInfo *Name = I->first;
3513 llvm::GlobalValue *Val = I->second;
Richard Smith85465e62013-04-06 07:07:44 +00003514 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola27c60b52014-06-03 02:42:01 +00003515 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith85465e62013-04-06 07:07:44 +00003516 }
Richard Smithdf931ce2013-04-06 05:00:46 +00003517}
3518
Alp Tokerfb8d02b2014-06-05 22:10:59 +00003519bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3520 GlobalDecl &Result) const {
3521 auto Res = Manglings.find(MangledName);
3522 if (Res == Manglings.end())
3523 return false;
3524 Result = Res->getValue();
3525 return true;
3526}
3527
John McCall09ae0322010-07-06 23:57:41 +00003528/// Emits metadata nodes associating all the global values in the
3529/// current module with the Decls they came from. This is useful for
3530/// projects using IR gen as a subroutine.
3531///
3532/// Since there's currently no way to associate an MDNode directly
3533/// with an llvm::GlobalValue, we create a global named metadata
3534/// with the name 'clang.global.decl.ptrs'.
3535void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00003536 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00003537
3538 // StaticLocalDeclMap
Robert Lytton5b88f78f2014-07-03 09:30:29 +00003539 for (auto &I : MangledDeclNames) {
3540 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3541 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall09ae0322010-07-06 23:57:41 +00003542 }
3543}
3544
3545/// Emits metadata nodes for all the local variables in the current
3546/// function.
3547void CodeGenFunction::EmitDeclMetadata() {
3548 if (LocalDeclMap.empty()) return;
3549
3550 llvm::LLVMContext &Context = getLLVMContext();
3551
3552 // Find the unique metadata ID for this name.
3553 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3554
Craig Topper8a13c412014-05-21 05:09:00 +00003555 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00003556
Robert Lytton5b88f78f2014-07-03 09:30:29 +00003557 for (auto &I : LocalDeclMap) {
3558 const Decl *D = I.first;
3559 llvm::Value *Addr = I.second;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003560 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00003561 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003562 Alloca->setMetadata(
3563 DeclPtrKind, llvm::MDNode::get(
3564 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003565 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00003566 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3567 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3568 }
3569 }
3570}
Daniel Dunbar900546d2010-07-16 00:00:15 +00003571
Rafael Espindola3bfa4682013-10-16 19:28:50 +00003572void CodeGenModule::EmitVersionIdentMetadata() {
3573 llvm::NamedMDNode *IdentMetadata =
3574 TheModule.getOrInsertNamedMetadata("llvm.ident");
3575 std::string Version = getClangFullVersion();
3576 llvm::LLVMContext &Ctx = TheModule.getContext();
3577
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003578 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola3bfa4682013-10-16 19:28:50 +00003579 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3580}
3581
Robert Lytton57765d52014-07-03 09:30:33 +00003582void CodeGenModule::EmitTargetMetadata() {
Richard Smith1ba0a072014-08-01 20:39:36 +00003583 // Warning, new MangledDeclNames may be appended within this loop.
3584 // We rely on MapVector insertions adding new elements to the end
3585 // of the container.
3586 // FIXME: Move this loop into the one target that needs it, and only
3587 // loop over those declarations for which we couldn't emit the target
3588 // metadata when we emitted the declaration.
3589 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
Richard Smith570706d2014-08-01 22:17:28 +00003590 auto Val = *(MangledDeclNames.begin() + I);
Richard Smith1ba0a072014-08-01 20:39:36 +00003591 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3592 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Robert Lytton57765d52014-07-03 09:30:33 +00003593 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3594 }
3595}
3596
Nick Lewycky85c011d2011-05-05 00:08:20 +00003597void CodeGenModule::EmitCoverageFile() {
3598 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky480cb992011-05-04 20:46:58 +00003599 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3600 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3601 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky85c011d2011-05-05 00:08:20 +00003602 llvm::MDString *CoverageFile =
3603 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky480cb992011-05-04 20:46:58 +00003604 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith2b1f2782014-11-11 21:31:03 +00003605 llvm::MDNode *CU = CUNode->getOperand(i);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003606 llvm::Metadata *Elts[] = {CoverageFile, CU};
3607 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky480cb992011-05-04 20:46:58 +00003608 }
3609 }
3610 }
3611}
Nico Webercf4ff5862012-10-11 10:13:44 +00003612
Nico Weber17d3a2c2014-09-08 16:26:36 +00003613llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Webercf4ff5862012-10-11 10:13:44 +00003614 // Sema has checked that all uuid strings are of the form
3615 // "12345678-1234-1234-1234-1234567890ab".
3616 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00003617 for (unsigned i = 0; i < 36; ++i) {
3618 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3619 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00003620 }
Nico Webercf4ff5862012-10-11 10:13:44 +00003621
Nico Weberdfa274e2014-09-08 16:11:15 +00003622 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemerbbecd092013-08-15 19:59:14 +00003623 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00003624
David Majnemerbbecd092013-08-15 19:59:14 +00003625 llvm::Constant *Field3[8];
3626 for (unsigned Idx = 0; Idx < 8; ++Idx)
3627 Field3[Idx] = llvm::ConstantInt::get(
3628 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3629
3630 llvm::Constant *Fields[4] = {
3631 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
3632 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
3633 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3634 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3635 };
3636
3637 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00003638}
David Majnemere2cb8d12014-07-07 06:20:47 +00003639
David Majnemer5f0dd612015-03-17 20:35:05 +00003640llvm::Constant *
David Majnemer37b417f2015-03-29 21:55:10 +00003641CodeGenModule::getAddrOfCXXCatchHandlerType(QualType Ty,
3642 QualType CatchHandlerType) {
3643 return getCXXABI().getAddrOfCXXCatchHandlerType(Ty, CatchHandlerType);
David Majnemer443250f2015-03-17 20:35:00 +00003644}
3645
David Majnemere2cb8d12014-07-07 06:20:47 +00003646llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
3647 bool ForEH) {
3648 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
3649 // FIXME: should we even be calling this method if RTTI is disabled
3650 // and it's not for EH?
3651 if (!ForEH && !getLangOpts().RTTI)
3652 return llvm::Constant::getNullValue(Int8PtrTy);
3653
3654 if (ForEH && Ty->isObjCObjectPointerType() &&
3655 LangOpts.ObjCRuntime.isGNUFamily())
3656 return ObjCRuntime->GetEHType(Ty);
3657
David Majnemer443250f2015-03-17 20:35:00 +00003658 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
David Majnemere2cb8d12014-07-07 06:20:47 +00003659}
3660
Alexey Bataev97720002014-11-11 04:05:39 +00003661void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
3662 for (auto RefExpr : D->varlists()) {
3663 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
3664 bool PerformInit =
3665 VD->getAnyInitializer() &&
3666 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
3667 /*ForRef=*/false);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003668 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
3669 VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(), PerformInit))
Alexey Bataev97720002014-11-11 04:05:39 +00003670 CXXGlobalInits.push_back(InitFunction);
3671 }
3672}
3673