blob: b35e81c0b2b672f5c08648c7548deb229c73e048 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CGCall.h"
18#include "CGDebugInfo.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000019#include "CGObjCRuntime.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000020#include "CGOpenCLRuntime.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070021#include "CGOpenMPRuntime.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "CodeGenFunction.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070023#include "CodeGenPGO.h"
Stephen Hines176edba2014-12-01 14:53:08 -080024#include "CoverageMappingGen.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "CodeGenTBAA.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000026#include "TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "clang/AST/ASTContext.h"
Ken Dyck687cc4a2010-01-26 13:48:07 +000028#include "clang/AST/CharUnits.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000029#include "clang/AST/DeclCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/AST/DeclObjC.h"
Douglas Gregoraf896892010-06-21 18:41:26 +000031#include "clang/AST/DeclTemplate.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000032#include "clang/AST/Mangle.h"
Anders Carlsson1a5e0d72009-11-30 23:41:22 +000033#include "clang/AST/RecordLayout.h"
Rafael Espindolaa411d2f2011-10-26 20:41:06 +000034#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindolabcf6b982011-12-19 14:41:01 +000035#include "clang/Basic/Builtins.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000036#include "clang/Basic/CharInfo.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000037#include "clang/Basic/Diagnostic.h"
Douglas Gregorb6cbe512013-01-14 17:21:00 +000038#include "clang/Basic/Module.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000039#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040#include "clang/Basic/TargetInfo.h"
Rafael Espindola9686f122013-10-16 19:28:50 +000041#include "clang/Basic/Version.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000042#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindolad2054982013-10-22 19:26:13 +000043#include "clang/Sema/SemaDiagnostic.h"
Sebastian Redl19b1a6e2012-02-25 20:51:20 +000044#include "llvm/ADT/APSInt.h"
John McCall6374c332010-03-06 00:35:14 +000045#include "llvm/ADT/Triple.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070046#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-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"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070052#include "llvm/ProfileData/InstrProfReader.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000053#include "llvm/Support/ConvertUTF.h"
Chris Lattner78f7ece2009-11-07 09:22:46 +000054#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000055
Reid Spencer5f016e22007-07-11 17:01:13 +000056using namespace clang;
57using namespace CodeGen;
58
Julien Lerouge77f68bb2011-09-09 22:41:49 +000059static const char AnnotationSection[] = "llvm.metadata";
60
Stephen Hines651f13c2014-04-23 16:59:28 -070061static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCall64aa4b32013-04-16 22:48:15 +000062 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +000063 case TargetCXXABI::GenericAArch64:
John McCall96fcde02013-01-25 23:36:14 +000064 case TargetCXXABI::GenericARM:
65 case TargetCXXABI::iOS:
Stephen Hines651f13c2014-04-23 16:59:28 -070066 case TargetCXXABI::iOS64:
John McCall96fcde02013-01-25 23:36:14 +000067 case TargetCXXABI::GenericItanium:
Stephen Hines651f13c2014-04-23 16:59:28 -070068 return CreateItaniumCXXABI(CGM);
John McCall96fcde02013-01-25 23:36:14 +000069 case TargetCXXABI::Microsoft:
Stephen Hines651f13c2014-04-23 16:59:28 -070070 return CreateMicrosoftCXXABI(CGM);
John McCallf16aa102010-08-22 21:01:12 +000071 }
72
73 llvm_unreachable("invalid C++ ABI kind");
John McCallf16aa102010-08-22 21:01:12 +000074}
75
Chandler Carruth2811ccf2009-11-12 17:24:48 +000076CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall3abae092013-04-16 22:48:20 +000077 llvm::Module &M, const llvm::DataLayout &TD,
Stephen Hines176edba2014-12-01 14:53:08 -080078 DiagnosticsEngine &diags,
79 CoverageSourceInfo *CoverageInfo)
Alexey Samsonov6a4c5dc2013-08-12 11:48:05 +000080 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
81 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070082 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr),
83 TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this),
84 ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr),
85 CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr),
86 NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
87 CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
88 NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
89 NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
90 BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
91 GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
Stephen Hines176edba2014-12-01 14:53:08 -080092 LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietz4f45bc02013-01-18 11:30:38 +000093
Chris Lattner8b418682012-02-07 00:39:47 +000094 // Initialize the type cache.
95 llvm::LLVMContext &LLVMContext = M.getContext();
96 VoidTy = llvm::Type::getVoidTy(LLVMContext);
97 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
98 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
99 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
101 FloatTy = llvm::Type::getFloatTy(LLVMContext);
102 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
103 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
104 PointerAlignInBytes =
105 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
106 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
107 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
108 Int8PtrTy = Int8Ty->getPointerTo(0);
109 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
110
John McCallbd7370a2013-02-28 19:01:20 +0000111 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
112
David Blaikie4e4d0842012-03-11 07:00:24 +0000113 if (LangOpts.ObjC1)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000114 createObjCRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000115 if (LangOpts.OpenCL)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000116 createOpenCLRuntime();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700117 if (LangOpts.OpenMP)
118 createOpenMPRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000119 if (LangOpts.CUDA)
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000120 createCUDARuntime();
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000121
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000122 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Stephen Hines176edba2014-12-01 14:53:08 -0800123 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000124 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
125 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Stephen Hines651f13c2014-04-23 16:59:28 -0700126 getCXXABI().getMangleContext());
Dan Gohman3d5aff52010-10-14 23:06:10 +0000127
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000128 // If debug info or coverage generation is enabled, create the CGDebugInfo
129 // object.
Douglas Gregor4cdad312012-10-23 20:05:01 +0000130 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000131 CodeGenOpts.EmitGcovArcs ||
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000132 CodeGenOpts.EmitGcovNotes)
133 DebugInfo = new CGDebugInfo(*this);
John McCalld16c2cf2011-02-08 08:22:06 +0000134
135 Block.GlobalUniqueCount = 0;
John McCall5936e332011-02-15 09:22:45 +0000136
David Blaikie4e4d0842012-03-11 07:00:24 +0000137 if (C.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000138 ARCData = new ARCEntrypoints();
139 RRData = new RREntrypoints();
Stephen Hines651f13c2014-04-23 16:59:28 -0700140
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700141 if (!CodeGenOpts.InstrProfileInput.empty()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700142 if (std::error_code EC = llvm::IndexedInstrProfReader::create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700143 CodeGenOpts.InstrProfileInput, PGOReader)) {
144 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
145 "Could not read profile: %0");
146 getDiags().Report(DiagID) << EC.message();
147 }
148 }
Stephen Hines176edba2014-12-01 14:53:08 -0800149
150 // If coverage mapping generation is enabled, create the
151 // CoverageMappingModuleGen object.
152 if (CodeGenOpts.CoverageMapping)
153 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattner2b94fe32008-03-01 08:45:05 +0000154}
155
156CodeGenModule::~CodeGenModule() {
Peter Collingbournee9265232011-07-27 20:29:46 +0000157 delete ObjCRuntime;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000158 delete OpenCLRuntime;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700159 delete OpenMPRuntime;
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000160 delete CUDARuntime;
Ted Kremenek0628b722011-10-08 05:28:26 +0000161 delete TheTargetCodeGenInfo;
Dan Gohman4376c852010-10-15 18:04:46 +0000162 delete TBAA;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000163 delete DebugInfo;
John McCallf85e1932011-06-15 23:02:42 +0000164 delete ARCData;
165 delete RRData;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000166}
167
David Chisnall0d13f6f2010-01-23 02:40:42 +0000168void CodeGenModule::createObjCRuntime() {
John McCall260611a2012-06-20 06:18:46 +0000169 // This is just isGNUFamily(), but we want to force implementors of
170 // new ABIs to decide how best to do this.
171 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000172 case ObjCRuntime::GNUstep:
173 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000174 case ObjCRuntime::ObjFW:
Peter Collingbournee9265232011-07-27 20:29:46 +0000175 ObjCRuntime = CreateGNUObjCRuntime(*this);
John McCall260611a2012-06-20 06:18:46 +0000176 return;
177
178 case ObjCRuntime::FragileMacOSX:
179 case ObjCRuntime::MacOSX:
180 case ObjCRuntime::iOS:
Peter Collingbournee9265232011-07-27 20:29:46 +0000181 ObjCRuntime = CreateMacObjCRuntime(*this);
John McCall260611a2012-06-20 06:18:46 +0000182 return;
183 }
184 llvm_unreachable("bad runtime kind");
David Chisnall0d13f6f2010-01-23 02:40:42 +0000185}
186
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000187void CodeGenModule::createOpenCLRuntime() {
188 OpenCLRuntime = new CGOpenCLRuntime(*this);
189}
190
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700191void CodeGenModule::createOpenMPRuntime() {
192 OpenMPRuntime = new CGOpenMPRuntime(*this);
193}
194
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000195void CodeGenModule::createCUDARuntime() {
196 CUDARuntime = CreateNVCUDARuntime(*this);
197}
198
Stephen Hines176edba2014-12-01 14:53:08 -0800199void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
200 Replacements[Name] = C;
201}
202
Rafael Espindola61a0a752013-11-05 21:37:29 +0000203void CodeGenModule::applyReplacements() {
204 for (ReplacementsTy::iterator I = Replacements.begin(),
205 E = Replacements.end();
206 I != E; ++I) {
207 StringRef MangledName = I->first();
208 llvm::Constant *Replacement = I->second;
209 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
210 if (!Entry)
211 continue;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700212 auto *OldF = cast<llvm::Function>(Entry);
213 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola081c2152013-11-12 04:53:19 +0000214 if (!NewF) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700215 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
216 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Stephen Hines651f13c2014-04-23 16:59:28 -0700217 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700218 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Stephen Hines651f13c2014-04-23 16:59:28 -0700219 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
220 CE->getOpcode() == llvm::Instruction::GetElementPtr);
221 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
222 }
Rafael Espindola081c2152013-11-12 04:53:19 +0000223 }
224
225 // Replace old with new, but keep the old order.
226 OldF->replaceAllUsesWith(Replacement);
227 if (NewF) {
228 NewF->removeFromParent();
229 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
230 }
231 OldF->eraseFromParent();
Rafael Espindola61a0a752013-11-05 21:37:29 +0000232 }
233}
234
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700235// This is only used in aliases that we created and we know they have a
236// linear structure.
237static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
238 llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
239 const llvm::Constant *C = &GA;
240 for (;;) {
241 C = C->stripPointerCasts();
242 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
243 return GO;
244 // stripPointerCasts will not walk over weak aliases.
245 auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
246 if (!GA2)
247 return nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -0800248 if (!Visited.insert(GA2).second)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700249 return nullptr;
250 C = GA2->getAliasee();
251 }
252}
253
Rafael Espindolad2054982013-10-22 19:26:13 +0000254void CodeGenModule::checkAliases() {
Stephen Hines651f13c2014-04-23 16:59:28 -0700255 // Check if the constructed aliases are well formed. It is really unfortunate
256 // that we have to do this in CodeGen, but we only construct mangled names
257 // and aliases during codegen.
Rafael Espindolad2054982013-10-22 19:26:13 +0000258 bool Error = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700259 DiagnosticsEngine &Diags = getDiags();
Rafael Espindolad2054982013-10-22 19:26:13 +0000260 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
261 E = Aliases.end(); I != E; ++I) {
262 const GlobalDecl &GD = *I;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700263 const auto *D = cast<ValueDecl>(GD.getDecl());
Rafael Espindolad2054982013-10-22 19:26:13 +0000264 const AliasAttr *AA = D->getAttr<AliasAttr>();
265 StringRef MangledName = getMangledName(GD);
266 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700267 auto *Alias = cast<llvm::GlobalAlias>(Entry);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700268 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
269 if (!GV) {
270 Error = true;
271 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
272 } else if (GV->isDeclaration()) {
Rafael Espindolad2054982013-10-22 19:26:13 +0000273 Error = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700274 Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
Stephen Hines651f13c2014-04-23 16:59:28 -0700275 }
276
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700277 llvm::Constant *Aliasee = Alias->getAliasee();
278 llvm::GlobalValue *AliaseeGV;
279 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
280 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
281 else
282 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
283
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700284 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
285 StringRef AliasSection = SA->getName();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700286 if (AliasSection != AliaseeGV->getSection())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700287 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
288 << AliasSection;
Rafael Espindolad2054982013-10-22 19:26:13 +0000289 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700290
291 // We have to handle alias to weak aliases in here. LLVM itself disallows
292 // this since the object semantics would not match the IL one. For
293 // compatibility with gcc we implement it by just pointing the alias
294 // to its aliasee's aliasee. We also warn, since the user is probably
295 // expecting the link to be weak.
296 if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
297 if (GA->mayBeOverridden()) {
298 Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
299 << GV->getName() << GA->getName();
300 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
301 GA->getAliasee(), Alias->getType());
302 Alias->setAliasee(Aliasee);
303 }
304 }
Rafael Espindolad2054982013-10-22 19:26:13 +0000305 }
306 if (!Error)
307 return;
308
309 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
310 E = Aliases.end(); I != E; ++I) {
311 const GlobalDecl &GD = *I;
312 StringRef MangledName = getMangledName(GD);
313 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700314 auto *Alias = cast<llvm::GlobalAlias>(Entry);
Rafael Espindolad2054982013-10-22 19:26:13 +0000315 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
316 Alias->eraseFromParent();
317 }
318}
319
Stephen Hines651f13c2014-04-23 16:59:28 -0700320void CodeGenModule::clear() {
321 DeferredDeclsToEmit.clear();
322}
323
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700324void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
325 StringRef MainFile) {
326 if (!hasDiagnostics())
327 return;
328 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
329 if (MainFile.empty())
330 MainFile = "<stdin>";
331 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
332 } else
333 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
334 << Mismatched;
335}
336
Ted Kremenek815c78f2008-08-05 18:50:11 +0000337void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000338 EmitDeferred();
Rafael Espindola61a0a752013-11-05 21:37:29 +0000339 applyReplacements();
Rafael Espindolad2054982013-10-22 19:26:13 +0000340 checkAliases();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000341 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000342 EmitCXXGlobalDtorFunc();
Richard Smithb80a16e2013-04-19 16:42:07 +0000343 EmitCXXThreadLocalInitFunc();
Peter Collingbournee9265232011-07-27 20:29:46 +0000344 if (ObjCRuntime)
345 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000346 AddGlobalCtor(ObjCInitFunction);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700347 if (getCodeGenOpts().ProfileInstrGenerate)
348 if (llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this))
349 AddGlobalCtor(PGOInit, 0);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700350 if (PGOReader && PGOStats.hasDiagnostics())
351 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000352 EmitCtorList(GlobalCtors, "llvm.global_ctors");
353 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000354 EmitGlobalAnnotations();
Richard Smith00249372013-04-06 05:00:46 +0000355 EmitStaticExternCAliases();
Stephen Hines176edba2014-12-01 14:53:08 -0800356 EmitDeferredUnusedCoverageMappings();
357 if (CoverageMapping)
358 CoverageMapping->emit();
Stephen Hines651f13c2014-04-23 16:59:28 -0700359 emitLLVMUsed();
Douglas Gregorf43b7212013-01-16 01:23:41 +0000360
Reid Kleckner3190ca92013-05-08 13:44:39 +0000361 if (CodeGenOpts.Autolink &&
362 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorf43b7212013-01-16 01:23:41 +0000363 EmitModuleLinkOptions();
364 }
Manman Renfc0f91c2013-06-19 01:46:49 +0000365 if (CodeGenOpts.DwarfVersion)
366 // We actually want the latest version when there are conflicts.
367 // We can change from Warning to Latest if such mode is supported.
368 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
369 CodeGenOpts.DwarfVersion);
Manman Ren1f856a02013-12-09 20:27:01 +0000370 if (DebugInfo)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700371 // We support a single version in the linked module. The LLVM
372 // parser will drop debug info with a different version number
373 // (and warn about it, too).
374 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren82e23c22013-12-09 21:04:35 +0000375 llvm::DEBUG_METADATA_VERSION);
Douglas Gregor5d75ea72013-01-14 18:28:43 +0000376
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700377 // We need to record the widths of enums and wchar_t, so that we can generate
378 // the correct build attributes in the ARM backend.
379 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
380 if ( Arch == llvm::Triple::arm
381 || Arch == llvm::Triple::armeb
382 || Arch == llvm::Triple::thumb
383 || Arch == llvm::Triple::thumbeb) {
384 // Width of wchar_t in bytes
385 uint64_t WCharWidth =
386 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
387 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
388
389 // The minimum width of an enum in bytes
390 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
391 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
392 }
393
Stephen Hines176edba2014-12-01 14:53:08 -0800394 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
395 llvm::PICLevel::Level PL = llvm::PICLevel::Default;
396 switch (PLevel) {
397 case 0: break;
398 case 1: PL = llvm::PICLevel::Small; break;
399 case 2: PL = llvm::PICLevel::Large; break;
400 default: llvm_unreachable("Invalid PIC Level");
401 }
402
403 getModule().setPICLevel(PL);
404 }
405
John McCallb2593832010-09-16 06:16:50 +0000406 SimplifyPersonality();
407
John McCall744016d2010-07-06 23:57:41 +0000408 if (getCodeGenOpts().EmitDeclMetadata)
409 EmitDeclMetadata();
Nick Lewycky5ea4f442011-05-04 20:46:58 +0000410
411 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky3dc05412011-05-05 00:08:20 +0000412 EmitCoverageFile();
Devang Patelf391dbe2011-08-16 20:58:22 +0000413
414 if (DebugInfo)
415 DebugInfo->finalize();
Rafael Espindola9686f122013-10-16 19:28:50 +0000416
417 EmitVersionIdentMetadata();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700418
419 EmitTargetMetadata();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000420}
421
Devang Patele80d5672011-03-23 16:29:39 +0000422void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
423 // Make sure that this type is translated.
424 Types.UpdateCompletedType(TD);
Devang Patele80d5672011-03-23 16:29:39 +0000425}
426
Dan Gohman3d5aff52010-10-14 23:06:10 +0000427llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
428 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700429 return nullptr;
Dan Gohman3d5aff52010-10-14 23:06:10 +0000430 return TBAA->getTBAAInfo(QTy);
431}
432
Kostya Serebryany8cb4a072012-03-26 17:03:51 +0000433llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
434 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700435 return nullptr;
Kostya Serebryany8cb4a072012-03-26 17:03:51 +0000436 return TBAA->getTBAAInfoForVTablePtr();
437}
438
Dan Gohmanb22c7dc2012-09-28 21:58:29 +0000439llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
440 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700441 return nullptr;
Dan Gohmanb22c7dc2012-09-28 21:58:29 +0000442 return TBAA->getTBAAStructInfo(QTy);
443}
444
Manman Renb37a73d2013-04-04 21:53:22 +0000445llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
446 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700447 return nullptr;
Manman Renb37a73d2013-04-04 21:53:22 +0000448 return TBAA->getTBAAStructTypeInfo(QTy);
449}
450
451llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
452 llvm::MDNode *AccessN,
453 uint64_t O) {
454 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700455 return nullptr;
Manman Renb37a73d2013-04-04 21:53:22 +0000456 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
457}
458
Manman Renfeba9f22013-10-08 00:08:49 +0000459/// Decorate the instruction with a TBAA tag. For both scalar TBAA
460/// and struct-path aware TBAA, the tag has the same format:
461/// base type, access type and offset.
Manman Renca835182013-04-11 23:02:56 +0000462/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
Dan Gohman3d5aff52010-10-14 23:06:10 +0000463void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
Manman Renca835182013-04-11 23:02:56 +0000464 llvm::MDNode *TBAAInfo,
465 bool ConvertTypeToTag) {
Manman Renfeba9f22013-10-08 00:08:49 +0000466 if (ConvertTypeToTag && TBAA)
Manman Renca835182013-04-11 23:02:56 +0000467 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
468 TBAA->getTBAAScalarTagInfo(TBAAInfo));
469 else
470 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
Dan Gohman3d5aff52010-10-14 23:06:10 +0000471}
472
Stephen Hines651f13c2014-04-23 16:59:28 -0700473void CodeGenModule::Error(SourceLocation loc, StringRef message) {
474 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
475 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall32096692011-03-18 02:56:14 +0000476}
477
Daniel Dunbar488e9932008-08-16 00:56:44 +0000478/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000479/// specified stmt yet.
David Blaikie0a1c8622013-08-19 21:02:26 +0000480void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikied6471f72011-09-25 23:23:43 +0000481 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000482 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000483 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000484 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
485 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000486}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000487
Daniel Dunbar488e9932008-08-16 00:56:44 +0000488/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000489/// specified decl yet.
David Blaikie0a1c8622013-08-19 21:02:26 +0000490void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikied6471f72011-09-25 23:23:43 +0000491 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000492 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000493 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000494 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000495}
496
John McCallbc8d40d2011-06-24 21:55:10 +0000497llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
498 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
499}
500
Mike Stump1eb44332009-09-09 15:08:12 +0000501void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000502 const NamedDecl *D) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000503 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000504 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000505 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000506 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000507 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000508
John McCallaf146032010-10-30 11:50:40 +0000509 // Set visibility for definitions.
Rafael Espindola2beda122013-02-27 02:15:29 +0000510 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000511 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
512 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000513}
514
Hans Wennborgde981f32012-06-28 08:01:44 +0000515static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
516 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
517 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
518 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
519 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
520 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
521}
522
523static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
524 CodeGenOptions::TLSModel M) {
525 switch (M) {
526 case CodeGenOptions::GeneralDynamicTLSModel:
527 return llvm::GlobalVariable::GeneralDynamicTLSModel;
528 case CodeGenOptions::LocalDynamicTLSModel:
529 return llvm::GlobalVariable::LocalDynamicTLSModel;
530 case CodeGenOptions::InitialExecTLSModel:
531 return llvm::GlobalVariable::InitialExecTLSModel;
532 case CodeGenOptions::LocalExecTLSModel:
533 return llvm::GlobalVariable::LocalExecTLSModel;
534 }
535 llvm_unreachable("Invalid TLS model!");
536}
537
Stephen Hines176edba2014-12-01 14:53:08 -0800538void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smith38afbc72013-04-13 02:43:54 +0000539 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgde981f32012-06-28 08:01:44 +0000540
Stephen Hines176edba2014-12-01 14:53:08 -0800541 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregor4cdad312012-10-23 20:05:01 +0000542 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgde981f32012-06-28 08:01:44 +0000543
544 // Override the TLS model if it is explicitly specified.
Stephen Hines651f13c2014-04-23 16:59:28 -0700545 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgde981f32012-06-28 08:01:44 +0000546 TLM = GetLLVMTLSModel(Attr->getModel());
547 }
548
549 GV->setThreadLocalMode(TLM);
550}
551
Chris Lattner5f9e2722011-07-23 10:55:15 +0000552StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700553 StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
554 if (!FoundStr.empty())
555 return FoundStr;
556
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700557 const auto *ND = cast<NamedDecl>(GD.getDecl());
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700558 SmallString<256> Buffer;
559 StringRef Str;
560 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
561 llvm::raw_svector_ostream Out(Buffer);
562 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
563 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
564 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
565 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
566 else
567 getCXXABI().getMangleContext().mangleName(ND, Out);
568 Str = Out.str();
569 } else {
Anders Carlsson793a9902010-06-22 16:05:32 +0000570 IdentifierInfo *II = ND->getIdentifier();
571 assert(II && "Attempt to mangle unnamed decl.");
Anders Carlsson793a9902010-06-22 16:05:32 +0000572 Str = II->getName();
Anders Carlsson793a9902010-06-22 16:05:32 +0000573 }
Anders Carlsson793a9902010-06-22 16:05:32 +0000574
Stephen Hines176edba2014-12-01 14:53:08 -0800575 // Keep the first result in the case of a mangling collision.
576 auto Result = Manglings.insert(std::make_pair(Str, GD));
577 return FoundStr = Result.first->first();
Anders Carlsson793a9902010-06-22 16:05:32 +0000578}
579
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700580StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
581 const BlockDecl *BD) {
Peter Collingbourne14110472011-01-13 18:57:25 +0000582 MangleContext &MangleCtx = getCXXABI().getMangleContext();
583 const Decl *D = GD.getDecl();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700584
585 SmallString<256> Buffer;
586 llvm::raw_svector_ostream Out(Buffer);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700587 if (!D)
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000588 MangleCtx.mangleGlobalBlock(BD,
589 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700590 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000591 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700592 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000593 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000594 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000595 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700596
Stephen Hines176edba2014-12-01 14:53:08 -0800597 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
598 return Result.first->first();
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000599}
600
Chris Lattner5f9e2722011-07-23 10:55:15 +0000601llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCallf746aa62010-03-19 23:29:14 +0000602 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000603}
604
Chris Lattner6d397602008-03-14 17:18:18 +0000605/// AddGlobalCtor - Add a function to the list that will be called before
606/// main() runs.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700607void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
608 llvm::Constant *AssociatedData) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000609 // FIXME: Type coercion of void()* types.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700610 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner6d397602008-03-14 17:18:18 +0000611}
612
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000613/// AddGlobalDtor - Add a function to the list that will be called
614/// when the module is unloaded.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700615void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000616 // FIXME: Type coercion of void()* types.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700617 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000618}
619
620void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
621 // Ctor function type is void()*.
John McCall0774cb82011-05-15 01:53:33 +0000622 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000623 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000624
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700625 // Get the type of a ctor entry, { i32, void ()*, i8* }.
626 llvm::StructType *CtorStructTy = llvm::StructType::get(
627 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000628
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000629 // Construct the constructor and destructor arrays.
Chris Lattner0b239712012-02-06 22:16:34 +0000630 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000631 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner0b239712012-02-06 22:16:34 +0000632 llvm::Constant *S[] = {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700633 llvm::ConstantInt::get(Int32Ty, I->Priority, false),
634 llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy),
635 (I->AssociatedData
636 ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy)
637 : llvm::Constant::getNullValue(VoidPtrTy))
Chris Lattner0b239712012-02-06 22:16:34 +0000638 };
Owen Anderson08e25242009-07-27 22:29:56 +0000639 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000640 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000641
642 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000643 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000644 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000645 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000646 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000647 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000648 }
Chris Lattner6d397602008-03-14 17:18:18 +0000649}
650
John McCalld46f9852010-02-19 01:32:20 +0000651llvm::GlobalValue::LinkageTypes
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000652CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700653 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknera4130ba2013-07-22 13:51:44 +0000654
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000655 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000656
Stephen Hines651f13c2014-04-23 16:59:28 -0700657 if (isa<CXXDestructorDecl>(D) &&
658 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700659 GD.getDtorType())) {
660 // Destructor variants in the Microsoft C++ ABI are always internal or
661 // linkonce_odr thunks emitted on an as-needed basis.
662 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
663 : llvm::GlobalValue::LinkOnceODRLinkage;
664 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700665
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700666 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld46f9852010-02-19 01:32:20 +0000667}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000668
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700669void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
670 llvm::Function *F) {
671 setNonAliasAttributes(D, F);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000672}
673
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000674void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000675 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000676 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000677 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000678 AttributeListType AttributeList;
Bill Wendling94236e72013-02-22 00:13:35 +0000679 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
Bill Wendling785b7782012-12-07 23:17:26 +0000680 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000681 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000682}
683
John McCalld1e40d52011-10-02 01:16:38 +0000684/// Determines whether the language options require us to model
685/// unwind exceptions. We treat -fexceptions as mandating this
686/// except under the fragile ObjC ABI with only ObjC exceptions
687/// enabled. This means, for example, that C with -fexceptions
688/// enables this.
David Blaikie4e4d0842012-03-11 07:00:24 +0000689static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCalld1e40d52011-10-02 01:16:38 +0000690 // If exceptions are completely disabled, obviously this is false.
David Blaikie4e4d0842012-03-11 07:00:24 +0000691 if (!LangOpts.Exceptions) return false;
John McCalld1e40d52011-10-02 01:16:38 +0000692
693 // If C++ exceptions are enabled, this is true.
David Blaikie4e4d0842012-03-11 07:00:24 +0000694 if (LangOpts.CXXExceptions) return true;
John McCalld1e40d52011-10-02 01:16:38 +0000695
696 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikie4e4d0842012-03-11 07:00:24 +0000697 if (LangOpts.ObjCExceptions) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000698 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCalld1e40d52011-10-02 01:16:38 +0000699 }
700
701 return true;
702}
703
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000704void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
705 llvm::Function *F) {
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000706 llvm::AttrBuilder B;
707
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000708 if (CodeGenOpts.UnwindTables)
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000709 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000710
David Blaikie4e4d0842012-03-11 07:00:24 +0000711 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000712 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000713
Eli Friedman2873aee2011-08-22 23:55:33 +0000714 if (D->hasAttr<NakedAttr>()) {
715 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000716 B.addAttribute(llvm::Attribute::Naked);
717 B.addAttribute(llvm::Attribute::NoInline);
Stephen Hines651f13c2014-04-23 16:59:28 -0700718 } else if (D->hasAttr<OptimizeNoneAttr>()) {
719 // OptimizeNone implies noinline; we should not be inlining such functions.
720 B.addAttribute(llvm::Attribute::OptimizeNone);
721 B.addAttribute(llvm::Attribute::NoInline);
722 } else if (D->hasAttr<NoDuplicateAttr>()) {
723 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000724 } else if (D->hasAttr<NoInlineAttr>()) {
725 B.addAttribute(llvm::Attribute::NoInline);
Stephen Hines651f13c2014-04-23 16:59:28 -0700726 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000727 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
728 llvm::Attribute::NoInline)) {
729 // (noinline wins over always_inline, and we can't specify both in IR)
730 B.addAttribute(llvm::Attribute::AlwaysInline);
Eli Friedman2873aee2011-08-22 23:55:33 +0000731 }
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000732
Diego Novillod27e5cb2013-05-24 20:18:15 +0000733 if (D->hasAttr<ColdAttr>()) {
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000734 B.addAttribute(llvm::Attribute::OptimizeForSize);
Diego Novillod27e5cb2013-05-24 20:18:15 +0000735 B.addAttribute(llvm::Attribute::Cold);
736 }
Benjamin Krameree409a92012-05-12 21:10:52 +0000737
Quentin Colombetaee56fa2012-11-01 23:55:47 +0000738 if (D->hasAttr<MinSizeAttr>())
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000739 B.addAttribute(llvm::Attribute::MinSize);
Richard Smithef4d5ce2012-09-28 22:46:07 +0000740
Stephen Hines651f13c2014-04-23 16:59:28 -0700741 if (D->hasAttr<OptimizeNoneAttr>()) {
742 // OptimizeNone wins over OptimizeForSize and MinSize.
743 B.removeAttribute(llvm::Attribute::OptimizeForSize);
744 B.removeAttribute(llvm::Attribute::MinSize);
745 }
746
David Blaikie4e4d0842012-03-11 07:00:24 +0000747 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000748 B.addAttribute(llvm::Attribute::StackProtect);
Stephen Hines651f13c2014-04-23 16:59:28 -0700749 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
750 B.addAttribute(llvm::Attribute::StackProtectStrong);
David Blaikie4e4d0842012-03-11 07:00:24 +0000751 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000752 B.addAttribute(llvm::Attribute::StackProtectReq);
Will Dietz4f45bc02013-01-18 11:30:38 +0000753
Alexey Samsonov7e73f942013-03-06 10:54:18 +0000754 // Add sanitizer attributes if function is not blacklisted.
Stephen Hines176edba2014-12-01 14:53:08 -0800755 if (!isInSanitizerBlacklist(F, D->getLocation())) {
Alexey Samsonov7e73f942013-03-06 10:54:18 +0000756 // When AddressSanitizer is enabled, set SanitizeAddress attribute
757 // unless __attribute__((no_sanitize_address)) is used.
Stephen Hines176edba2014-12-01 14:53:08 -0800758 if (LangOpts.Sanitize.has(SanitizerKind::Address) &&
759 !D->hasAttr<NoSanitizeAddressAttr>())
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000760 B.addAttribute(llvm::Attribute::SanitizeAddress);
Alexey Samsonov7e73f942013-03-06 10:54:18 +0000761 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
Stephen Hines176edba2014-12-01 14:53:08 -0800762 if (LangOpts.Sanitize.has(SanitizerKind::Thread) &&
763 !D->hasAttr<NoSanitizeThreadAttr>())
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000764 B.addAttribute(llvm::Attribute::SanitizeThread);
Alexey Samsonov7e73f942013-03-06 10:54:18 +0000765 // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
Stephen Hines176edba2014-12-01 14:53:08 -0800766 if (LangOpts.Sanitize.has(SanitizerKind::Memory) &&
767 !D->hasAttr<NoSanitizeMemoryAttr>())
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000768 B.addAttribute(llvm::Attribute::SanitizeMemory);
Alexey Samsonov7e73f942013-03-06 10:54:18 +0000769 }
Alexander Potapenko89651ea2012-02-02 11:49:28 +0000770
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000771 F->addAttributes(llvm::AttributeSet::FunctionIndex,
772 llvm::AttributeSet::get(
773 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
774
775 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
776 F->setUnnamedAddr(true);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700777 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000778 if (MD->isVirtual())
779 F->setUnnamedAddr(true);
780
Sean Huntcf807c42010-08-18 23:23:40 +0000781 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
782 if (alignment)
783 F->setAlignment(alignment);
784
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000785 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000786 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
787 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000788}
789
Mike Stump1eb44332009-09-09 15:08:12 +0000790void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000791 llvm::GlobalValue *GV) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700792 if (const auto *ND = dyn_cast<NamedDecl>(D))
Anders Carlsson934176f2011-01-29 19:41:00 +0000793 setGlobalVisibility(GV, ND);
John McCall1fb0caa2010-10-22 21:05:15 +0000794 else
795 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000796
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000797 if (D->hasAttr<UsedAttr>())
Stephen Hines651f13c2014-04-23 16:59:28 -0700798 addUsedGlobal(GV);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700799}
800
Stephen Hines176edba2014-12-01 14:53:08 -0800801void CodeGenModule::setAliasAttributes(const Decl *D,
802 llvm::GlobalValue *GV) {
803 SetCommonAttributes(D, GV);
804
805 // Process the dllexport attribute based on whether the original definition
806 // (not necessarily the aliasee) was exported.
807 if (D->hasAttr<DLLExportAttr>())
808 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
809}
810
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700811void CodeGenModule::setNonAliasAttributes(const Decl *D,
812 llvm::GlobalObject *GO) {
813 SetCommonAttributes(D, GO);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000814
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000815 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700816 GO->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000817
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700818 getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000819}
820
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000821void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
822 llvm::Function *F,
823 const CGFunctionInfo &FI) {
824 SetLLVMFunctionAttributes(D, FI, F);
825 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000826
827 F->setLinkage(llvm::Function::InternalLinkage);
828
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700829 setNonAliasAttributes(D, F);
830}
831
832static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
833 const NamedDecl *ND) {
834 // Set linkage and visibility in case we never see a definition.
835 LinkageInfo LV = ND->getLinkageAndVisibility();
836 if (LV.getLinkage() != ExternalLinkage) {
837 // Don't set internal linkage on declarations.
838 } else {
839 if (ND->hasAttr<DLLImportAttr>()) {
840 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
841 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
842 } else if (ND->hasAttr<DLLExportAttr>()) {
843 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
844 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
845 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
846 // "extern_weak" is overloaded in LLVM; we probably should have
847 // separate linkage types for this.
848 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
849 }
850
851 // Set visibility on a declaration only if it's explicit.
852 if (LV.isVisibilityExplicit())
853 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
854 }
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000855}
856
Stephen Hines176edba2014-12-01 14:53:08 -0800857void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
858 bool IsIncompleteFunction,
859 bool IsThunk) {
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000860 if (unsigned IID = F->getIntrinsicID()) {
861 // If this is an intrinsic function, set the function's attributes
862 // to the intrinsic's attributes.
Bill Wendling50e6b182012-10-15 04:47:45 +0000863 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
864 (llvm::Intrinsic::ID)IID));
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000865 return;
866 }
867
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700868 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000869
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000870 if (!IsIncompleteFunction)
John McCallde5d3c72012-02-17 03:33:10 +0000871 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Stephen Hines651f13c2014-04-23 16:59:28 -0700873 // Add the Returned attribute for "this", except for iOS 5 and earlier
874 // where substantial code, including the libstdc++ dylib, was compiled with
875 // GCC and does not actually return "this".
Stephen Hines176edba2014-12-01 14:53:08 -0800876 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700877 !(getTarget().getTriple().isiOS() &&
878 getTarget().getTriple().isOSVersionLT(6))) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000879 assert(!F->arg_empty() &&
880 F->arg_begin()->getType()
881 ->canLosslesslyBitCastTo(F->getReturnType()) &&
882 "unexpected this return");
883 F->addAttribute(1, llvm::Attribute::Returned);
884 }
885
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000886 // Only a few attributes are set on declarations; these may later be
887 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700889 setLinkageAndVisibilityForGV(F, FD);
John McCallaf146032010-10-30 11:50:40 +0000890
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700891 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
892 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
893 // Don't dllexport/import destructor thunks.
894 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
John McCallaf146032010-10-30 11:50:40 +0000895 }
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000896 }
897
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000898 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000899 F->setSection(SA->getName());
Richard Smithddcff1b2013-07-21 23:12:18 +0000900
901 // A replaceable global allocation function does not act like a builtin by
902 // default, only if it is invoked by a new-expression or delete-expression.
903 if (FD->isReplaceableGlobalAllocationFunction())
904 F->addAttribute(llvm::AttributeSet::FunctionIndex,
905 llvm::Attribute::NoBuiltin);
Daniel Dunbar219df662008-09-08 23:44:31 +0000906}
907
Stephen Hines651f13c2014-04-23 16:59:28 -0700908void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +0000909 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +0000910 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000911 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000912}
913
Stephen Hines651f13c2014-04-23 16:59:28 -0700914void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
915 assert(!GV->isDeclaration() &&
916 "Only globals with definition can force usage.");
917 LLVMCompilerUsed.push_back(GV);
918}
919
920static void emitUsed(CodeGenModule &CGM, StringRef Name,
921 std::vector<llvm::WeakVH> &List) {
Daniel Dunbar02698712009-02-13 20:29:50 +0000922 // Don't create llvm.used if there is no need.
Stephen Hines651f13c2014-04-23 16:59:28 -0700923 if (List.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +0000924 return;
925
Stephen Hines651f13c2014-04-23 16:59:28 -0700926 // Convert List to what ConstantArray needs.
Chris Lattner0b239712012-02-06 22:16:34 +0000927 SmallVector<llvm::Constant*, 8> UsedArray;
Stephen Hines651f13c2014-04-23 16:59:28 -0700928 UsedArray.resize(List.size());
929 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000930 UsedArray[i] =
Stephen Hines651f13c2014-04-23 16:59:28 -0700931 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
932 CGM.Int8PtrTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000933 }
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000935 if (UsedArray.empty())
936 return;
Stephen Hines651f13c2014-04-23 16:59:28 -0700937 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700939 auto *GV = new llvm::GlobalVariable(
940 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
941 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar02698712009-02-13 20:29:50 +0000942
943 GV->setSection("llvm.metadata");
944}
945
Stephen Hines651f13c2014-04-23 16:59:28 -0700946void CodeGenModule::emitLLVMUsed() {
947 emitUsed(*this, "llvm.used", LLVMUsed);
948 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
949}
950
Reid Kleckner3190ca92013-05-08 13:44:39 +0000951void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
952 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
953 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
954}
955
Aaron Ballmana7ff62f2013-06-04 02:07:14 +0000956void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
957 llvm::SmallString<32> Opt;
958 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
959 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
960 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
961}
962
Reid Kleckner3190ca92013-05-08 13:44:39 +0000963void CodeGenModule::AddDependentLib(StringRef Lib) {
964 llvm::SmallString<24> Opt;
965 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
966 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
967 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
968}
969
Douglas Gregor858afb32013-01-14 20:53:57 +0000970/// \brief Add link options implied by the given module, including modules
971/// it depends on, using a postorder walk.
Reid Kleckner3190ca92013-05-08 13:44:39 +0000972static void addLinkOptionsPostorder(CodeGenModule &CGM,
Douglas Gregor858afb32013-01-14 20:53:57 +0000973 Module *Mod,
Daniel Dunbarf9d03c12013-01-17 01:35:06 +0000974 SmallVectorImpl<llvm::Value *> &Metadata,
Douglas Gregor858afb32013-01-14 20:53:57 +0000975 llvm::SmallPtrSet<Module *, 16> &Visited) {
976 // Import this module's parent.
Stephen Hines176edba2014-12-01 14:53:08 -0800977 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Kleckner3190ca92013-05-08 13:44:39 +0000978 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregor858afb32013-01-14 20:53:57 +0000979 }
980
981 // Import this module's dependencies.
982 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
Stephen Hines176edba2014-12-01 14:53:08 -0800983 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Kleckner3190ca92013-05-08 13:44:39 +0000984 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregor858afb32013-01-14 20:53:57 +0000985 }
986
987 // Add linker options to link against the libraries/frameworks
988 // described by this module.
Reid Kleckner3190ca92013-05-08 13:44:39 +0000989 llvm::LLVMContext &Context = CGM.getLLVMContext();
Douglas Gregor858afb32013-01-14 20:53:57 +0000990 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Kleckner3190ca92013-05-08 13:44:39 +0000991 // Link against a framework. Frameworks are currently Darwin only, so we
992 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregor858afb32013-01-14 20:53:57 +0000993 if (Mod->LinkLibraries[I-1].IsFramework) {
994 llvm::Value *Args[2] = {
995 llvm::MDString::get(Context, "-framework"),
996 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
997 };
998
999 Metadata.push_back(llvm::MDNode::get(Context, Args));
1000 continue;
1001 }
1002
1003 // Link against a library.
Reid Kleckner3190ca92013-05-08 13:44:39 +00001004 llvm::SmallString<24> Opt;
1005 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1006 Mod->LinkLibraries[I-1].Library, Opt);
1007 llvm::Value *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregor858afb32013-01-14 20:53:57 +00001008 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1009 }
1010}
1011
1012void CodeGenModule::EmitModuleLinkOptions() {
1013 // Collect the set of all of the modules we want to visit to emit link
1014 // options, which is essentially the imported modules and all of their
1015 // non-explicit child modules.
1016 llvm::SetVector<clang::Module *> LinkModules;
1017 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1018 SmallVector<clang::Module *, 16> Stack;
1019
1020 // Seed the stack with imported modules.
1021 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
1022 MEnd = ImportedModules.end();
1023 M != MEnd; ++M) {
Stephen Hines176edba2014-12-01 14:53:08 -08001024 if (Visited.insert(*M).second)
Douglas Gregor858afb32013-01-14 20:53:57 +00001025 Stack.push_back(*M);
1026 }
1027
1028 // Find all of the modules to import, making a little effort to prune
1029 // non-leaf modules.
1030 while (!Stack.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00001031 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregor858afb32013-01-14 20:53:57 +00001032
1033 bool AnyChildren = false;
1034
1035 // Visit the submodules of this module.
1036 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1037 SubEnd = Mod->submodule_end();
1038 Sub != SubEnd; ++Sub) {
1039 // Skip explicit children; they need to be explicitly imported to be
1040 // linked against.
1041 if ((*Sub)->IsExplicit)
1042 continue;
1043
Stephen Hines176edba2014-12-01 14:53:08 -08001044 if (Visited.insert(*Sub).second) {
Douglas Gregor858afb32013-01-14 20:53:57 +00001045 Stack.push_back(*Sub);
1046 AnyChildren = true;
1047 }
1048 }
1049
1050 // We didn't find any children, so add this module to the list of
1051 // modules to link against.
1052 if (!AnyChildren) {
1053 LinkModules.insert(Mod);
1054 }
1055 }
1056
1057 // Add link options for all of the imported modules in reverse topological
Reid Kleckner3190ca92013-05-08 13:44:39 +00001058 // order. We don't do anything to try to order import link flags with respect
1059 // to linker options inserted by things like #pragma comment().
Daniel Dunbarf9d03c12013-01-17 01:35:06 +00001060 SmallVector<llvm::Value *, 16> MetadataArgs;
Douglas Gregor858afb32013-01-14 20:53:57 +00001061 Visited.clear();
1062 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
1063 MEnd = LinkModules.end();
1064 M != MEnd; ++M) {
Stephen Hines176edba2014-12-01 14:53:08 -08001065 if (Visited.insert(*M).second)
Reid Kleckner3190ca92013-05-08 13:44:39 +00001066 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
Douglas Gregor858afb32013-01-14 20:53:57 +00001067 }
Daniel Dunbarf9d03c12013-01-17 01:35:06 +00001068 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Kleckner3190ca92013-05-08 13:44:39 +00001069 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregor858afb32013-01-14 20:53:57 +00001070
Daniel Dunbarf9d03c12013-01-17 01:35:06 +00001071 // Add the linker options metadata flag.
1072 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
Reid Kleckner3190ca92013-05-08 13:44:39 +00001073 llvm::MDNode::get(getLLVMContext(),
1074 LinkerOptionsMetadata));
Douglas Gregor858afb32013-01-14 20:53:57 +00001075}
1076
Daniel Dunbar02698712009-02-13 20:29:50 +00001077void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +00001078 // Emit code for any potentially referenced deferred decls. Since a
1079 // previously unused static decl may become used during the generation of code
Nick Lewyckydce67a72011-07-18 05:26:13 +00001080 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00001081
John McCalld5617ee2013-01-25 22:31:03 +00001082 while (true) {
Anders Carlsson046c2942010-04-17 20:15:18 +00001083 if (!DeferredVTables.empty()) {
John McCalld5617ee2013-01-25 22:31:03 +00001084 EmitDeferredVTables();
1085
1086 // Emitting a v-table doesn't directly cause more v-tables to
1087 // become deferred, although it can cause functions to be
1088 // emitted that then need those v-tables.
1089 assert(DeferredVTables.empty());
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00001090 }
1091
John McCalld5617ee2013-01-25 22:31:03 +00001092 // Stop if we're out of both deferred v-tables and deferred declarations.
1093 if (DeferredDeclsToEmit.empty()) break;
1094
Stephen Hines651f13c2014-04-23 16:59:28 -07001095 DeferredGlobal &G = DeferredDeclsToEmit.back();
1096 GlobalDecl D = G.GD;
1097 llvm::GlobalValue *GV = G.GV;
Chris Lattner67b00522009-03-21 09:44:56 +00001098 DeferredDeclsToEmit.pop_back();
1099
Stephen Hines651f13c2014-04-23 16:59:28 -07001100 assert(GV == GetGlobalValue(getMangledName(D)));
John McCallc76702c2010-05-27 01:45:30 +00001101 // Check to see if we've already emitted this. This is necessary
1102 // for a couple of reasons: first, decls can end up in the
1103 // deferred-decls queue multiple times, and second, decls can end
1104 // up with definitions in unusual ways (e.g. by an extern inline
1105 // function acquiring a strong function redefinition). Just
1106 // ignore these cases.
Stephen Hines651f13c2014-04-23 16:59:28 -07001107 if(!GV->isDeclaration())
John McCallc76702c2010-05-27 01:45:30 +00001108 continue;
1109
Chris Lattner67b00522009-03-21 09:44:56 +00001110 // Otherwise, emit the definition and move on to the next one.
Stephen Hines651f13c2014-04-23 16:59:28 -07001111 EmitGlobalDefinition(D, GV);
Chris Lattner67b00522009-03-21 09:44:56 +00001112 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001113}
1114
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001115void CodeGenModule::EmitGlobalAnnotations() {
1116 if (Annotations.empty())
1117 return;
1118
1119 // Create a new global variable for the ConstantStruct in the Module.
1120 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1121 Annotations[0]->getType(), Annotations.size()), Annotations);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001122 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1123 llvm::GlobalValue::AppendingLinkage,
1124 Array, "llvm.global.annotations");
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001125 gv->setSection(AnnotationSection);
1126}
1127
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001128llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramer471b52a2013-11-10 16:55:11 +00001129 llvm::Constant *&AStr = AnnotationStrings[Str];
1130 if (AStr)
1131 return AStr;
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001132
1133 // Not found yet, create a new global.
Chris Lattner94010692012-02-05 02:30:40 +00001134 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001135 auto *gv =
1136 new llvm::GlobalVariable(getModule(), s->getType(), true,
1137 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001138 gv->setSection(AnnotationSection);
1139 gv->setUnnamedAddr(true);
Benjamin Kramer471b52a2013-11-10 16:55:11 +00001140 AStr = gv;
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001141 return gv;
1142}
1143
1144llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1145 SourceManager &SM = getContext().getSourceManager();
1146 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1147 if (PLoc.isValid())
1148 return EmitAnnotationString(PLoc.getFilename());
1149 return EmitAnnotationString(SM.getBufferName(Loc));
1150}
1151
1152llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1153 SourceManager &SM = getContext().getSourceManager();
1154 PresumedLoc PLoc = SM.getPresumedLoc(L);
1155 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1156 SM.getExpansionLineNumber(L);
1157 return llvm::ConstantInt::get(Int32Ty, LineNo);
1158}
1159
Mike Stump1eb44332009-09-09 15:08:12 +00001160llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001161 const AnnotateAttr *AA,
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001162 SourceLocation L) {
1163 // Get the globals for file name, annotation, and the line number.
1164 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1165 *UnitGV = EmitAnnotationUnit(L),
1166 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001167
Daniel Dunbar57d5cee2009-04-14 22:41:13 +00001168 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001169 llvm::Constant *Fields[4] = {
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001170 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1171 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1172 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1173 LineNoCst
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001174 };
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001175 return llvm::ConstantStruct::getAnon(Fields);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001176}
1177
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001178void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1179 llvm::GlobalValue *GV) {
1180 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1181 // Get the struct elements for these annotations.
Stephen Hines651f13c2014-04-23 16:59:28 -07001182 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1183 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001184}
1185
Stephen Hines176edba2014-12-01 14:53:08 -08001186bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1187 SourceLocation Loc) const {
1188 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1189 // Blacklist by function name.
1190 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1191 return true;
1192 // Blacklist by location.
1193 if (!Loc.isInvalid())
1194 return SanitizerBL.isBlacklistedLocation(Loc);
1195 // If location is unknown, this may be a compiler-generated function. Assume
1196 // it's located in the main file.
1197 auto &SM = Context.getSourceManager();
1198 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1199 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1200 }
1201 return false;
1202}
1203
1204bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1205 SourceLocation Loc, QualType Ty,
1206 StringRef Category) const {
1207 // For now globals can be blacklisted only in ASan.
1208 if (!LangOpts.Sanitize.has(SanitizerKind::Address))
1209 return false;
1210 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1211 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1212 return true;
1213 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1214 return true;
1215 // Check global type.
1216 if (!Ty.isNull()) {
1217 // Drill down the array types: if global variable of a fixed type is
1218 // blacklisted, we also don't instrument arrays of them.
1219 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1220 Ty = AT->getElementType();
1221 Ty = Ty.getCanonicalType().getUnqualifiedType();
1222 // We allow to blacklist only record types (classes, structs etc.)
1223 if (Ty->isRecordType()) {
1224 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1225 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1226 return true;
1227 }
1228 }
1229 return false;
1230}
1231
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +00001232bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00001233 // Never defer when EmitAllDecls is specified.
David Blaikie4e4d0842012-03-11 07:00:24 +00001234 if (LangOpts.EmitAllDecls)
Daniel Dunbar73241df2009-02-13 21:18:01 +00001235 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001236
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00001237 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar73241df2009-02-13 21:18:01 +00001238}
1239
Nico Weberc5f80462012-10-11 10:13:44 +00001240llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1241 const CXXUuidofExpr* E) {
1242 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1243 // well-formed.
David Majnemerc80eb462013-08-13 06:32:20 +00001244 StringRef Uuid = E->getUuidAsStringRef(Context);
David Majnemerc8fe0112013-08-09 08:35:59 +00001245 std::string Name = "_GUID_" + Uuid.lower();
1246 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Weberc5f80462012-10-11 10:13:44 +00001247
1248 // Look for an existing global.
1249 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1250 return GV;
1251
Stephen Hines176edba2014-12-01 14:53:08 -08001252 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Weberc5f80462012-10-11 10:13:44 +00001253 assert(Init && "failed to initialize as constant");
1254
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001255 auto *GV = new llvm::GlobalVariable(
David Majnemer8effeda2013-08-15 19:59:14 +00001256 getModule(), Init->getType(),
Reid Klecknerdc1ac5e2013-09-03 21:49:32 +00001257 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
Nico Weberc5f80462012-10-11 10:13:44 +00001258 return GV;
1259}
1260
Rafael Espindola6a836702010-03-04 18:17:24 +00001261llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1262 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1263 assert(AA && "No alias?");
1264
Chris Lattner2acc6e32011-07-18 04:24:23 +00001265 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola6a836702010-03-04 18:17:24 +00001266
Rafael Espindola6a836702010-03-04 18:17:24 +00001267 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +00001268 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001269 if (Entry) {
1270 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1271 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1272 }
Rafael Espindola6a836702010-03-04 18:17:24 +00001273
1274 llvm::Constant *Aliasee;
1275 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +00001276 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1277 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001278 /*ForVTable=*/false);
Rafael Espindola6a836702010-03-04 18:17:24 +00001279 else
John McCallf746aa62010-03-19 23:29:14 +00001280 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001281 llvm::PointerType::getUnqual(DeclTy),
1282 nullptr);
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001283
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001284 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001285 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1286 WeakRefReferences.insert(F);
Rafael Espindola6a836702010-03-04 18:17:24 +00001287
1288 return Aliasee;
1289}
1290
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001291void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001292 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Rafael Espindola6a836702010-03-04 18:17:24 +00001294 // Weak references don't produce any output by themselves.
1295 if (Global->hasAttr<WeakRefAttr>())
1296 return;
1297
Chris Lattnerbd532712009-03-22 21:47:11 +00001298 // If this is an alias definition (which otherwise looks like a declaration)
1299 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001300 if (Global->hasAttr<AliasAttr>())
Rafael Espindola87017a72013-10-22 14:23:09 +00001301 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +00001302
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001303 // If this is CUDA, be selective about which declarations we emit.
David Blaikie4e4d0842012-03-11 07:00:24 +00001304 if (LangOpts.CUDA) {
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001305 if (CodeGenOpts.CUDAIsDevice) {
1306 if (!Global->hasAttr<CUDADeviceAttr>() &&
1307 !Global->hasAttr<CUDAGlobalAttr>() &&
1308 !Global->hasAttr<CUDAConstantAttr>() &&
1309 !Global->hasAttr<CUDASharedAttr>())
1310 return;
1311 } else {
1312 if (!Global->hasAttr<CUDAHostAttr>() && (
1313 Global->hasAttr<CUDADeviceAttr>() ||
1314 Global->hasAttr<CUDAConstantAttr>() ||
1315 Global->hasAttr<CUDASharedAttr>()))
1316 return;
1317 }
1318 }
1319
Chris Lattner67b00522009-03-21 09:44:56 +00001320 // Ignore declarations, they will be emitted on their first use.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001321 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +00001322 // Forward declarations are emitted lazily on first use.
Nick Lewyckydce67a72011-07-18 05:26:13 +00001323 if (!FD->doesThisDeclarationHaveABody()) {
1324 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1325 return;
1326
Chris Lattner5f9e2722011-07-23 10:55:15 +00001327 StringRef MangledName = getMangledName(GD);
Stephen Hines651f13c2014-04-23 16:59:28 -07001328
1329 // Compute the function info and LLVM type.
1330 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1331 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1332
1333 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1334 /*DontDefer=*/false);
Daniel Dunbar73241df2009-02-13 21:18:01 +00001335 return;
Nick Lewyckydce67a72011-07-18 05:26:13 +00001336 }
Daniel Dunbar02698712009-02-13 20:29:50 +00001337 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001338 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001339 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1340
Stephen Hines176edba2014-12-01 14:53:08 -08001341 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1342 !Context.isMSStaticDataMemberInlineDefinition(VD))
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00001343 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +00001344 }
1345
Chris Lattner67b00522009-03-21 09:44:56 +00001346 // Defer code generation when possible if this is a static definition, inline
1347 // function etc. These we only want to emit if they are used.
Chris Lattner4357a822010-04-13 17:39:09 +00001348 if (!MayDeferGeneration(Global)) {
1349 // Emit the definition if it can't be deferred.
1350 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001351 return;
1352 }
John McCallbf40cb52010-07-15 23:40:35 +00001353
1354 // If we're deferring emission of a C++ variable with an
1355 // initializer, remember the order in which it appeared in the file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001356 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCallbf40cb52010-07-15 23:40:35 +00001357 cast<VarDecl>(Global)->hasInit()) {
1358 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001359 CXXGlobalInits.push_back(nullptr);
John McCallbf40cb52010-07-15 23:40:35 +00001360 }
Chris Lattner4357a822010-04-13 17:39:09 +00001361
1362 // If the value has already been used, add it directly to the
1363 // DeferredDeclsToEmit list.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001364 StringRef MangledName = getMangledName(GD);
Stephen Hines651f13c2014-04-23 16:59:28 -07001365 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName))
1366 addDeferredDeclToEmit(GV, GD);
Chris Lattner4357a822010-04-13 17:39:09 +00001367 else {
1368 // Otherwise, remember that we saw a deferred decl with this name. The
1369 // first use of the mangled name will cause it to move into
1370 // DeferredDeclsToEmit.
1371 DeferredDecls[MangledName] = GD;
1372 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +00001373}
1374
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001375namespace {
1376 struct FunctionIsDirectlyRecursive :
1377 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1378 const StringRef Name;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001379 const Builtin::Context &BI;
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001380 bool Result;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001381 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1382 Name(N), BI(C), Result(false) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001383 }
1384 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1385
1386 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001387 const FunctionDecl *FD = E->getDirectCallee();
1388 if (!FD)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001389 return true;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001390 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1391 if (Attr && Name == Attr->getLabel()) {
1392 Result = true;
1393 return false;
1394 }
1395 unsigned BuiltinID = FD->getBuiltinID();
1396 if (!BuiltinID)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001397 return true;
Nick Lewyckyf6b56372012-01-18 03:41:19 +00001398 StringRef BuiltinName = BI.GetName(BuiltinID);
1399 if (BuiltinName.startswith("__builtin_") &&
1400 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001401 Result = true;
1402 return false;
1403 }
1404 return true;
1405 }
1406 };
1407}
1408
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001409// isTriviallyRecursive - Check if this function calls another
1410// decl that, because of the asm attribute or the other decl being a builtin,
1411// ends up pointing to itself.
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001412bool
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001413CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1414 StringRef Name;
1415 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky22afacc2012-01-18 01:50:13 +00001416 // asm labels are a special kind of mangling we have to support.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001417 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1418 if (!Attr)
1419 return false;
1420 Name = Attr->getLabel();
1421 } else {
1422 Name = FD->getName();
1423 }
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001424
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001425 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1426 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001427 return Walker.Result;
1428}
1429
1430bool
Peter Collingbourne144a31f2013-06-05 17:49:37 +00001431CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1432 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001433 return true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001434 const auto *F = cast<FunctionDecl>(GD.getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07001435 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001436 return false;
1437 // PR9614. Avoid cases where the source code is lying to us. An available
1438 // externally function should have an equivalent function somewhere else,
1439 // but a function that calls itself is clearly not equivalent to the real
1440 // implementation.
1441 // This happens in glibc's btowc and in some configure checks.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001442 return !isTriviallyRecursive(F);
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001443}
1444
Adrian Prantl0a050f72013-05-09 23:16:27 +00001445/// If the type for the method's class was generated by
1446/// CGDebugInfo::createContextChain(), the cache contains only a
1447/// limited DIType without any declarations. Since EmitFunctionStart()
1448/// needs to find the canonical declaration for each method, we need
1449/// to construct the complete type prior to emitting the method.
1450void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1451 if (!D->isInstance())
1452 return;
1453
1454 if (CGDebugInfo *DI = getModuleDebugInfo())
1455 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001456 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
Adrian Prantl0a050f72013-05-09 23:16:27 +00001457 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1458 }
1459}
1460
Stephen Hines651f13c2014-04-23 16:59:28 -07001461void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001462 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Dan Gohmancb421fa2010-04-19 16:39:44 +00001464 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +00001465 Context.getSourceManager(),
1466 "Generating code for declaration");
1467
Peter Collingbourne144a31f2013-06-05 17:49:37 +00001468 if (isa<FunctionDecl>(D)) {
Douglas Gregor44eac332010-07-13 06:02:28 +00001469 // At -O0, don't generate IR for functions with available_externally
1470 // linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +00001471 if (!shouldEmitFunction(GD))
Douglas Gregor44eac332010-07-13 06:02:28 +00001472 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +00001473
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001474 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Adrian Prantl0a050f72013-05-09 23:16:27 +00001475 CompleteDIClassType(Method);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001476 // Make sure to emit the definition(s) before we emit the thunks.
1477 // This is necessary for the generation of certain thunks.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001478 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Stephen Hines176edba2014-12-01 14:53:08 -08001479 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001480 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Stephen Hines176edba2014-12-01 14:53:08 -08001481 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001482 else
Stephen Hines651f13c2014-04-23 16:59:28 -07001483 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001484
Douglas Gregor44eac332010-07-13 06:02:28 +00001485 if (Method->isVirtual())
1486 getVTables().EmitThunks(GD);
1487
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001488 return;
Douglas Gregor44eac332010-07-13 06:02:28 +00001489 }
Chris Lattnerb5e81562010-04-13 17:57:11 +00001490
Stephen Hines651f13c2014-04-23 16:59:28 -07001491 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregor44eac332010-07-13 06:02:28 +00001492 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001493
1494 if (const auto *VD = dyn_cast<VarDecl>(D))
Chris Lattnerb5e81562010-04-13 17:57:11 +00001495 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +00001496
David Blaikieb219cfc2011-09-23 05:06:16 +00001497 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001498}
1499
Chris Lattner74391b42009-03-22 21:03:39 +00001500/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1501/// module, create and return an llvm Function with the specified type. If there
1502/// is something in the module with the specified name, return it potentially
1503/// bitcasted to the right type.
1504///
1505/// If D is non-null, it specifies a decl that correspond to this. This is used
1506/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001507llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001508CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001509 llvm::Type *Ty,
Reid Kleckner73701ea2013-07-22 13:07:10 +00001510 GlobalDecl GD, bool ForVTable,
Stephen Hines176edba2014-12-01 14:53:08 -08001511 bool DontDefer, bool IsThunk,
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001512 llvm::AttributeSet ExtraAttrs) {
Reid Kleckner73701ea2013-07-22 13:07:10 +00001513 const Decl *D = GD.getDecl();
1514
Chris Lattner0558e792009-03-21 09:25:43 +00001515 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001516 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +00001517 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00001518 if (WeakRefReferences.erase(Entry)) {
Reid Kleckner73701ea2013-07-22 13:07:10 +00001519 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola6a836702010-03-04 18:17:24 +00001520 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001521 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001522 }
1523
Stephen Hines176edba2014-12-01 14:53:08 -08001524 // Handle dropped DLL attributes.
1525 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1526 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1527
Chris Lattner0558e792009-03-21 09:25:43 +00001528 if (Entry->getType()->getElementType() == Ty)
1529 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Chris Lattner0558e792009-03-21 09:25:43 +00001531 // Make sure the result is of the correct type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001532 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattner0558e792009-03-21 09:25:43 +00001533 }
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Eli Friedman654ad402009-11-09 05:07:37 +00001535 // This function doesn't have a complete type (for example, the return
1536 // type is an incomplete struct). Use a fake type instead, and make
1537 // sure not to try to set attributes.
1538 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +00001539
Chris Lattner2acc6e32011-07-18 04:24:23 +00001540 llvm::FunctionType *FTy;
John McCall784f2112010-04-28 00:00:30 +00001541 if (isa<llvm::FunctionType>(Ty)) {
1542 FTy = cast<llvm::FunctionType>(Ty);
1543 } else {
John McCall0774cb82011-05-15 01:53:33 +00001544 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedman654ad402009-11-09 05:07:37 +00001545 IsIncompleteFunction = true;
1546 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001547
John McCall784f2112010-04-28 00:00:30 +00001548 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +00001549 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001550 MangledName, &getModule());
1551 assert(F->getName() == MangledName && "name was uniqued!");
Reid Kleckner73701ea2013-07-22 13:07:10 +00001552 if (D)
Stephen Hines176edba2014-12-01 14:53:08 -08001553 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001554 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1555 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
Bill Wendling909b6de2013-01-23 00:21:06 +00001556 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1557 llvm::AttributeSet::get(VMContext,
1558 llvm::AttributeSet::FunctionIndex,
1559 B));
1560 }
Eli Friedman654ad402009-11-09 05:07:37 +00001561
Stephen Hines651f13c2014-04-23 16:59:28 -07001562 if (!DontDefer) {
1563 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1564 // each other bottoming out with the base dtor. Therefore we emit non-base
1565 // dtors on usage, even if there is no dtor definition in the TU.
1566 if (D && isa<CXXDestructorDecl>(D) &&
1567 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1568 GD.getDtorType()))
1569 addDeferredDeclToEmit(F, GD);
John McCallbfdcdc82010-12-15 04:00:32 +00001570
Stephen Hines651f13c2014-04-23 16:59:28 -07001571 // This is the first use or definition of a mangled name. If there is a
1572 // deferred decl with this name, remember that we need to emit it at the end
1573 // of the file.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001574 auto DDI = DeferredDecls.find(MangledName);
Stephen Hines651f13c2014-04-23 16:59:28 -07001575 if (DDI != DeferredDecls.end()) {
1576 // Move the potentially referenced deferred decl to the
1577 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1578 // don't need it anymore).
1579 addDeferredDeclToEmit(F, DDI->second);
1580 DeferredDecls.erase(DDI);
Richard Smith3cebc732013-11-05 09:12:18 +00001581
Stephen Hines651f13c2014-04-23 16:59:28 -07001582 // Otherwise, if this is a sized deallocation function, emit a weak
1583 // definition
1584 // for it at the end of the translation unit.
1585 } else if (D && cast<FunctionDecl>(D)
1586 ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
1587 addDeferredDeclToEmit(F, GD);
1588
1589 // Otherwise, there are cases we have to worry about where we're
1590 // using a declaration for which we must emit a definition but where
1591 // we might not find a top-level definition:
1592 // - member functions defined inline in their classes
1593 // - friend functions defined inline in some class
1594 // - special member functions with implicit definitions
1595 // If we ever change our AST traversal to walk into class methods,
1596 // this will be unnecessary.
1597 //
1598 // We also don't emit a definition for a function if it's going to be an
Stephen Hines176edba2014-12-01 14:53:08 -08001599 // entry in a vtable, unless it's already marked as used.
Stephen Hines651f13c2014-04-23 16:59:28 -07001600 } else if (getLangOpts().CPlusPlus && D) {
1601 // Look for a declaration that's lexically in a record.
Stephen Hines176edba2014-12-01 14:53:08 -08001602 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1603 FD = FD->getPreviousDecl()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001604 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Stephen Hines176edba2014-12-01 14:53:08 -08001605 if (FD->doesThisDeclarationHaveABody()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001606 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1607 break;
1608 }
John McCallbfdcdc82010-12-15 04:00:32 +00001609 }
Stephen Hines176edba2014-12-01 14:53:08 -08001610 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001611 }
Chris Lattner67b00522009-03-21 09:44:56 +00001612 }
Mike Stump1eb44332009-09-09 15:08:12 +00001613
John McCall784f2112010-04-28 00:00:30 +00001614 // Make sure the result is of the requested type.
1615 if (!IsIncompleteFunction) {
1616 assert(F->getType()->getElementType() == Ty);
1617 return F;
1618 }
1619
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001620 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCall784f2112010-04-28 00:00:30 +00001621 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +00001622}
1623
Chris Lattner74391b42009-03-22 21:03:39 +00001624/// GetAddrOfFunction - Return the address of the given function. If Ty is
1625/// non-null, then this function will use the specified type if it has to
1626/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001627llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001628 llvm::Type *Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07001629 bool ForVTable,
1630 bool DontDefer) {
Chris Lattner74391b42009-03-22 21:03:39 +00001631 // If there was no specific requested type, just convert it now.
1632 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +00001633 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001634
Chris Lattner5f9e2722011-07-23 10:55:15 +00001635 StringRef MangledName = getMangledName(GD);
Stephen Hines651f13c2014-04-23 16:59:28 -07001636 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
Chris Lattner74391b42009-03-22 21:03:39 +00001637}
Eli Friedman77ba7082008-05-30 19:50:47 +00001638
Chris Lattner74391b42009-03-22 21:03:39 +00001639/// CreateRuntimeFunction - Create a new runtime function with the specified
1640/// type and name.
1641llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001642CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001643 StringRef Name,
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001644 llvm::AttributeSet ExtraAttrs) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001645 llvm::Constant *C =
1646 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Stephen Hines176edba2014-12-01 14:53:08 -08001647 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001648 if (auto *F = dyn_cast<llvm::Function>(C))
John McCallbd7370a2013-02-28 19:01:20 +00001649 if (F->empty())
1650 F->setCallingConv(getRuntimeCC());
1651 return C;
Chris Lattner74391b42009-03-22 21:03:39 +00001652}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001653
Richard Smitha9b21d22012-02-17 06:48:11 +00001654/// isTypeConstant - Determine whether an object of this type can be emitted
1655/// as a constant.
1656///
1657/// If ExcludeCtor is true, the duration when the object's constructor runs
1658/// will not be considered. The caller will need to verify that the object is
1659/// not written to during its construction.
1660bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1661 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +00001662 return false;
Richard Smitha9b21d22012-02-17 06:48:11 +00001663
David Blaikie4e4d0842012-03-11 07:00:24 +00001664 if (Context.getLangOpts().CPlusPlus) {
Richard Smitha9b21d22012-02-17 06:48:11 +00001665 if (const CXXRecordDecl *Record
1666 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1667 return ExcludeCtor && !Record->hasMutableFields() &&
1668 Record->hasTrivialDestructor();
Eli Friedman20e098b2009-12-11 21:23:03 +00001669 }
Richard Smitha9b21d22012-02-17 06:48:11 +00001670
Eli Friedman20e098b2009-12-11 21:23:03 +00001671 return true;
1672}
1673
Chris Lattner74391b42009-03-22 21:03:39 +00001674/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1675/// create and return an llvm GlobalVariable with the specified type. If there
1676/// is something in the module with the specified name, return it potentially
1677/// bitcasted to the right type.
1678///
1679/// If D is non-null, it specifies a decl that correspond to this. This is used
1680/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001681llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001682CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001683 llvm::PointerType *Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001684 const VarDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +00001685 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001686 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +00001687 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00001688 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001689 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001690 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001691 }
1692
Stephen Hines176edba2014-12-01 14:53:08 -08001693 // Handle dropped DLL attributes.
1694 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1695 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1696
Chris Lattner74391b42009-03-22 21:03:39 +00001697 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +00001698 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Chris Lattner99b53612009-03-21 08:03:33 +00001700 // Make sure the result is of the correct type.
Matt Arsenault54307da2013-11-15 02:19:52 +00001701 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1702 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1703
Owen Anderson3c4972d2009-07-29 18:54:39 +00001704 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +00001705 }
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Stephen Hines651f13c2014-04-23 16:59:28 -07001707 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001708 auto *GV = new llvm::GlobalVariable(
1709 getModule(), Ty->getElementType(), false,
1710 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
1711 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Stephen Hines651f13c2014-04-23 16:59:28 -07001712
Chris Lattner67b00522009-03-21 09:44:56 +00001713 // This is the first use or definition of a mangled name. If there is a
1714 // deferred decl with this name, remember that we need to emit it at the end
1715 // of the file.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001716 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001717 if (DDI != DeferredDecls.end()) {
1718 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1719 // list, and remove it from DeferredDecls (since we don't need it anymore).
Stephen Hines651f13c2014-04-23 16:59:28 -07001720 addDeferredDeclToEmit(GV, DDI->second);
Chris Lattner67b00522009-03-21 09:44:56 +00001721 DeferredDecls.erase(DDI);
1722 }
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Chris Lattner99b53612009-03-21 08:03:33 +00001724 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +00001725 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001726 // FIXME: This code is overly simple and should be merged with other global
1727 // handling.
Richard Smitha9b21d22012-02-17 06:48:11 +00001728 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner99b53612009-03-21 08:03:33 +00001729
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001730 setLinkageAndVisibilityForGV(GV, D);
Eli Friedman56ebe502009-04-19 21:05:03 +00001731
Richard Smithb80a16e2013-04-19 16:42:07 +00001732 if (D->getTLSKind()) {
Richard Smithdb4f61f2013-04-22 08:06:17 +00001733 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1734 CXXThreadLocals.push_back(std::make_pair(D, GV));
Hans Wennborgde981f32012-06-28 08:01:44 +00001735 setTLSMode(GV, *D);
Richard Smithb80a16e2013-04-19 16:42:07 +00001736 }
Bill Wendling0cbb3ed2013-11-21 05:19:27 +00001737
1738 // If required by the ABI, treat declarations of static data members with
1739 // inline initializers as definitions.
Stephen Hines176edba2014-12-01 14:53:08 -08001740 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Bill Wendling0cbb3ed2013-11-21 05:19:27 +00001741 EmitGlobalVarDefinition(D);
Stephen Hines176edba2014-12-01 14:53:08 -08001742 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001743
1744 // Handle XCore specific ABI requirements.
1745 if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1746 D->getLanguageLinkage() == CLanguageLinkage &&
1747 D->getType().isConstant(Context) &&
1748 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1749 GV->setSection(".cp.rodata");
Chris Lattner74391b42009-03-22 21:03:39 +00001750 }
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001752 if (AddrSpace != Ty->getAddressSpace())
Matt Arsenault54307da2013-11-15 02:19:52 +00001753 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1754
1755 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001756}
1757
Chris Lattner74391b42009-03-22 21:03:39 +00001758
Anders Carlsson3bd62022011-01-29 18:20:20 +00001759llvm::GlobalVariable *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001760CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001761 llvm::Type *Ty,
Anders Carlsson3bd62022011-01-29 18:20:20 +00001762 llvm::GlobalValue::LinkageTypes Linkage) {
1763 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001764 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlsson3bd62022011-01-29 18:20:20 +00001765
Anders Carlsson3bd62022011-01-29 18:20:20 +00001766 if (GV) {
1767 // Check if the variable has the right type.
1768 if (GV->getType()->getElementType() == Ty)
1769 return GV;
1770
1771 // Because C++ name mangling, the only way we can end up with an already
1772 // existing global with the same name is if it has been declared extern "C".
Nico Weberc5f80462012-10-11 10:13:44 +00001773 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlsson3bd62022011-01-29 18:20:20 +00001774 OldGV = GV;
1775 }
1776
1777 // Create a new variable.
1778 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001779 Linkage, nullptr, Name);
1780
Anders Carlsson3bd62022011-01-29 18:20:20 +00001781 if (OldGV) {
1782 // Replace occurrences of the old variable if needed.
1783 GV->takeName(OldGV);
1784
1785 if (!OldGV->use_empty()) {
1786 llvm::Constant *NewPtrForOldDecl =
1787 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1788 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1789 }
1790
1791 OldGV->eraseFromParent();
1792 }
1793
1794 return GV;
1795}
1796
Chris Lattner74391b42009-03-22 21:03:39 +00001797/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1798/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher0ff258b2012-04-16 23:55:04 +00001799/// then it will be created with the specified type instead of whatever the
Chris Lattner74391b42009-03-22 21:03:39 +00001800/// normal requested type would be.
1801llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001802 llvm::Type *Ty) {
Chris Lattner74391b42009-03-22 21:03:39 +00001803 assert(D->hasGlobalStorage() && "Not a global variable");
1804 QualType ASTTy = D->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001805 if (!Ty)
Chris Lattner74391b42009-03-22 21:03:39 +00001806 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Chris Lattner2acc6e32011-07-18 04:24:23 +00001808 llvm::PointerType *PTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001809 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCallf746aa62010-03-19 23:29:14 +00001810
Chris Lattner5f9e2722011-07-23 10:55:15 +00001811 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001812 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001813}
1814
1815/// CreateRuntimeVariable - Create a new runtime global variable with the
1816/// specified type and name.
1817llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001818CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001819 StringRef Name) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001820 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
Chris Lattner74391b42009-03-22 21:03:39 +00001821}
1822
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001823void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1824 assert(!D->getInit() && "Cannot emit definite definitions here!");
1825
Douglas Gregor7520bd12009-04-21 19:28:58 +00001826 if (MayDeferGeneration(D)) {
1827 // If we have not seen a reference to this variable yet, place it
1828 // into the deferred declarations table to be emitted if needed
1829 // later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001830 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001831 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001832 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001833 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001834 }
1835 }
1836
1837 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001838 EmitGlobalVarDefinition(D);
1839}
1840
Chris Lattner2acc6e32011-07-18 04:24:23 +00001841CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck06f486e2011-01-18 02:01:14 +00001842 return Context.toCharUnitsFromBits(
Micah Villmow25a6a842012-10-08 16:25:52 +00001843 TheDataLayout.getTypeStoreSizeInBits(Ty));
Ken Dyck687cc4a2010-01-26 13:48:07 +00001844}
1845
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001846unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1847 unsigned AddrSpace) {
1848 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1849 if (D->hasAttr<CUDAConstantAttr>())
1850 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1851 else if (D->hasAttr<CUDASharedAttr>())
1852 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1853 else
1854 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1855 }
1856
1857 return AddrSpace;
1858}
1859
Richard Smith00249372013-04-06 05:00:46 +00001860template<typename SomeDecl>
1861void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1862 llvm::GlobalValue *GV) {
1863 if (!getLangOpts().CPlusPlus)
1864 return;
1865
1866 // Must have 'used' attribute, or else inline assembly can't rely on
1867 // the name existing.
1868 if (!D->template hasAttr<UsedAttr>())
1869 return;
1870
1871 // Must have internal linkage and an ordinary name.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001872 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smith00249372013-04-06 05:00:46 +00001873 return;
1874
1875 // Must be in an extern "C" context. Entities declared directly within
1876 // a record are not extern "C" even if the record is in such a context.
Rafael Espindolabc650912013-10-17 15:37:26 +00001877 const SomeDecl *First = D->getFirstDecl();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00001878 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smith00249372013-04-06 05:00:46 +00001879 return;
1880
1881 // OK, this is an internal linkage entity inside an extern "C" linkage
1882 // specification. Make a note of that so we can give it the "expected"
1883 // mangled name if nothing else is using that name.
Richard Smith67972042013-04-06 07:07:44 +00001884 std::pair<StaticExternCMap::iterator, bool> R =
1885 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smith00249372013-04-06 05:00:46 +00001886
1887 // If we have multiple internal linkage entities with the same name
1888 // in extern "C" regions, none of them gets that name.
Richard Smith67972042013-04-06 07:07:44 +00001889 if (!R.second)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001890 R.first->second = nullptr;
Richard Smith00249372013-04-06 05:00:46 +00001891}
1892
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001893void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001894 llvm::Constant *Init = nullptr;
Eli Friedman77ba7082008-05-30 19:50:47 +00001895 QualType ASTTy = D->getType();
Richard Smith7ca48502012-02-13 22:16:19 +00001896 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1897 bool NeedsGlobalCtor = false;
1898 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Richard Smith2d6a5672012-01-14 04:30:29 +00001900 const VarDecl *InitDecl;
1901 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001902
Anders Carlsson3bb92692010-01-26 17:43:42 +00001903 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001904 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001905 // implicitly initialized with { 0 }.
1906 //
1907 // Note that tentative definitions are only emitted at the end of
1908 // a translation unit, so they should never have incomplete
1909 // type. In addition, EmitTentativeDefinition makes sure that we
1910 // never attempt to emit a tentative definition if a real one
1911 // exists. A use may still exists, however, so we still may need
1912 // to do a RAUW.
1913 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00001914 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00001915 } else {
Richard Smith7c3e6152013-06-12 22:31:48 +00001916 initializedGlobalDecl = GlobalDecl(D);
1917 Init = EmitConstantInit(*InitDecl);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001918
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001919 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00001920 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00001921 if (D->getType()->isReferenceType())
1922 T = D->getType();
Richard Smith2d6a5672012-01-14 04:30:29 +00001923
David Blaikie4e4d0842012-03-11 07:00:24 +00001924 if (getLangOpts().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001925 Init = EmitNullConstant(T);
Richard Smith7ca48502012-02-13 22:16:19 +00001926 NeedsGlobalCtor = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001927 } else {
1928 ErrorUnsupported(D, "static initializer");
1929 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1930 }
John McCallbf40cb52010-07-15 23:40:35 +00001931 } else {
1932 // We don't need an initializer, so remove the entry for the delayed
Richard Smith7ca48502012-02-13 22:16:19 +00001933 // initializer position (just in case this entry was delayed) if we
1934 // also don't need to register a destructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00001935 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCallbf40cb52010-07-15 23:40:35 +00001936 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00001937 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001938 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001939
Chris Lattner2acc6e32011-07-18 04:24:23 +00001940 llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00001941 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Chris Lattner570585c2009-03-21 09:16:30 +00001943 // Strip off a bitcast if we got one back.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001944 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001945 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault54307da2013-11-15 02:19:52 +00001946 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1947 // All zero index gep.
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001948 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00001949 Entry = CE->getOperand(0);
1950 }
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Chris Lattner570585c2009-03-21 09:16:30 +00001952 // Entry is now either a Function or GlobalVariable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001953 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Chris Lattner570585c2009-03-21 09:16:30 +00001955 // We have a definition after a declaration with the wrong type.
1956 // We must make a new GlobalVariable* and update everything that used OldGV
1957 // (a declaration or tentative definition) with the new GlobalVariable*
1958 // (which will be a definition).
1959 //
1960 // This happens if there is a prototype for a global (e.g.
1961 // "extern int x[];") and then a definition of a different type (e.g.
1962 // "int x[10];"). This also happens when an initializer has a different type
1963 // from the type of the global (this happens with unions).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001964 if (!GV ||
Chris Lattner570585c2009-03-21 09:16:30 +00001965 GV->getType()->getElementType() != InitType ||
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001966 GV->getType()->getAddressSpace() !=
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001967 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001968
John McCallf746aa62010-03-19 23:29:14 +00001969 // Move the old entry aside so that we'll create a new one.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001970 Entry->setName(StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00001971
Chris Lattner570585c2009-03-21 09:16:30 +00001972 // Make a new global with the correct type, this is now guaranteed to work.
1973 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00001974
Eli Friedman77ba7082008-05-30 19:50:47 +00001975 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00001976 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001977 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00001978 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00001979
1980 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00001981 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00001982 }
Devang Patel8e53e722007-10-26 16:31:40 +00001983
Richard Smith00249372013-04-06 05:00:46 +00001984 MaybeHandleStaticInExternC(D, GV);
1985
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001986 if (D->hasAttr<AnnotateAttr>())
1987 AddGlobalAnnotations(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001988
Chris Lattner88a69ad2007-07-13 05:13:43 +00001989 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001990
1991 // If it is safe to mark the global 'constant', do so now.
Richard Smitha9b21d22012-02-17 06:48:11 +00001992 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1993 isTypeConstant(D->getType(), true));
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Stephen Hines176edba2014-12-01 14:53:08 -08001995 // If it is in a read-only section, mark it 'constant'.
1996 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
1997 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
1998 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
1999 GV->setConstant(true);
2000 }
2001
Ken Dyck8b752f12010-01-27 17:10:57 +00002002 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smitha9b21d22012-02-17 06:48:11 +00002003
Chris Lattner88a69ad2007-07-13 05:13:43 +00002004 // Set the llvm linkage type as appropriate.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002005 llvm::GlobalValue::LinkageTypes Linkage =
2006 getLLVMLinkageVarDefinition(D, GV->isConstant());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002007
2008 // On Darwin, the backing variable for a C++11 thread_local variable always
2009 // has internal linkage; all accesses should just be calls to the
2010 // Itanium-specified entry point, which has the normal linkage of the
2011 // variable.
Stephen Hines176edba2014-12-01 14:53:08 -08002012 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2013 Context.getTargetInfo().getTriple().isMacOSX())
2014 Linkage = llvm::GlobalValue::InternalLinkage;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002015
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002016 GV->setLinkage(Linkage);
Stephen Hines651f13c2014-04-23 16:59:28 -07002017 if (D->hasAttr<DLLImportAttr>())
2018 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2019 else if (D->hasAttr<DLLExportAttr>())
2020 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Stephen Hines176edba2014-12-01 14:53:08 -08002021 else
2022 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Bill Wendling0cbb3ed2013-11-21 05:19:27 +00002023
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002024 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00002025 // common vars aren't constant even if declared const.
2026 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00002027
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002028 setNonAliasAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00002029
Stephen Hines176edba2014-12-01 14:53:08 -08002030 if (D->getTLSKind() && !GV->isThreadLocal()) {
2031 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2032 CXXThreadLocals.push_back(std::make_pair(D, GV));
2033 setTLSMode(GV, *D);
2034 }
2035
John McCall3030eb82010-11-06 09:44:32 +00002036 // Emit the initializer function if necessary.
Richard Smith7ca48502012-02-13 22:16:19 +00002037 if (NeedsGlobalCtor || NeedsGlobalDtor)
2038 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCall3030eb82010-11-06 09:44:32 +00002039
Stephen Hines176edba2014-12-01 14:53:08 -08002040 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany05c5ebc2012-08-21 06:53:28 +00002041
Sanjiv Gupta686226b2008-06-05 08:59:10 +00002042 // Emit global variable debug information.
Eric Christopher73fb3502011-10-13 21:45:18 +00002043 if (CGDebugInfo *DI = getModuleDebugInfo())
Douglas Gregor4cdad312012-10-23 20:05:01 +00002044 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00002045 DI->EmitGlobalVariable(GV, D);
Chris Lattner88a69ad2007-07-13 05:13:43 +00002046}
Reid Spencer5f016e22007-07-11 17:01:13 +00002047
Stephen Hines176edba2014-12-01 14:53:08 -08002048static bool isVarDeclStrongDefinition(const ASTContext &Context,
2049 const VarDecl *D, bool NoCommon) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002050 // Don't give variables common linkage if -fno-common was specified unless it
2051 // was overridden by a NoCommon attribute.
2052 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2053 return true;
2054
2055 // C11 6.9.2/2:
2056 // A declaration of an identifier for an object that has file scope without
2057 // an initializer, and without a storage-class specifier or with the
2058 // storage-class specifier static, constitutes a tentative definition.
2059 if (D->getInit() || D->hasExternalStorage())
2060 return true;
2061
2062 // A variable cannot be both common and exist in a section.
2063 if (D->hasAttr<SectionAttr>())
2064 return true;
2065
2066 // Thread local vars aren't considered common linkage.
2067 if (D->getTLSKind())
2068 return true;
2069
2070 // Tentative definitions marked with WeakImportAttr are true definitions.
2071 if (D->hasAttr<WeakImportAttr>())
2072 return true;
2073
Stephen Hines176edba2014-12-01 14:53:08 -08002074 // Declarations with a required alignment do not have common linakge in MSVC
2075 // mode.
2076 if (Context.getLangOpts().MSVCCompat &&
2077 (Context.isAlignmentRequired(D->getType()) || D->hasAttr<AlignedAttr>()))
2078 return true;
2079
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002080 return false;
2081}
2082
2083llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2084 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002085 if (Linkage == GVA_Internal)
2086 return llvm::Function::InternalLinkage;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002087
2088 if (D->hasAttr<WeakAttr>()) {
2089 if (IsConstantVariable)
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002090 return llvm::GlobalVariable::WeakODRLinkage;
2091 else
2092 return llvm::GlobalVariable::WeakAnyLinkage;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002093 }
2094
2095 // We are guaranteed to have a strong definition somewhere else,
2096 // so we can use available_externally linkage.
2097 if (Linkage == GVA_AvailableExternally)
2098 return llvm::Function::AvailableExternallyLinkage;
2099
2100 // Note that Apple's kernel linker doesn't support symbol
2101 // coalescing, so we need to avoid linkonce and weak linkages there.
2102 // Normally, this means we just map to internal, but for explicit
2103 // instantiations we'll map to external.
2104
2105 // In C++, the compiler has to emit a definition in every translation unit
2106 // that references the function. We should use linkonce_odr because
2107 // a) if all references in this translation unit are optimized away, we
2108 // don't need to codegen it. b) if the function persists, it needs to be
2109 // merged with other definitions. c) C++ has the ODR, so we know the
2110 // definition is dependable.
2111 if (Linkage == GVA_DiscardableODR)
2112 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2113 : llvm::Function::InternalLinkage;
2114
2115 // An explicit instantiation of a template has weak linkage, since
2116 // explicit instantiations can occur in multiple translation units
2117 // and must all be equivalent. However, we are not allowed to
2118 // throw away these explicit instantiations.
2119 if (Linkage == GVA_StrongODR)
2120 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2121 : llvm::Function::ExternalLinkage;
2122
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002123 // C++ doesn't have tentative definitions and thus cannot have common
2124 // linkage.
2125 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Stephen Hines176edba2014-12-01 14:53:08 -08002126 !isVarDeclStrongDefinition(Context, cast<VarDecl>(D),
2127 CodeGenOpts.NoCommon))
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002128 return llvm::GlobalVariable::CommonLinkage;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002129
2130 // selectany symbols are externally visible, so use weak instead of
2131 // linkonce. MSVC optimizes away references to const selectany globals, so
2132 // all definitions should be the same and ODR linkage should be used.
2133 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2134 if (D->hasAttr<SelectAnyAttr>())
2135 return llvm::GlobalVariable::WeakODRLinkage;
2136
2137 // Otherwise, we have strong external linkage.
2138 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002139 return llvm::GlobalVariable::ExternalLinkage;
2140}
2141
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002142llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2143 const VarDecl *VD, bool IsConstant) {
2144 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2145 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2146}
2147
John McCalla923c972012-12-12 22:21:47 +00002148/// Replace the uses of a function that was declared with a non-proto type.
2149/// We want to silently drop extra arguments from call sites
2150static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2151 llvm::Function *newFn) {
2152 // Fast path.
2153 if (old->use_empty()) return;
2154
2155 llvm::Type *newRetTy = newFn->getReturnType();
2156 SmallVector<llvm::Value*, 4> newArgs;
2157
2158 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2159 ui != ue; ) {
2160 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Stephen Hines651f13c2014-04-23 16:59:28 -07002161 llvm::User *user = use->getUser();
John McCalla923c972012-12-12 22:21:47 +00002162
2163 // Recognize and replace uses of bitcasts. Most calls to
2164 // unprototyped functions will use bitcasts.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002165 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCalla923c972012-12-12 22:21:47 +00002166 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2167 replaceUsesOfNonProtoConstant(bitcast, newFn);
2168 continue;
2169 }
2170
2171 // Recognize calls to the function.
2172 llvm::CallSite callSite(user);
2173 if (!callSite) continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07002174 if (!callSite.isCallee(&*use)) continue;
John McCalla923c972012-12-12 22:21:47 +00002175
2176 // If the return types don't match exactly, then we can't
2177 // transform this call unless it's dead.
2178 if (callSite->getType() != newRetTy && !callSite->use_empty())
2179 continue;
2180
2181 // Get the call site's attribute list.
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002182 SmallVector<llvm::AttributeSet, 8> newAttrs;
John McCalla923c972012-12-12 22:21:47 +00002183 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2184
2185 // Collect any return attributes from the call.
Bill Wendlinga37ce612013-01-21 21:57:40 +00002186 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
Bill Wendlinged01f842013-01-21 22:45:00 +00002187 newAttrs.push_back(
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002188 llvm::AttributeSet::get(newFn->getContext(),
2189 oldAttrs.getRetAttributes()));
John McCalla923c972012-12-12 22:21:47 +00002190
2191 // If the function was passed too few arguments, don't transform.
2192 unsigned newNumArgs = newFn->arg_size();
2193 if (callSite.arg_size() < newNumArgs) continue;
2194
2195 // If extra arguments were passed, we silently drop them.
2196 // If any of the types mismatch, we don't transform.
2197 unsigned argNo = 0;
2198 bool dontTransform = false;
2199 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2200 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2201 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2202 dontTransform = true;
2203 break;
2204 }
2205
2206 // Add any parameter attributes.
Bill Wendling89530e42013-01-23 06:15:10 +00002207 if (oldAttrs.hasAttributes(argNo + 1))
2208 newAttrs.
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002209 push_back(llvm::
2210 AttributeSet::get(newFn->getContext(),
2211 oldAttrs.getParamAttributes(argNo + 1)));
John McCalla923c972012-12-12 22:21:47 +00002212 }
2213 if (dontTransform)
2214 continue;
2215
Bill Wendlinge67e4c92013-01-18 21:26:07 +00002216 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002217 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2218 oldAttrs.getFnAttributes()));
John McCalla923c972012-12-12 22:21:47 +00002219
2220 // Okay, we can transform this. Create the new call instruction and copy
2221 // over the required information.
2222 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2223
2224 llvm::CallSite newCall;
2225 if (callSite.isCall()) {
2226 newCall = llvm::CallInst::Create(newFn, newArgs, "",
2227 callSite.getInstruction());
2228 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002229 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCalla923c972012-12-12 22:21:47 +00002230 newCall = llvm::InvokeInst::Create(newFn,
2231 oldInvoke->getNormalDest(),
2232 oldInvoke->getUnwindDest(),
2233 newArgs, "",
2234 callSite.getInstruction());
2235 }
2236 newArgs.clear(); // for the next iteration
2237
2238 if (!newCall->getType()->isVoidTy())
2239 newCall->takeName(callSite.getInstruction());
2240 newCall.setAttributes(
2241 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2242 newCall.setCallingConv(callSite.getCallingConv());
2243
2244 // Finally, remove the old call, replacing any uses with the new one.
2245 if (!callSite->use_empty())
2246 callSite->replaceAllUsesWith(newCall.getInstruction());
2247
2248 // Copy debug location attached to CI.
2249 if (!callSite->getDebugLoc().isUnknown())
2250 newCall->setDebugLoc(callSite->getDebugLoc());
2251 callSite->eraseFromParent();
2252 }
2253}
2254
Chris Lattnerbdb01322009-05-05 06:16:31 +00002255/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2256/// implement a function with no prototype, e.g. "int foo() {}". If there are
2257/// existing call uses of the old function in the module, this adjusts them to
2258/// call the new function directly.
2259///
2260/// This is not just a cleanup: the always_inline pass requires direct calls to
2261/// functions to be able to inline them. If there is a bitcast in the way, it
2262/// won't inline them. Instcombine normally deletes these calls, but it isn't
2263/// run at -O0.
2264static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2265 llvm::Function *NewFn) {
2266 // If we're redefining a global as a function, don't transform it.
John McCalla923c972012-12-12 22:21:47 +00002267 if (!isa<llvm::Function>(Old)) return;
Mike Stump1eb44332009-09-09 15:08:12 +00002268
John McCalla923c972012-12-12 22:21:47 +00002269 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattnerbdb01322009-05-05 06:16:31 +00002270}
2271
Rafael Espindola02503932012-03-08 15:51:03 +00002272void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2273 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2274 // If we have a definition, this might be a deferred decl. If the
2275 // instantiation is explicit, make sure we emit it at the end.
2276 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2277 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00002278
2279 EmitTopLevelDecl(VD);
Rafael Espindola234fe652012-03-05 10:54:55 +00002280}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002281
Stephen Hines651f13c2014-04-23 16:59:28 -07002282void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2283 llvm::GlobalValue *GV) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002284 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalld26bc762011-03-09 04:27:21 +00002285
John McCall1f6f9612011-03-09 08:12:35 +00002286 // Compute the function info and LLVM type.
John McCallde5d3c72012-02-17 03:33:10 +00002287 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2288 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalld26bc762011-03-09 04:27:21 +00002289
Chris Lattner9fa959d2009-05-12 20:58:15 +00002290 // Get or create the prototype for the function.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002291 if (!GV) {
2292 llvm::Constant *C =
2293 GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002295 // Strip off a bitcast if we got one back.
2296 if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
2297 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2298 GV = cast<llvm::GlobalValue>(CE->getOperand(0));
2299 } else {
2300 GV = cast<llvm::GlobalValue>(C);
2301 }
Chris Lattner0558e792009-03-21 09:25:43 +00002302 }
Mike Stump1eb44332009-09-09 15:08:12 +00002303
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002304 if (!GV->isDeclaration()) {
Bill Wendlinga36ef5b2013-11-25 07:42:52 +00002305 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
Stephen Hines176edba2014-12-01 14:53:08 -08002306 GlobalDecl OldGD = Manglings.lookup(GV->getName());
2307 if (auto *Prev = OldGD.getDecl())
2308 getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
Bill Wendlinga36ef5b2013-11-25 07:42:52 +00002309 return;
2310 }
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002312 if (GV->getType()->getElementType() != Ty) {
Daniel Dunbar42745812009-03-09 23:53:08 +00002313 // If the types mismatch then we have to rewrite the definition.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002314 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00002315
Chris Lattner62b33ea2009-03-21 08:38:50 +00002316 // F is the Function* for the one with the wrong type, we must make a new
2317 // Function* and update everything that used F (a declaration) with the new
2318 // Function* (which will be a definition).
2319 //
2320 // This happens if there is a prototype for a function
2321 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00002322 // (e.g. "int f(int x)"). Move the old function aside so that it
2323 // doesn't interfere with GetAddrOfFunction.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002324 GV->setName(StringRef());
2325 auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00002326
John McCalla923c972012-12-12 22:21:47 +00002327 // This might be an implementation of a function without a
2328 // prototype, in which case, try to do special replacement of
2329 // calls which match the new prototype. The really key thing here
2330 // is that we also potentially drop arguments from the call site
2331 // so as to make a direct call, which makes the inliner happier
2332 // and suppresses a number of optimizer warnings (!) about
2333 // dropping arguments.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002334 if (!GV->use_empty()) {
2335 ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
2336 GV->removeDeadConstantUsers();
Chris Lattner9fa959d2009-05-12 20:58:15 +00002337 }
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Chris Lattner62b33ea2009-03-21 08:38:50 +00002339 // Replace uses of F with the Function we will endow with a body.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002340 if (!GV->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002341 llvm::Constant *NewPtrForOldDecl =
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002342 llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
2343 GV->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattnerbdb01322009-05-05 06:16:31 +00002344 }
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Chris Lattner62b33ea2009-03-21 08:38:50 +00002346 // Ok, delete the old function now, which is dead.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002347 GV->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002349 GV = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002350 }
Mike Stump1eb44332009-09-09 15:08:12 +00002351
John McCall112c9672010-11-02 21:04:24 +00002352 // We need to set linkage and visibility on the function before
2353 // generating code for it because various parts of IR generation
2354 // want to propagate this information down (e.g. to local static
2355 // declarations).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002356 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne144a31f2013-06-05 17:49:37 +00002357 setFunctionLinkage(GD, Fn);
Stephen Hines176edba2014-12-01 14:53:08 -08002358 if (D->hasAttr<DLLImportAttr>())
2359 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2360 else if (D->hasAttr<DLLExportAttr>())
2361 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2362 else
2363 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002364
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002365 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Anders Carlsson0ffeaad2011-01-29 19:39:23 +00002366 setGlobalVisibility(Fn, D);
John McCall112c9672010-11-02 21:04:24 +00002367
Richard Smith00249372013-04-06 05:00:46 +00002368 MaybeHandleStaticInExternC(D, Fn);
2369
John McCalld26bc762011-03-09 04:27:21 +00002370 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00002371
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002372 setFunctionDefinitionAttributes(D, Fn);
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002373 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00002374
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002375 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00002376 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002377 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00002378 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge77f68bb2011-09-09 22:41:49 +00002379 if (D->hasAttr<AnnotateAttr>())
2380 AddGlobalAnnotations(D, Fn);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002381}
Stephen Hines651f13c2014-04-23 16:59:28 -07002382
John McCallf746aa62010-03-19 23:29:14 +00002383void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002384 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002385 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00002386 assert(AA && "Not an alias?");
2387
Chris Lattner5f9e2722011-07-23 10:55:15 +00002388 StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00002389
John McCallf746aa62010-03-19 23:29:14 +00002390 // If there is a definition in the module, then it wins over the alias.
2391 // This is dubious, but allow it to be safe. Just ignore the alias.
2392 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2393 if (Entry && !Entry->isDeclaration())
2394 return;
2395
Rafael Espindolad2054982013-10-22 19:26:13 +00002396 Aliases.push_back(GD);
2397
Chris Lattner2acc6e32011-07-18 04:24:23 +00002398 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00002399
2400 // Create a reference to the named value. This ensures that it is emitted
2401 // if a deferred decl.
2402 llvm::Constant *Aliasee;
2403 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +00002404 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson1faa89f2011-02-05 04:35:53 +00002405 /*ForVTable=*/false);
Chris Lattnerbd532712009-03-22 21:47:11 +00002406 else
John McCallf746aa62010-03-19 23:29:14 +00002407 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002408 llvm::PointerType::getUnqual(DeclTy),
Stephen Hines176edba2014-12-01 14:53:08 -08002409 /*D=*/nullptr);
Chris Lattnerbd532712009-03-22 21:47:11 +00002410
2411 // Create the new alias itself, but don't set a name yet.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002412 auto *GA = llvm::GlobalAlias::create(
2413 cast<llvm::PointerType>(Aliasee->getType())->getElementType(), 0,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002414 llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00002415
Chris Lattnerbd532712009-03-22 21:47:11 +00002416 if (Entry) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002417 if (GA->getAliasee() == Entry) {
2418 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2419 return;
2420 }
2421
John McCallf746aa62010-03-19 23:29:14 +00002422 assert(Entry->isDeclaration());
2423
Chris Lattnerbd532712009-03-22 21:47:11 +00002424 // If there is a declaration in the module, then we had an extern followed
2425 // by the alias, as in:
2426 // extern int test6();
2427 // ...
2428 // int test6() __attribute__((alias("test7")));
2429 //
2430 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00002431 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00002432
Owen Anderson3c4972d2009-07-29 18:54:39 +00002433 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00002434 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00002435 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00002436 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00002437 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00002438 }
Mike Stump1eb44332009-09-09 15:08:12 +00002439
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002440 // Set attributes which are particular to an alias; this is a
2441 // specialization of the attributes which may be set on a global
2442 // variable/function.
Stephen Hines176edba2014-12-01 14:53:08 -08002443 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2444 D->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002445 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2446 }
2447
Stephen Hines176edba2014-12-01 14:53:08 -08002448 if (const auto *VD = dyn_cast<VarDecl>(D))
2449 if (VD->getTLSKind())
2450 setTLSMode(GA, *VD);
2451
2452 setAliasAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00002453}
2454
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002455llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002456 ArrayRef<llvm::Type*> Tys) {
Jay Foaddf983a82011-07-12 14:06:48 +00002457 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002458 Tys);
Chris Lattner7acda7c2007-12-18 00:25:38 +00002459}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00002460
Daniel Dunbar1d552912009-07-23 22:52:48 +00002461static llvm::StringMapEntry<llvm::Constant*> &
2462GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2463 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002464 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00002465 bool &IsUTF16,
2466 unsigned &StringLength) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002467 StringRef String = Literal->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002468 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00002469
Daniel Dunbarf015b032009-09-22 10:03:52 +00002470 // Check for simple case.
2471 if (!Literal->containsNonAsciiOrNull()) {
2472 StringLength = NumBytes;
Stephen Hines176edba2014-12-01 14:53:08 -08002473 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarf015b032009-09-22 10:03:52 +00002474 }
2475
Bill Wendling84392d02012-03-30 00:26:17 +00002476 // Otherwise, convert the UTF8 literals into a string of shorts.
2477 IsUTF16 = true;
2478
2479 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divacky31ba6132012-09-06 15:59:27 +00002480 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00002481 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00002483 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2484 &ToPtr, ToPtr + NumBytes,
2485 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00002486
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002487 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00002488 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002489
Bill Wendling84392d02012-03-30 00:26:17 +00002490 // Add an explicit null.
2491 *ToPtr = 0;
Stephen Hines176edba2014-12-01 14:53:08 -08002492 return *Map.insert(std::make_pair(
2493 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2494 (StringLength + 1) * 2),
2495 nullptr)).first;
Daniel Dunbar1d552912009-07-23 22:52:48 +00002496}
2497
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002498static llvm::StringMapEntry<llvm::Constant*> &
2499GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling8322c232012-03-29 22:12:09 +00002500 const StringLiteral *Literal,
2501 unsigned &StringLength) {
2502 StringRef String = Literal->getString();
2503 StringLength = String.size();
Stephen Hines176edba2014-12-01 14:53:08 -08002504 return *Map.insert(std::make_pair(String, nullptr)).first;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002505}
2506
Daniel Dunbar1d552912009-07-23 22:52:48 +00002507llvm::Constant *
2508CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2509 unsigned StringLength = 0;
2510 bool isUTF16 = false;
2511 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00002512 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Micah Villmow25a6a842012-10-08 16:25:52 +00002513 getDataLayout().isLittleEndian(),
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002514 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00002515
Stephen Hines176edba2014-12-01 14:53:08 -08002516 if (auto *C = Entry.second)
Daniel Dunbar1d552912009-07-23 22:52:48 +00002517 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00002518
Chris Lattner8b418682012-02-07 00:39:47 +00002519 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002520 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002521 llvm::Value *V;
2522
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002523 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00002524 if (!CFConstantStringClassRef) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002525 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002526 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002527 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002528 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002529 // Decay array -> ptr
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002530 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2531 CFConstantStringClassRef = V;
Anders Carlssonc9e20912007-08-21 00:21:21 +00002532 }
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002533 else
2534 V = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00002535
Anders Carlssone3daa762008-11-15 18:54:24 +00002536 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002537
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002538 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssone3daa762008-11-15 18:54:24 +00002539
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00002540 llvm::Constant *Fields[4];
Douglas Gregor44b43212008-12-11 16:49:14 +00002541
Anders Carlssonc9e20912007-08-21 00:21:21 +00002542 // Class pointer.
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002543 Fields[0] = cast<llvm::ConstantExpr>(V);
Mike Stump1eb44332009-09-09 15:08:12 +00002544
Anders Carlssonc9e20912007-08-21 00:21:21 +00002545 // Flags.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002546 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002547 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00002548 llvm::ConstantInt::get(Ty, 0x07C8);
2549
Anders Carlssonc9e20912007-08-21 00:21:21 +00002550 // String pointer.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002551 llvm::Constant *C = nullptr;
Bill Wendling84392d02012-03-30 00:26:17 +00002552 if (isUTF16) {
Stephen Hines176edba2014-12-01 14:53:08 -08002553 ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
2554 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
2555 Entry.first().size() / 2);
Bill Wendling84392d02012-03-30 00:26:17 +00002556 C = llvm::ConstantDataArray::get(VMContext, Arr);
2557 } else {
Stephen Hines176edba2014-12-01 14:53:08 -08002558 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling84392d02012-03-30 00:26:17 +00002559 }
Daniel Dunbara9668e02009-04-03 00:57:44 +00002560
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002561 // Note: -fwritable-strings doesn't make the backing store strings of
2562 // CFStrings writable. (See <rdar://problem/10657500>)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002563 auto *GV =
Stephen Hines651f13c2014-04-23 16:59:28 -07002564 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2565 llvm::GlobalValue::PrivateLinkage, C, ".str");
Rafael Espindolab266a1f2011-01-17 16:31:00 +00002566 GV->setUnnamedAddr(true);
Ulrich Weigand6b203512013-05-06 16:23:57 +00002567 // Don't enforce the target's minimum global alignment, since the only use
2568 // of the string is via this class initializer.
Stephen Hines651f13c2014-04-23 16:59:28 -07002569 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2570 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2571 // that changes the section it ends in, which surprises ld64.
Daniel Dunbara9668e02009-04-03 00:57:44 +00002572 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00002573 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2574 GV->setAlignment(Align.getQuantity());
Stephen Hines651f13c2014-04-23 16:59:28 -07002575 GV->setSection("__TEXT,__ustring");
Daniel Dunbarf7e903d2011-04-12 23:30:52 +00002576 } else {
2577 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2578 GV->setAlignment(Align.getQuantity());
Stephen Hines651f13c2014-04-23 16:59:28 -07002579 GV->setSection("__TEXT,__cstring,cstring_literals");
Daniel Dunbara9668e02009-04-03 00:57:44 +00002580 }
Bill Wendling84392d02012-03-30 00:26:17 +00002581
2582 // String.
Jay Foada5c04342011-07-21 14:31:17 +00002583 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson5add6832009-08-16 05:55:31 +00002584
Bill Wendling84392d02012-03-30 00:26:17 +00002585 if (isUTF16)
2586 // Cast the UTF16 string to the correct type.
2587 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2588
Anders Carlssonc9e20912007-08-21 00:21:21 +00002589 // String length.
2590 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00002591 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00002592
Anders Carlssonc9e20912007-08-21 00:21:21 +00002593 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00002594 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00002595 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2596 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00002597 "_unnamed_cfstring_");
Stephen Hines651f13c2014-04-23 16:59:28 -07002598 GV->setSection("__DATA,__cfstring");
Stephen Hines176edba2014-12-01 14:53:08 -08002599 Entry.second = GV;
Mike Stump1eb44332009-09-09 15:08:12 +00002600
Anders Carlsson0c678292007-11-01 00:41:52 +00002601 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00002602}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002603
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00002604llvm::Constant *
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002605CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002606 unsigned StringLength = 0;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002607 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002608 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Stephen Hines176edba2014-12-01 14:53:08 -08002609
2610 if (auto *C = Entry.second)
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002611 return C;
2612
Chris Lattner812234b2012-02-06 22:47:00 +00002613 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002614 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002615 llvm::Value *V;
Fariborz Jahanianec951e02010-04-23 22:33:39 +00002616 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002617 if (!ConstantStringClassRef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002618 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002619 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002620 llvm::Constant *GV;
John McCall260611a2012-06-20 06:18:46 +00002621 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002622 std::string str =
2623 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2624 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002625 GV = getObjCRuntime().GetClassGlobal(str);
2626 // Make sure the result is of the correct type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002627 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002628 V = llvm::ConstantExpr::getBitCast(GV, PTy);
2629 ConstantStringClassRef = V;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002630 } else {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002631 std::string str =
2632 StringClass.empty() ? "_NSConstantStringClassReference"
2633 : "_" + StringClass + "ClassReference";
Chris Lattner2acc6e32011-07-18 04:24:23 +00002634 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002635 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002636 // Decay array -> ptr
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002637 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2638 ConstantStringClassRef = V;
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002639 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002640 }
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002641 else
2642 V = ConstantStringClassRef;
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002643
2644 if (!NSConstantStringType) {
2645 // Construct the type for a constant NSString.
Stephen Hines651f13c2014-04-23 16:59:28 -07002646 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002647 D->startDefinition();
2648
2649 QualType FieldTypes[3];
2650
2651 // const int *isa;
2652 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2653 // const char *str;
2654 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2655 // unsigned int length;
2656 FieldTypes[2] = Context.UnsignedIntTy;
2657
2658 // Create fields
2659 for (unsigned i = 0; i < 3; ++i) {
2660 FieldDecl *Field = FieldDecl::Create(Context, D,
2661 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002662 SourceLocation(), nullptr,
2663 FieldTypes[i], /*TInfo=*/nullptr,
2664 /*BitWidth=*/nullptr,
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002665 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002666 ICIS_NoInit);
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002667 Field->setAccess(AS_public);
2668 D->addDecl(Field);
2669 }
2670
2671 D->completeDefinition();
2672 QualType NSTy = Context.getTagDeclType(D);
2673 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2674 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002675
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00002676 llvm::Constant *Fields[3];
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002677
2678 // Class pointer.
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002679 Fields[0] = cast<llvm::ConstantExpr>(V);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002680
2681 // String pointer.
Chris Lattner94010692012-02-05 02:30:40 +00002682 llvm::Constant *C =
Stephen Hines176edba2014-12-01 14:53:08 -08002683 llvm::ConstantDataArray::getString(VMContext, Entry.first());
2684
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002685 llvm::GlobalValue::LinkageTypes Linkage;
2686 bool isConstant;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002687 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikie4e4d0842012-03-11 07:00:24 +00002688 isConstant = !LangOpts.WritableStrings;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002689
2690 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
2691 Linkage, C, ".str");
Rafael Espindola803d3072011-01-17 22:11:21 +00002692 GV->setUnnamedAddr(true);
Ulrich Weigand6b203512013-05-06 16:23:57 +00002693 // Don't enforce the target's minimum global alignment, since the only use
2694 // of the string is via this class initializer.
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002695 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2696 GV->setAlignment(Align.getQuantity());
Jay Foada5c04342011-07-21 14:31:17 +00002697 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002698
2699 // String length.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002700 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002701 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2702
2703 // The struct.
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002704 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002705 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2706 llvm::GlobalVariable::PrivateLinkage, C,
2707 "_unnamed_nsstring_");
Stephen Hines651f13c2014-04-23 16:59:28 -07002708 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2709 const char *NSStringNonFragileABISection =
2710 "__DATA,__objc_stringobj,regular,no_dead_strip";
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002711 // FIXME. Fix section.
Stephen Hines651f13c2014-04-23 16:59:28 -07002712 GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2713 ? NSStringNonFragileABISection
2714 : NSStringSection);
Stephen Hines176edba2014-12-01 14:53:08 -08002715 Entry.second = GV;
2716
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002717 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00002718}
2719
Douglas Gregor0815b572011-08-09 17:23:49 +00002720QualType CodeGenModule::getObjCFastEnumerationStateType() {
2721 if (ObjCFastEnumerationStateType.isNull()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002722 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor0815b572011-08-09 17:23:49 +00002723 D->startDefinition();
2724
2725 QualType FieldTypes[] = {
2726 Context.UnsignedLongTy,
2727 Context.getPointerType(Context.getObjCIdType()),
2728 Context.getPointerType(Context.UnsignedLongTy),
2729 Context.getConstantArrayType(Context.UnsignedLongTy,
2730 llvm::APInt(32, 5), ArrayType::Normal, 0)
2731 };
2732
2733 for (size_t i = 0; i < 4; ++i) {
2734 FieldDecl *Field = FieldDecl::Create(Context,
2735 D,
2736 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002737 SourceLocation(), nullptr,
2738 FieldTypes[i], /*TInfo=*/nullptr,
2739 /*BitWidth=*/nullptr,
Douglas Gregor0815b572011-08-09 17:23:49 +00002740 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002741 ICIS_NoInit);
Douglas Gregor0815b572011-08-09 17:23:49 +00002742 Field->setAccess(AS_public);
2743 D->addDecl(Field);
2744 }
2745
2746 D->completeDefinition();
2747 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2748 }
2749
2750 return ObjCFastEnumerationStateType;
2751}
2752
Eli Friedman64f45a22011-11-01 02:23:42 +00002753llvm::Constant *
2754CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2755 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2756
2757 // Don't emit it as the address of the string, emit the string data itself
2758 // as an inline array.
Chris Lattner812234b2012-02-06 22:47:00 +00002759 if (E->getCharByteWidth() == 1) {
2760 SmallString<64> Str(E->getString());
2761
2762 // Resize the string to the right size, which is indicated by its type.
2763 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2764 Str.resize(CAT->getSize().getZExtValue());
2765 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2766 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002767
2768 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner94010692012-02-05 02:30:40 +00002769 llvm::Type *ElemTy = AType->getElementType();
2770 unsigned NumElements = AType->getNumElements();
Chris Lattnerd79ed432012-02-06 22:52:04 +00002771
2772 // Wide strings have either 2-byte or 4-byte elements.
2773 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2774 SmallVector<uint16_t, 32> Elements;
2775 Elements.reserve(NumElements);
2776
2777 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2778 Elements.push_back(E->getCodeUnit(i));
2779 Elements.resize(NumElements);
2780 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner94010692012-02-05 02:30:40 +00002781 }
2782
Chris Lattnerd79ed432012-02-06 22:52:04 +00002783 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2784 SmallVector<uint32_t, 32> Elements;
2785 Elements.reserve(NumElements);
2786
2787 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2788 Elements.push_back(E->getCodeUnit(i));
2789 Elements.resize(NumElements);
2790 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedman64f45a22011-11-01 02:23:42 +00002791}
2792
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002793static llvm::GlobalVariable *
2794GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
2795 CodeGenModule &CGM, StringRef GlobalName,
2796 unsigned Alignment) {
2797 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2798 unsigned AddrSpace = 0;
2799 if (CGM.getLangOpts().OpenCL)
2800 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2801
2802 // Create a global variable for this string
2803 auto *GV = new llvm::GlobalVariable(
2804 CGM.getModule(), C->getType(), !CGM.getLangOpts().WritableStrings, LT, C,
2805 GlobalName, nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2806 GV->setAlignment(Alignment);
2807 GV->setUnnamedAddr(true);
2808 return GV;
2809}
2810
Daniel Dunbar61432932008-08-13 23:20:05 +00002811/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2812/// constant array for the given string literal.
Stephen Hines176edba2014-12-01 14:53:08 -08002813llvm::GlobalVariable *
2814CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
2815 StringRef Name) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002816 auto Alignment =
2817 getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
Stephen Hines651f13c2014-04-23 16:59:28 -07002818
Stephen Hines176edba2014-12-01 14:53:08 -08002819 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2820 llvm::GlobalVariable **Entry = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002821 if (!LangOpts.WritableStrings) {
Stephen Hines176edba2014-12-01 14:53:08 -08002822 Entry = &ConstantStringMap[C];
2823 if (auto GV = *Entry) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002824 if (Alignment > GV->getAlignment())
2825 GV->setAlignment(Alignment);
2826 return GV;
Stephen Hines651f13c2014-04-23 16:59:28 -07002827 }
Eli Friedman7eb79c12009-11-16 05:55:46 +00002828 }
Eli Friedman64f45a22011-11-01 02:23:42 +00002829
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002830 SmallString<256> MangledNameBuffer;
2831 StringRef GlobalVariableName;
2832 llvm::GlobalValue::LinkageTypes LT;
Seth Cantrell7d6a7c02012-01-18 12:11:32 +00002833
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002834 // Mangle the string literal if the ABI allows for it. However, we cannot
2835 // do this if we are compiling with ASan or -fwritable-strings because they
2836 // rely on strings having normal linkage.
Stephen Hines176edba2014-12-01 14:53:08 -08002837 if (!LangOpts.WritableStrings &&
2838 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002839 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2840 llvm::raw_svector_ostream Out(MangledNameBuffer);
2841 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2842 Out.flush();
Stephen Hines651f13c2014-04-23 16:59:28 -07002843
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002844 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2845 GlobalVariableName = MangledNameBuffer;
2846 } else {
2847 LT = llvm::GlobalValue::PrivateLinkage;
Stephen Hines176edba2014-12-01 14:53:08 -08002848 GlobalVariableName = Name;
Stephen Hines651f13c2014-04-23 16:59:28 -07002849 }
2850
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002851 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
2852 if (Entry)
Stephen Hines176edba2014-12-01 14:53:08 -08002853 *Entry = GV;
Stephen Hines651f13c2014-04-23 16:59:28 -07002854
Stephen Hines176edba2014-12-01 14:53:08 -08002855 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
2856 QualType());
Eli Friedman64f45a22011-11-01 02:23:42 +00002857 return GV;
Daniel Dunbar61432932008-08-13 23:20:05 +00002858}
2859
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002860/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2861/// array for the given ObjCEncodeExpr node.
Stephen Hines176edba2014-12-01 14:53:08 -08002862llvm::GlobalVariable *
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002863CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2864 std::string Str;
2865 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00002866
2867 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002868}
2869
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002870/// GetAddrOfConstantCString - Returns a pointer to a character array containing
2871/// the literal and a terminating '\0' character.
2872/// The result has pointer to array type.
Stephen Hines176edba2014-12-01 14:53:08 -08002873llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
2874 const std::string &Str, const char *GlobalName, unsigned Alignment) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002875 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002876 if (Alignment == 0) {
2877 Alignment = getContext()
2878 .getAlignOfGlobalVarInChars(getContext().CharTy)
2879 .getQuantity();
2880 }
2881
Stephen Hines176edba2014-12-01 14:53:08 -08002882 llvm::Constant *C =
2883 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
2884
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002885 // Don't share any string literals if strings aren't constant.
Stephen Hines176edba2014-12-01 14:53:08 -08002886 llvm::GlobalVariable **Entry = nullptr;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002887 if (!LangOpts.WritableStrings) {
Stephen Hines176edba2014-12-01 14:53:08 -08002888 Entry = &ConstantStringMap[C];
2889 if (auto GV = *Entry) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002890 if (Alignment > GV->getAlignment())
2891 GV->setAlignment(Alignment);
2892 return GV;
2893 }
2894 }
2895
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002896 // Get the default prefix if a name wasn't specified.
2897 if (!GlobalName)
2898 GlobalName = ".str";
2899 // Create a global variable for this.
2900 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
2901 GlobalName, Alignment);
2902 if (Entry)
Stephen Hines176edba2014-12-01 14:53:08 -08002903 *Entry = GV;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002904 return GV;
Daniel Dunbar61432932008-08-13 23:20:05 +00002905}
Daniel Dunbar41071de2008-08-15 23:26:23 +00002906
Richard Smith211c8dd2013-06-05 00:46:14 +00002907llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smith3282b842013-06-14 03:07:01 +00002908 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smith211c8dd2013-06-05 00:46:14 +00002909 assert((E->getStorageDuration() == SD_Static ||
2910 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002911 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smith211c8dd2013-06-05 00:46:14 +00002912
2913 // If we're not materializing a subobject of the temporary, keep the
2914 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smith3282b842013-06-14 03:07:01 +00002915 QualType MaterializedType = Init->getType();
2916 if (Init == E->GetTemporaryExpr())
2917 MaterializedType = E->getType();
Richard Smith211c8dd2013-06-05 00:46:14 +00002918
2919 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2920 if (Slot)
2921 return Slot;
2922
2923 // FIXME: If an externally-visible declaration extends multiple temporaries,
2924 // we need to give each temporary the same name in every translation unit (and
2925 // we also need to make the temporaries externally-visible).
2926 SmallString<256> Name;
2927 llvm::raw_svector_ostream Out(Name);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002928 getCXXABI().getMangleContext().mangleReferenceTemporary(
2929 VD, E->getManglingNumber(), Out);
Richard Smith211c8dd2013-06-05 00:46:14 +00002930 Out.flush();
2931
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002932 APValue *Value = nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00002933 if (E->getStorageDuration() == SD_Static) {
Richard Smith3282b842013-06-14 03:07:01 +00002934 // We might have a cached constant initializer for this temporary. Note
2935 // that this might have a different value from the value computed by
2936 // evaluating the initializer if the surrounding constant expression
2937 // modifies the temporary.
Richard Smith211c8dd2013-06-05 00:46:14 +00002938 Value = getContext().getMaterializedTemporaryValue(E, false);
2939 if (Value && Value->isUninit())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002940 Value = nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00002941 }
2942
Richard Smith3282b842013-06-14 03:07:01 +00002943 // Try evaluating it now, it might have a constant initializer.
2944 Expr::EvalResult EvalResult;
2945 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2946 !EvalResult.hasSideEffects())
2947 Value = &EvalResult.Val;
2948
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002949 llvm::Constant *InitialValue = nullptr;
Richard Smith3282b842013-06-14 03:07:01 +00002950 bool Constant = false;
2951 llvm::Type *Type;
Richard Smith211c8dd2013-06-05 00:46:14 +00002952 if (Value) {
2953 // The temporary has a constant initializer, use it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002954 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
Richard Smith3282b842013-06-14 03:07:01 +00002955 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2956 Type = InitialValue->getType();
Richard Smith211c8dd2013-06-05 00:46:14 +00002957 } else {
Richard Smith3282b842013-06-14 03:07:01 +00002958 // No initializer, the initialization will be provided when we
Richard Smith211c8dd2013-06-05 00:46:14 +00002959 // initialize the declaration which performed lifetime extension.
Richard Smith3282b842013-06-14 03:07:01 +00002960 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smith211c8dd2013-06-05 00:46:14 +00002961 }
2962
2963 // Create a global variable for this lifetime-extended temporary.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002964 llvm::GlobalValue::LinkageTypes Linkage =
2965 getLLVMLinkageVarDefinition(VD, Constant);
2966 // There is no need for this temporary to have global linkage if the global
2967 // variable has external linkage.
2968 if (Linkage == llvm::GlobalVariable::ExternalLinkage)
2969 Linkage = llvm::GlobalVariable::PrivateLinkage;
2970 unsigned AddrSpace = GetGlobalVarAddressSpace(
2971 VD, getContext().getTargetAddressSpace(MaterializedType));
2972 auto *GV = new llvm::GlobalVariable(
2973 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
2974 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2975 AddrSpace);
2976 setGlobalVisibility(GV, VD);
Richard Smith211c8dd2013-06-05 00:46:14 +00002977 GV->setAlignment(
Richard Smith3282b842013-06-14 03:07:01 +00002978 getContext().getTypeAlignInChars(MaterializedType).getQuantity());
Richard Smith211c8dd2013-06-05 00:46:14 +00002979 if (VD->getTLSKind())
2980 setTLSMode(GV, *VD);
2981 Slot = GV;
2982 return GV;
2983}
2984
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002985/// EmitObjCPropertyImplementations - Emit information for synthesized
2986/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00002987void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002988 ObjCImplementationDecl *D) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002989 for (const auto *PID : D->property_impls()) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002990 // Dynamic is just for type-checking.
2991 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2992 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2993
2994 // Determine which methods need to be implemented, some may have
Jordan Rose1e4691b2012-10-10 16:42:25 +00002995 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002996 // we want, that just indicates if the decl came from a
2997 // property. What we want to know is if the method is defined in
2998 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002999 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00003000 CodeGenFunction(*this).GenerateObjCGetter(
3001 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003002 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003003 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00003004 CodeGenFunction(*this).GenerateObjCSetter(
3005 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003006 }
3007 }
3008}
3009
John McCalle81ac692011-03-22 07:05:39 +00003010static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00003011 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3012 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00003013 ivar; ivar = ivar->getNextIvar())
3014 if (ivar->getType().isDestructedType())
3015 return true;
3016
3017 return false;
3018}
3019
Stephen Hines176edba2014-12-01 14:53:08 -08003020static bool AllTrivialInitializers(CodeGenModule &CGM,
3021 ObjCImplementationDecl *D) {
3022 CodeGenFunction CGF(CGM);
3023 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3024 E = D->init_end(); B != E; ++B) {
3025 CXXCtorInitializer *CtorInitExp = *B;
3026 Expr *Init = CtorInitExp->getInit();
3027 if (!CGF.isTrivialInitializer(Init))
3028 return false;
3029 }
3030 return true;
3031}
3032
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003033/// EmitObjCIvarInitializations - Emit information for ivar initialization
3034/// for an implementation.
3035void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCalle81ac692011-03-22 07:05:39 +00003036 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3037 if (needsDestructMethod(D)) {
3038 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3039 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3040 ObjCMethodDecl *DTORMethod =
3041 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003042 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003043 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00003044 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003045 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCalle81ac692011-03-22 07:05:39 +00003046 D->addInstanceMethod(DTORMethod);
3047 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCallb03527a2012-10-17 04:53:31 +00003048 D->setHasDestructors(true);
John McCalle81ac692011-03-22 07:05:39 +00003049 }
3050
3051 // If the implementation doesn't have any ivar initializers, we don't need
3052 // a .cxx_construct.
Stephen Hines176edba2014-12-01 14:53:08 -08003053 if (D->getNumIvarInitializers() == 0 ||
3054 AllTrivialInitializers(*this, D))
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003055 return;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003056
John McCalle81ac692011-03-22 07:05:39 +00003057 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3058 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003059 // The constructor returns 'self'.
3060 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3061 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00003062 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00003063 cxxSelector,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003064 getContext().getObjCIdType(),
3065 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003066 /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00003067 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003068 /*isImplicitlyDeclared=*/true,
3069 /*isDefined=*/false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003070 ObjCMethodDecl::Required);
3071 D->addInstanceMethod(CTORMethod);
3072 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCallb03527a2012-10-17 04:53:31 +00003073 D->setHasNonZeroConstructors(true);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003074}
3075
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003076/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00003077void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003078 for (auto *I : ND->decls()) {
3079 if (const auto *VD = dyn_cast<VarDecl>(I))
David Blaikie0d520f72013-09-04 21:07:37 +00003080 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3081 VD->getTemplateSpecializationKind() != TSK_Undeclared)
3082 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07003083 EmitTopLevelDecl(I);
David Blaikie0d520f72013-09-04 21:07:37 +00003084 }
Anders Carlsson984e0682009-04-01 00:58:25 +00003085}
3086
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003087// EmitLinkageSpec - Emit all declarations in a linkage spec.
3088void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00003089 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3090 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003091 ErrorUnsupported(LSD, "linkage spec");
3092 return;
3093 }
3094
Stephen Hines651f13c2014-04-23 16:59:28 -07003095 for (auto *I : LSD->decls()) {
Fariborz Jahanian107dae42012-10-26 22:20:25 +00003096 // Meta-data for ObjC class includes references to implemented methods.
3097 // Generate class's method definitions first.
Stephen Hines651f13c2014-04-23 16:59:28 -07003098 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3099 for (auto *M : OID->methods())
3100 EmitTopLevelDecl(M);
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00003101 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003102 EmitTopLevelDecl(I);
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00003103 }
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003104}
3105
Daniel Dunbar41071de2008-08-15 23:26:23 +00003106/// EmitTopLevelDecl - Emit code for a single top level declaration.
3107void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor16e8be22009-06-29 17:30:29 +00003108 // Ignore dependent declarations.
3109 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3110 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003111
Daniel Dunbar41071de2008-08-15 23:26:23 +00003112 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00003113 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00003114 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00003115 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00003116 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00003117 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3118 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor16e8be22009-06-29 17:30:29 +00003119 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003120
Anders Carlsson555b4bb2009-09-10 23:43:36 +00003121 EmitGlobal(cast<FunctionDecl>(D));
Stephen Hines176edba2014-12-01 14:53:08 -08003122 // Always provide some coverage mapping
3123 // even for the functions that aren't emitted.
3124 AddDeferredUnusedCoverageMapping(D);
Anders Carlsson555b4bb2009-09-10 23:43:36 +00003125 break;
Larisse Voufoef4579c2013-08-06 01:03:05 +00003126
Daniel Dunbar41071de2008-08-15 23:26:23 +00003127 case Decl::Var:
Larisse Voufoef4579c2013-08-06 01:03:05 +00003128 // Skip variable templates
3129 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3130 return;
3131 case Decl::VarTemplateSpecialization:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00003132 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003133 break;
3134
John McCall26fbc722011-04-12 01:01:22 +00003135 // Indirect fields from global anonymous structs and unions can be
3136 // ignored; only the actual variable requires IR gen support.
3137 case Decl::IndirectField:
3138 break;
3139
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003140 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00003141 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00003142 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003143 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003144 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00003145 case Decl::UsingShadow:
Douglas Gregor127102b2009-06-29 20:59:39 +00003146 case Decl::ClassTemplate:
Larisse Voufoef4579c2013-08-06 01:03:05 +00003147 case Decl::VarTemplate:
3148 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor127102b2009-06-29 20:59:39 +00003149 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003150 case Decl::TypeAliasTemplate:
Douglas Gregor6a576ab2011-06-05 05:04:23 +00003151 case Decl::Block:
Michael Han684aa732013-02-22 17:15:32 +00003152 case Decl::Empty:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003153 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07003154 case Decl::Using: // using X; [C++]
3155 if (CGDebugInfo *DI = getModuleDebugInfo())
3156 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3157 return;
David Blaikiefc46ebc2013-05-20 22:50:41 +00003158 case Decl::NamespaceAlias:
3159 if (CGDebugInfo *DI = getModuleDebugInfo())
3160 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3161 return;
David Blaikie1601a4a2013-04-26 05:41:06 +00003162 case Decl::UsingDirective: // using namespace X; [C++]
3163 if (CGDebugInfo *DI = getModuleDebugInfo())
3164 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3165 return;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003166 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00003167 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00003168 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3169 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson1fe598c2009-11-24 05:16:24 +00003170 return;
3171
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +00003172 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003173 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00003174 case Decl::CXXDestructor:
Francois Pichet8387e2a2011-04-22 22:18:13 +00003175 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3176 return;
Reid Klecknera4130ba2013-07-22 13:51:44 +00003177 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlsson27ae5362009-04-17 01:58:57 +00003178 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00003179
3180 case Decl::StaticAssert:
3181 // Nothing to do.
3182 break;
3183
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003184 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00003185
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00003186 // Forward declarations, no (immediate) code generation.
Chris Lattner285d0db2009-04-01 02:36:43 +00003187 case Decl::ObjCInterface:
Eric Christopherffb0c3a2012-07-19 22:22:55 +00003188 case Decl::ObjCCategory:
Chris Lattner285d0db2009-04-01 02:36:43 +00003189 break;
3190
Douglas Gregorbd9482d2012-01-01 21:23:57 +00003191 case Decl::ObjCProtocol: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003192 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorbd9482d2012-01-01 21:23:57 +00003193 if (Proto->isThisDeclarationADefinition())
3194 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbar41071de2008-08-15 23:26:23 +00003195 break;
Douglas Gregorbd9482d2012-01-01 21:23:57 +00003196 }
3197
Daniel Dunbar41071de2008-08-15 23:26:23 +00003198 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003199 // Categories have properties but don't support synthesize so we
3200 // can ignore them here.
Peter Collingbournee9265232011-07-27 20:29:46 +00003201 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003202 break;
3203
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003204 case Decl::ObjCImplementation: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003205 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003206 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003207 EmitObjCIvarInitializations(OMD);
Peter Collingbournee9265232011-07-27 20:29:46 +00003208 ObjCRuntime->GenerateClass(OMD);
Eric Christopherbe6c6862012-04-11 05:56:05 +00003209 // Emit global variable debug information.
3210 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov96a66392012-12-03 18:28:12 +00003211 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3212 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3213 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbar41071de2008-08-15 23:26:23 +00003214 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003215 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00003216 case Decl::ObjCMethod: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003217 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbar41071de2008-08-15 23:26:23 +00003218 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003219 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00003220 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3221 break;
3222 }
Mike Stump1eb44332009-09-09 15:08:12 +00003223 case Decl::ObjCCompatibleAlias:
David Chisnall29254f42012-01-31 18:59:20 +00003224 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003225 break;
3226
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003227 case Decl::LinkageSpec:
3228 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003229 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00003230
3231 case Decl::FileScopeAsm: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003232 auto *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003233 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00003234
Daniel Dunbar41071de2008-08-15 23:26:23 +00003235 const std::string &S = getModule().getModuleInlineAsm();
3236 if (S.empty())
3237 getModule().setModuleInlineAsm(AsmString);
Joerg Sonnenberger8ce9cca2012-08-10 10:57:52 +00003238 else if (S.end()[-1] == '\n')
Chris Lattner9f5bff02011-07-23 20:04:25 +00003239 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00003240 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00003241 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00003242 break;
3243 }
Mike Stump1eb44332009-09-09 15:08:12 +00003244
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003245 case Decl::Import: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003246 auto *Import = cast<ImportDecl>(D);
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003247
3248 // Ignore import declarations that come from imported modules.
3249 if (clang::Module *Owner = Import->getOwningModule()) {
3250 if (getLangOpts().CurrentModule.empty() ||
3251 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3252 break;
3253 }
3254
Douglas Gregor858afb32013-01-14 20:53:57 +00003255 ImportedModules.insert(Import->getImportedModule());
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003256 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07003257 }
3258
Stephen Hines176edba2014-12-01 14:53:08 -08003259 case Decl::OMPThreadPrivate:
3260 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3261 break;
3262
Stephen Hines651f13c2014-04-23 16:59:28 -07003263 case Decl::ClassTemplateSpecialization: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003264 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
Stephen Hines651f13c2014-04-23 16:59:28 -07003265 if (DebugInfo &&
3266 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition)
3267 DebugInfo->completeTemplateDefinition(*Spec);
3268 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003269
Mike Stump1eb44332009-09-09 15:08:12 +00003270 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00003271 // Make sure we handled everything we should, every other kind is a
3272 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3273 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00003274 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3275 }
3276}
John McCall744016d2010-07-06 23:57:41 +00003277
Stephen Hines176edba2014-12-01 14:53:08 -08003278void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3279 // Do we need to generate coverage mapping?
3280 if (!CodeGenOpts.CoverageMapping)
3281 return;
3282 switch (D->getKind()) {
3283 case Decl::CXXConversion:
3284 case Decl::CXXMethod:
3285 case Decl::Function:
3286 case Decl::ObjCMethod:
3287 case Decl::CXXConstructor:
3288 case Decl::CXXDestructor: {
3289 if (!cast<FunctionDecl>(D)->hasBody())
3290 return;
3291 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3292 if (I == DeferredEmptyCoverageMappingDecls.end())
3293 DeferredEmptyCoverageMappingDecls[D] = true;
3294 break;
3295 }
3296 default:
3297 break;
3298 };
3299}
3300
3301void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3302 // Do we need to generate coverage mapping?
3303 if (!CodeGenOpts.CoverageMapping)
3304 return;
3305 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3306 if (Fn->isTemplateInstantiation())
3307 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3308 }
3309 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3310 if (I == DeferredEmptyCoverageMappingDecls.end())
3311 DeferredEmptyCoverageMappingDecls[D] = false;
3312 else
3313 I->second = false;
3314}
3315
3316void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3317 std::vector<const Decl *> DeferredDecls;
3318 for (const auto I : DeferredEmptyCoverageMappingDecls) {
3319 if (!I.second)
3320 continue;
3321 DeferredDecls.push_back(I.first);
3322 }
3323 // Sort the declarations by their location to make sure that the tests get a
3324 // predictable order for the coverage mapping for the unused declarations.
3325 if (CodeGenOpts.DumpCoverageMapping)
3326 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3327 [] (const Decl *LHS, const Decl *RHS) {
3328 return LHS->getLocStart() < RHS->getLocStart();
3329 });
3330 for (const auto *D : DeferredDecls) {
3331 switch (D->getKind()) {
3332 case Decl::CXXConversion:
3333 case Decl::CXXMethod:
3334 case Decl::Function:
3335 case Decl::ObjCMethod: {
3336 CodeGenPGO PGO(*this);
3337 GlobalDecl GD(cast<FunctionDecl>(D));
3338 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3339 getFunctionLinkage(GD));
3340 break;
3341 }
3342 case Decl::CXXConstructor: {
3343 CodeGenPGO PGO(*this);
3344 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3345 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3346 getFunctionLinkage(GD));
3347 break;
3348 }
3349 case Decl::CXXDestructor: {
3350 CodeGenPGO PGO(*this);
3351 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3352 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3353 getFunctionLinkage(GD));
3354 break;
3355 }
3356 default:
3357 break;
3358 };
3359 }
3360}
3361
John McCall744016d2010-07-06 23:57:41 +00003362/// Turns the given pointer into a constant.
3363static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3364 const void *Ptr) {
3365 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2acc6e32011-07-18 04:24:23 +00003366 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall744016d2010-07-06 23:57:41 +00003367 return llvm::ConstantInt::get(i64, PtrInt);
3368}
3369
3370static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3371 llvm::NamedMDNode *&GlobalMetadata,
3372 GlobalDecl D,
3373 llvm::GlobalValue *Addr) {
3374 if (!GlobalMetadata)
3375 GlobalMetadata =
3376 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3377
3378 // TODO: should we report variant information for ctors/dtors?
3379 llvm::Value *Ops[] = {
3380 Addr,
3381 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3382 };
Jay Foad6f141652011-04-21 19:59:12 +00003383 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall744016d2010-07-06 23:57:41 +00003384}
3385
Richard Smith00249372013-04-06 05:00:46 +00003386/// For each function which is declared within an extern "C" region and marked
3387/// as 'used', but has internal linkage, create an alias from the unmangled
3388/// name to the mangled name if possible. People expect to be able to refer
3389/// to such functions with an unmangled name from inline assembly within the
3390/// same translation unit.
3391void CodeGenModule::EmitStaticExternCAliases() {
Richard Smith84083b72013-04-13 01:28:18 +00003392 for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3393 E = StaticExternCValues.end();
3394 I != E; ++I) {
3395 IdentifierInfo *Name = I->first;
3396 llvm::GlobalValue *Val = I->second;
Richard Smith67972042013-04-06 07:07:44 +00003397 if (Val && !getModule().getNamedValue(Name->getName()))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003398 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith67972042013-04-06 07:07:44 +00003399 }
Richard Smith00249372013-04-06 05:00:46 +00003400}
3401
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003402bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3403 GlobalDecl &Result) const {
3404 auto Res = Manglings.find(MangledName);
3405 if (Res == Manglings.end())
3406 return false;
3407 Result = Res->getValue();
3408 return true;
3409}
3410
John McCall744016d2010-07-06 23:57:41 +00003411/// Emits metadata nodes associating all the global values in the
3412/// current module with the Decls they came from. This is useful for
3413/// projects using IR gen as a subroutine.
3414///
3415/// Since there's currently no way to associate an MDNode directly
3416/// with an llvm::GlobalValue, we create a global named metadata
3417/// with the name 'clang.global.decl.ptrs'.
3418void CodeGenModule::EmitDeclMetadata() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003419 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall744016d2010-07-06 23:57:41 +00003420
3421 // StaticLocalDeclMap
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003422 for (auto &I : MangledDeclNames) {
3423 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3424 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall744016d2010-07-06 23:57:41 +00003425 }
3426}
3427
3428/// Emits metadata nodes for all the local variables in the current
3429/// function.
3430void CodeGenFunction::EmitDeclMetadata() {
3431 if (LocalDeclMap.empty()) return;
3432
3433 llvm::LLVMContext &Context = getLLVMContext();
3434
3435 // Find the unique metadata ID for this name.
3436 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3437
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003438 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall744016d2010-07-06 23:57:41 +00003439
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003440 for (auto &I : LocalDeclMap) {
3441 const Decl *D = I.first;
3442 llvm::Value *Addr = I.second;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003443 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall744016d2010-07-06 23:57:41 +00003444 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foad6f141652011-04-21 19:59:12 +00003445 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003446 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall744016d2010-07-06 23:57:41 +00003447 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3448 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3449 }
3450 }
3451}
Daniel Dunbar673431a2010-07-16 00:00:15 +00003452
Rafael Espindola9686f122013-10-16 19:28:50 +00003453void CodeGenModule::EmitVersionIdentMetadata() {
3454 llvm::NamedMDNode *IdentMetadata =
3455 TheModule.getOrInsertNamedMetadata("llvm.ident");
3456 std::string Version = getClangFullVersion();
3457 llvm::LLVMContext &Ctx = TheModule.getContext();
3458
3459 llvm::Value *IdentNode[] = {
3460 llvm::MDString::get(Ctx, Version)
3461 };
3462 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3463}
3464
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003465void CodeGenModule::EmitTargetMetadata() {
Stephen Hines176edba2014-12-01 14:53:08 -08003466 // Warning, new MangledDeclNames may be appended within this loop.
3467 // We rely on MapVector insertions adding new elements to the end
3468 // of the container.
3469 // FIXME: Move this loop into the one target that needs it, and only
3470 // loop over those declarations for which we couldn't emit the target
3471 // metadata when we emitted the declaration.
3472 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
3473 auto Val = *(MangledDeclNames.begin() + I);
3474 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3475 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003476 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3477 }
3478}
3479
Nick Lewycky3dc05412011-05-05 00:08:20 +00003480void CodeGenModule::EmitCoverageFile() {
3481 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky5ea4f442011-05-04 20:46:58 +00003482 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3483 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3484 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky3dc05412011-05-05 00:08:20 +00003485 llvm::MDString *CoverageFile =
3486 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky5ea4f442011-05-04 20:46:58 +00003487 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3488 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky3dc05412011-05-05 00:08:20 +00003489 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky5ea4f442011-05-04 20:46:58 +00003490 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3491 GCov->addOperand(N);
3492 }
3493 }
3494 }
3495}
Nico Weberc5f80462012-10-11 10:13:44 +00003496
Stephen Hines176edba2014-12-01 14:53:08 -08003497llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Weberc5f80462012-10-11 10:13:44 +00003498 // Sema has checked that all uuid strings are of the form
3499 // "12345678-1234-1234-1234-1234567890ab".
3500 assert(Uuid.size() == 36);
David Majnemer8effeda2013-08-15 19:59:14 +00003501 for (unsigned i = 0; i < 36; ++i) {
3502 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3503 else assert(isHexDigit(Uuid[i]));
Nico Weberc5f80462012-10-11 10:13:44 +00003504 }
Nico Weberc5f80462012-10-11 10:13:44 +00003505
Stephen Hines176edba2014-12-01 14:53:08 -08003506 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemer8effeda2013-08-15 19:59:14 +00003507 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Weberc5f80462012-10-11 10:13:44 +00003508
David Majnemer8effeda2013-08-15 19:59:14 +00003509 llvm::Constant *Field3[8];
3510 for (unsigned Idx = 0; Idx < 8; ++Idx)
3511 Field3[Idx] = llvm::ConstantInt::get(
3512 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3513
3514 llvm::Constant *Fields[4] = {
3515 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
3516 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
3517 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3518 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3519 };
3520
3521 return llvm::ConstantStruct::getAnon(Fields);
Nico Weberc5f80462012-10-11 10:13:44 +00003522}
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003523
3524llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
3525 bool ForEH) {
3526 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
3527 // FIXME: should we even be calling this method if RTTI is disabled
3528 // and it's not for EH?
3529 if (!ForEH && !getLangOpts().RTTI)
3530 return llvm::Constant::getNullValue(Int8PtrTy);
3531
3532 if (ForEH && Ty->isObjCObjectPointerType() &&
3533 LangOpts.ObjCRuntime.isGNUFamily())
3534 return ObjCRuntime->GetEHType(Ty);
3535
3536 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
3537}
3538
Stephen Hines176edba2014-12-01 14:53:08 -08003539void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
3540 for (auto RefExpr : D->varlists()) {
3541 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
3542 bool PerformInit =
3543 VD->getAnyInitializer() &&
3544 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
3545 /*ForRef=*/false);
3546 if (auto InitFunction =
3547 getOpenMPRuntime().EmitOMPThreadPrivateVarDefinition(
3548 VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(),
3549 PerformInit))
3550 CXXGlobalInits.push_back(InitFunction);
3551 }
3552}
3553