blob: 22ff2081c6b65d9830b42125be9109737df872a2 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCall.h"
18#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000019#include "CGObjCRuntime.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000020#include "CGOpenCLRuntime.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "CodeGenFunction.h"
Justin Bogneref512b92014-01-06 22:27:43 +000023#include "CodeGenPGO.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000024#include "CodeGenTBAA.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000025#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000026#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000027#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000028#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000030#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000031#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000032#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000033#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000034#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000035#include "clang/Basic/CharInfo.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000036#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000037#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000038#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000039#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000040#include "clang/Basic/Version.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindola208b5c02013-10-22 19:26:13 +000042#include "clang/Sema/SemaDiagnostic.h"
Sebastian Redl4a7eab22012-02-25 20:51:20 +000043#include "llvm/ADT/APSInt.h"
John McCallbeec5a02010-03-06 00:35:14 +000044#include "llvm/ADT/Triple.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000045#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000046#include "llvm/IR/CallingConv.h"
47#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/LLVMContext.h"
50#include "llvm/IR/Module.h"
Justin Bogner837a6f62014-04-18 21:52:00 +000051#include "llvm/ProfileData/InstrProfReader.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000052#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000053#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000054
Chris Lattnerbed31442007-05-28 01:07:47 +000055using namespace clang;
56using namespace CodeGen;
57
Julien Lerouge5a6b6982011-09-09 22:41:49 +000058static const char AnnotationSection[] = "llvm.metadata";
59
Alp Toker82862252013-12-28 21:58:40 +000060static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000061 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000062 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000063 case TargetCXXABI::GenericARM:
64 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000065 case TargetCXXABI::iOS64:
John McCall57625922013-01-25 23:36:14 +000066 case TargetCXXABI::GenericItanium:
Alp Toker82862252013-12-28 21:58:40 +000067 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000068 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000069 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000070 }
71
72 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000073}
74
Chandler Carruthbc55fe22009-11-12 17:24:48 +000075CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall568d4102013-04-16 22:48:20 +000076 llvm::Module &M, const llvm::DataLayout &TD,
David Blaikie9c902b52011-09-25 23:23:43 +000077 DiagnosticsEngine &diags)
Alexey Samsonovd6e043b2013-08-12 11:48:05 +000078 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
79 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
80 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
81 TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0),
Alexey Bataev9959db52014-05-06 10:08:46 +000082 OpenCLRuntime(0), OpenMPRuntime(nullptr), CUDARuntime(0), DebugInfo(0),
83 ARCData(0), NoObjCARCExceptionsMetadata(0), RRData(0), PGOReader(nullptr),
Justin Bogneref512b92014-01-06 22:27:43 +000084 CFConstantStringClassRef(0),
Alexey Samsonovd6e043b2013-08-12 11:48:05 +000085 ConstantStringClassRef(0), NSConstantStringType(0),
86 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0),
87 BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0),
88 LifetimeStartFn(0), LifetimeEndFn(0),
89 SanitizerBlacklist(
90 llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)),
91 SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled
92 : LangOpts.Sanitize) {
Will Dietzf54319c2013-01-18 11:30:38 +000093
Chris Lattnerece04092012-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 McCall882987f2013-02-28 19:01:20 +0000111 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
112
David Blaikiebbafb8a2012-03-11 07:00:24 +0000113 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000114 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000115 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000116 createOpenCLRuntime();
Alexey Bataev9959db52014-05-06 10:08:46 +0000117 if (LangOpts.OpenMP)
118 createOpenMPRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000119 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000120 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000121
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000122 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Will Dietzf54319c2013-01-18 11:30:38 +0000123 if (SanOpts.Thread ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000124 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
125 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Alp Toker82862252013-12-28 21:58:40 +0000126 getCXXABI().getMangleContext());
Dan Gohman947c9af2010-10-14 23:06:10 +0000127
Nick Lewycky207bce32011-04-21 23:44:07 +0000128 // If debug info or coverage generation is enabled, create the CGDebugInfo
129 // object.
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000130 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000131 CodeGenOpts.EmitGcovArcs ||
Nick Lewycky207bce32011-04-21 23:44:07 +0000132 CodeGenOpts.EmitGcovNotes)
133 DebugInfo = new CGDebugInfo(*this);
John McCallad7c5c12011-02-08 08:22:06 +0000134
135 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000136
David Blaikiebbafb8a2012-03-11 07:00:24 +0000137 if (C.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +0000138 ARCData = new ARCEntrypoints();
139 RRData = new RREntrypoints();
Justin Bogneref512b92014-01-06 22:27:43 +0000140
Justin Bogner837a6f62014-04-18 21:52:00 +0000141 if (!CodeGenOpts.InstrProfileInput.empty()) {
142 if (llvm::error_code EC = llvm::IndexedInstrProfReader::create(
143 CodeGenOpts.InstrProfileInput, PGOReader)) {
144 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
145 "Could not read profile: %0");
146 getDiags().Report(DiagID) << EC.message();
147 }
148 }
Chris Lattnera087ff92008-03-01 08:45:05 +0000149}
150
151CodeGenModule::~CodeGenModule() {
Peter Collingbournee1d20992011-07-27 20:29:46 +0000152 delete ObjCRuntime;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000153 delete OpenCLRuntime;
Alexey Bataev9959db52014-05-06 10:08:46 +0000154 delete OpenMPRuntime;
Peter Collingbournefe883422011-10-06 18:29:37 +0000155 delete CUDARuntime;
Ted Kremenekc168e502011-10-08 05:28:26 +0000156 delete TheTargetCodeGenInfo;
Dan Gohmand19ee8a2010-10-15 18:04:46 +0000157 delete TBAA;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000158 delete DebugInfo;
John McCall31168b02011-06-15 23:02:42 +0000159 delete ARCData;
160 delete RRData;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000161}
162
David Chisnall481e3a82010-01-23 02:40:42 +0000163void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000164 // This is just isGNUFamily(), but we want to force implementors of
165 // new ABIs to decide how best to do this.
166 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000167 case ObjCRuntime::GNUstep:
168 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000169 case ObjCRuntime::ObjFW:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000170 ObjCRuntime = CreateGNUObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000171 return;
172
173 case ObjCRuntime::FragileMacOSX:
174 case ObjCRuntime::MacOSX:
175 case ObjCRuntime::iOS:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000176 ObjCRuntime = CreateMacObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000177 return;
178 }
179 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000180}
181
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000182void CodeGenModule::createOpenCLRuntime() {
183 OpenCLRuntime = new CGOpenCLRuntime(*this);
184}
185
Alexey Bataev9959db52014-05-06 10:08:46 +0000186void CodeGenModule::createOpenMPRuntime() {
187 OpenMPRuntime = new CGOpenMPRuntime(*this);
188}
189
Peter Collingbournefe883422011-10-06 18:29:37 +0000190void CodeGenModule::createCUDARuntime() {
191 CUDARuntime = CreateNVCUDARuntime(*this);
192}
193
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000194void CodeGenModule::applyReplacements() {
195 for (ReplacementsTy::iterator I = Replacements.begin(),
196 E = Replacements.end();
197 I != E; ++I) {
198 StringRef MangledName = I->first();
199 llvm::Constant *Replacement = I->second;
200 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
201 if (!Entry)
202 continue;
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000203 llvm::Function *OldF = cast<llvm::Function>(Entry);
204 llvm::Function *NewF = dyn_cast<llvm::Function>(Replacement);
205 if (!NewF) {
Reid Klecknerb78257d2014-02-03 18:54:51 +0000206 if (llvm::GlobalAlias *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
207 NewF = dyn_cast<llvm::Function>(Alias->getAliasedGlobal());
208 } else {
209 llvm::ConstantExpr *CE = cast<llvm::ConstantExpr>(Replacement);
210 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
211 CE->getOpcode() == llvm::Instruction::GetElementPtr);
212 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
213 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000214 }
215
216 // Replace old with new, but keep the old order.
217 OldF->replaceAllUsesWith(Replacement);
218 if (NewF) {
219 NewF->removeFromParent();
220 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
221 }
222 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000223 }
224}
225
Rafael Espindola208b5c02013-10-22 19:26:13 +0000226void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000227 // Check if the constructed aliases are well formed. It is really unfortunate
228 // that we have to do this in CodeGen, but we only construct mangled names
229 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000230 bool Error = false;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000231 DiagnosticsEngine &Diags = getDiags();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000232 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
233 E = Aliases.end(); I != E; ++I) {
234 const GlobalDecl &GD = *I;
235 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
236 const AliasAttr *AA = D->getAttr<AliasAttr>();
237 StringRef MangledName = getMangledName(GD);
238 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
239 llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000240 llvm::GlobalValue *GV = Alias->getAliasedGlobal();
Rafael Espindola93c7a652014-03-13 15:47:50 +0000241 if (!GV) {
Rafael Espindola208b5c02013-10-22 19:26:13 +0000242 Error = true;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000243 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
Rafael Espindola93c7a652014-03-13 15:47:50 +0000244 } else if (GV->isDeclaration()) {
245 Error = true;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000246 Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000247 }
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000248
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000249 llvm::Constant *Aliasee = Alias->getAliasee();
250 llvm::GlobalValue *AliaseeGV;
251 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) {
252 assert((CE->getOpcode() == llvm::Instruction::BitCast ||
253 CE->getOpcode() == llvm::Instruction::AddrSpaceCast) &&
254 "Unsupported aliasee");
255 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
256 } else {
257 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
258 }
Rafael Espindola502f65a2014-05-05 20:21:03 +0000259
260 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
261 StringRef AliasSection = SA->getName();
262 if (AliasSection != AliaseeGV->getSection())
263 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
264 << AliasSection;
265 }
266
267 // We have to handle alias to weak aliases in here. LLVM itself disallows
268 // this since the object semantics would not match the IL one. For
269 // compatibility with gcc we implement it by just pointing the alias
270 // to its aliasee's aliasee. We also warn, since the user is probably
271 // expecting the link to be weak.
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000272 if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
273 if (GA->mayBeOverridden()) {
Rafael Espindolac67b8152014-05-05 19:33:09 +0000274 Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000275 << GA->getAliasedGlobal()->getName() << GA->getName();
276 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
277 GA->getAliasee(), Alias->getType());
278 Alias->setAliasee(Aliasee);
279 }
280 }
Rafael Espindola208b5c02013-10-22 19:26:13 +0000281 }
282 if (!Error)
283 return;
284
285 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
286 E = Aliases.end(); I != E; ++I) {
287 const GlobalDecl &GD = *I;
288 StringRef MangledName = getMangledName(GD);
289 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
290 llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
291 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
292 Alias->eraseFromParent();
293 }
294}
295
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000296void CodeGenModule::clear() {
297 DeferredDeclsToEmit.clear();
298}
299
Ted Kremenek2c674f62008-08-05 18:50:11 +0000300void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000301 EmitDeferred();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000302 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000303 checkAliases();
Eli Friedman5866fe32010-01-08 00:50:11 +0000304 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000305 EmitCXXGlobalDtorFunc();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000306 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000307 if (ObjCRuntime)
308 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000309 AddGlobalCtor(ObjCInitFunction);
Justin Bognerf2ea7752014-04-10 18:13:13 +0000310 if (getCodeGenOpts().ProfileInstrGenerate)
311 if (llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this))
312 AddGlobalCtor(PGOInit, 0);
Justin Bogner837a6f62014-04-18 21:52:00 +0000313 if (PGOReader && PGOStats.isOutOfDate())
Justin Bognere2ef2a02014-04-15 21:22:35 +0000314 getDiags().Report(diag::warn_profile_data_out_of_date)
315 << PGOStats.Visited << PGOStats.Missing << PGOStats.Mismatched;
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000316 EmitCtorList(GlobalCtors, "llvm.global_ctors");
317 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000318 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000319 EmitStaticExternCAliases();
Rafael Espindola060062a2014-03-06 22:15:10 +0000320 emitLLVMUsed();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000321
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000322 if (CodeGenOpts.Autolink &&
323 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000324 EmitModuleLinkOptions();
325 }
Manman Ren9691f7f2013-06-19 01:46:49 +0000326 if (CodeGenOpts.DwarfVersion)
327 // We actually want the latest version when there are conflicts.
328 // We can change from Warning to Latest if such mode is supported.
329 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
330 CodeGenOpts.DwarfVersion);
Manman Ren4b7f23d2013-11-22 19:42:45 +0000331 if (DebugInfo)
332 // We support a single version in the linked module: error out when
Manman Renba2fa8b2013-12-02 19:37:35 +0000333 // modules do not have the same version. We are going to implement dropping
334 // debug info when the version number is not up-to-date. Once that is
335 // done, the bitcode linker is not going to see modules with different
336 // version numbers.
Manman Ren4b7f23d2013-11-22 19:42:45 +0000337 getModule().addModuleFlag(llvm::Module::Error, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000338 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000339
John McCall0bdb1fd2010-09-16 06:16:50 +0000340 SimplifyPersonality();
341
John McCall09ae0322010-07-06 23:57:41 +0000342 if (getCodeGenOpts().EmitDeclMetadata)
343 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000344
345 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000346 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000347
348 if (DebugInfo)
349 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000350
351 EmitVersionIdentMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000352}
353
Devang Patel945b8ae2011-03-23 16:29:39 +0000354void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
355 // Make sure that this type is translated.
356 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000357}
358
Dan Gohman947c9af2010-10-14 23:06:10 +0000359llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
360 if (!TBAA)
361 return 0;
362 return TBAA->getTBAAInfo(QTy);
363}
364
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000365llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
366 if (!TBAA)
367 return 0;
368 return TBAA->getTBAAInfoForVTablePtr();
369}
370
Dan Gohman22695fc2012-09-28 21:58:29 +0000371llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
372 if (!TBAA)
373 return 0;
374 return TBAA->getTBAAStructInfo(QTy);
375}
376
Manman Renc451e572013-04-04 21:53:22 +0000377llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
378 if (!TBAA)
379 return 0;
380 return TBAA->getTBAAStructTypeInfo(QTy);
381}
382
383llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
384 llvm::MDNode *AccessN,
385 uint64_t O) {
386 if (!TBAA)
387 return 0;
388 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
389}
390
Manman Ren4f755de2013-10-08 00:08:49 +0000391/// Decorate the instruction with a TBAA tag. For both scalar TBAA
392/// and struct-path aware TBAA, the tag has the same format:
393/// base type, access type and offset.
Manman Rene1ad74e2013-04-11 23:02:56 +0000394/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
Dan Gohman947c9af2010-10-14 23:06:10 +0000395void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
Manman Rene1ad74e2013-04-11 23:02:56 +0000396 llvm::MDNode *TBAAInfo,
397 bool ConvertTypeToTag) {
Manman Ren4f755de2013-10-08 00:08:49 +0000398 if (ConvertTypeToTag && TBAA)
Manman Rene1ad74e2013-04-11 23:02:56 +0000399 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
400 TBAA->getTBAAScalarTagInfo(TBAAInfo));
401 else
402 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
Dan Gohman947c9af2010-10-14 23:06:10 +0000403}
404
Alp Toker29cb66b2014-01-26 06:17:37 +0000405void CodeGenModule::Error(SourceLocation loc, StringRef message) {
406 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
407 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000408}
409
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000410/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000411/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000412void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000413 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000414 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000415 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000416 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
417 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000418}
Chris Lattner41af8182007-12-02 06:27:33 +0000419
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000420/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000421/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000422void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000423 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000424 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000425 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000426 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000427}
428
John McCall23c29fe2011-06-24 21:55:10 +0000429llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
430 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
431}
432
Mike Stump11289f42009-09-09 15:08:12 +0000433void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000434 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000435 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000436 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000437 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000438 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000439 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000440
John McCallc273f242010-10-30 11:50:40 +0000441 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000442 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000443 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
444 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000445}
446
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000447static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
448 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
449 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
450 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
451 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
452 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
453}
454
455static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
456 CodeGenOptions::TLSModel M) {
457 switch (M) {
458 case CodeGenOptions::GeneralDynamicTLSModel:
459 return llvm::GlobalVariable::GeneralDynamicTLSModel;
460 case CodeGenOptions::LocalDynamicTLSModel:
461 return llvm::GlobalVariable::LocalDynamicTLSModel;
462 case CodeGenOptions::InitialExecTLSModel:
463 return llvm::GlobalVariable::InitialExecTLSModel;
464 case CodeGenOptions::LocalExecTLSModel:
465 return llvm::GlobalVariable::LocalExecTLSModel;
466 }
467 llvm_unreachable("Invalid TLS model!");
468}
469
470void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
471 const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000472 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000473
474 llvm::GlobalVariable::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000475 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000476
477 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000478 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000479 TLM = GetLLVMTLSModel(Attr->getModel());
480 }
481
482 GV->setThreadLocalMode(TLM);
483}
484
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000485StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000486 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
487
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000488 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000489 if (!Str.empty())
490 return Str;
491
John McCall5d865c322010-08-31 07:33:07 +0000492 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000493 IdentifierInfo *II = ND->getIdentifier();
494 assert(II && "Attempt to mangle unnamed decl.");
495
496 Str = II->getName();
497 return Str;
498 }
499
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000500 SmallString<256> Buffer;
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000501 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000502 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000503 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000504 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000505 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000506 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000507 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000508
509 // Allocate space for the mangled name.
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000510 Out.flush();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000511 size_t Length = Buffer.size();
512 char *Name = MangledNamesAllocator.Allocate<char>(Length);
513 std::copy(Buffer.begin(), Buffer.end(), Name);
514
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000515 Str = StringRef(Name, Length);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000516
517 return Str;
518}
519
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000520void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
521 const BlockDecl *BD) {
522 MangleContext &MangleCtx = getCXXABI().getMangleContext();
523 const Decl *D = GD.getDecl();
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000524 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000525 if (D == 0)
Fariborz Jahanian63628032012-06-26 16:06:38 +0000526 MangleCtx.mangleGlobalBlock(BD,
527 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000528 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000529 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000530 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000531 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000532 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000533 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson635186a2010-06-09 02:36:32 +0000534}
535
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000536llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +0000537 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000538}
539
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000540/// AddGlobalCtor - Add a function to the list that will be called before
541/// main() runs.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000542void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000543 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000544 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000545}
546
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000547/// AddGlobalDtor - Add a function to the list that will be called
548/// when the module is unloaded.
549void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000550 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000551 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
552}
553
554void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
555 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +0000556 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000557 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000558
559 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000560 llvm::StructType *CtorStructTy =
Chris Lattnerece04092012-02-07 00:39:47 +0000561 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000562
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000563 // Construct the constructor and destructor arrays.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000564 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000565 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner3def9ae2012-02-06 22:16:34 +0000566 llvm::Constant *S[] = {
567 llvm::ConstantInt::get(Int32Ty, I->second, false),
568 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
569 };
Owen Anderson0e0189d2009-07-27 22:29:56 +0000570 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000571 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000572
573 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000574 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000575 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000576 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000577 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000578 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000579 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000580}
581
John McCalld4324142010-02-19 01:32:20 +0000582llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000583CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Eli Friedmanc48d31c2013-07-01 20:53:07 +0000584 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +0000585
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000586 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000587
David Majnemer27d69db2014-04-28 22:17:59 +0000588 bool UseThunkForDtorVariant =
589 isa<CXXDestructorDecl>(D) &&
Reid Klecknera12cd282013-12-11 19:21:27 +0000590 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
David Majnemer27d69db2014-04-28 22:17:59 +0000591 GD.getDtorType());
Reid Klecknera12cd282013-12-11 19:21:27 +0000592
David Majnemer27d69db2014-04-28 22:17:59 +0000593 return getLLVMLinkageforDeclarator(D, Linkage, /*isConstantVariable=*/false,
594 UseThunkForDtorVariant);
John McCalld4324142010-02-19 01:32:20 +0000595}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000596
John McCalld4324142010-02-19 01:32:20 +0000597
598/// SetFunctionDefinitionAttributes - Set attributes for a global.
599///
600/// FIXME: This is currently only done for aliases and functions, but not for
601/// variables (these details are set in EmitGlobalVarDefinition for variables).
602void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
603 llvm::GlobalValue *GV) {
Rafael Espindola502f65a2014-05-05 20:21:03 +0000604 setNonAliasAttributes(D, GV);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000605}
606
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000607void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000608 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000609 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000610 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000611 AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +0000612 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
Bill Wendling3087d022012-12-07 23:17:26 +0000613 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000614 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000615}
616
John McCall9b0a7ce2011-10-02 01:16:38 +0000617/// Determines whether the language options require us to model
618/// unwind exceptions. We treat -fexceptions as mandating this
619/// except under the fragile ObjC ABI with only ObjC exceptions
620/// enabled. This means, for example, that C with -fexceptions
621/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000622static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +0000623 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000624 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +0000625
626 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000627 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +0000628
629 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000630 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +0000631 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +0000632 }
633
634 return true;
635}
636
Daniel Dunbar38932572009-04-14 08:05:55 +0000637void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
638 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000639 llvm::AttrBuilder B;
640
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000641 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000642 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000643
David Blaikiebbafb8a2012-03-11 07:00:24 +0000644 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000645 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000646
Eli Friedmanc55efe42011-08-22 23:55:33 +0000647 if (D->hasAttr<NakedAttr>()) {
648 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000649 B.addAttribute(llvm::Attribute::Naked);
650 B.addAttribute(llvm::Attribute::NoInline);
Paul Robinsonf0674352014-03-31 22:29:15 +0000651 } else if (D->hasAttr<OptimizeNoneAttr>()) {
652 // OptimizeNone implies noinline; we should not be inlining such functions.
653 B.addAttribute(llvm::Attribute::OptimizeNone);
654 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +0000655 } else if (D->hasAttr<NoDuplicateAttr>()) {
656 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000657 } else if (D->hasAttr<NoInlineAttr>()) {
658 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +0000659 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000660 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
661 llvm::Attribute::NoInline)) {
662 // (noinline wins over always_inline, and we can't specify both in IR)
663 B.addAttribute(llvm::Attribute::AlwaysInline);
Eli Friedmanc55efe42011-08-22 23:55:33 +0000664 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000665
Diego Novillo5f2b1ce2013-05-24 20:18:15 +0000666 if (D->hasAttr<ColdAttr>()) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000667 B.addAttribute(llvm::Attribute::OptimizeForSize);
Diego Novillo5f2b1ce2013-05-24 20:18:15 +0000668 B.addAttribute(llvm::Attribute::Cold);
669 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +0000670
Quentin Colombet4e172062012-11-01 23:55:47 +0000671 if (D->hasAttr<MinSizeAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000672 B.addAttribute(llvm::Attribute::MinSize);
Richard Smithb555a762012-09-28 22:46:07 +0000673
Paul Robinsonf0674352014-03-31 22:29:15 +0000674 if (D->hasAttr<OptimizeNoneAttr>()) {
675 // OptimizeNone wins over OptimizeForSize and MinSize.
676 B.removeAttribute(llvm::Attribute::OptimizeForSize);
677 B.removeAttribute(llvm::Attribute::MinSize);
678 }
679
David Blaikiebbafb8a2012-03-11 07:00:24 +0000680 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000681 B.addAttribute(llvm::Attribute::StackProtect);
Josh Mageee0fc1a82014-02-11 01:35:14 +0000682 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
683 B.addAttribute(llvm::Attribute::StackProtectStrong);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000684 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000685 B.addAttribute(llvm::Attribute::StackProtectReq);
Will Dietzf54319c2013-01-18 11:30:38 +0000686
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000687 // Add sanitizer attributes if function is not blacklisted.
Alexey Samsonovd6e043b2013-08-12 11:48:05 +0000688 if (!SanitizerBlacklist->isIn(*F)) {
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000689 // When AddressSanitizer is enabled, set SanitizeAddress attribute
690 // unless __attribute__((no_sanitize_address)) is used.
691 if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000692 B.addAttribute(llvm::Attribute::SanitizeAddress);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000693 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
694 if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000695 B.addAttribute(llvm::Attribute::SanitizeThread);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000696 }
697 // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
698 if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000699 B.addAttribute(llvm::Attribute::SanitizeMemory);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000700 }
Alexander Potapenkoef41fd32012-02-02 11:49:28 +0000701
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000702 F->addAttributes(llvm::AttributeSet::FunctionIndex,
703 llvm::AttributeSet::get(
704 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
705
706 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
707 F->setUnnamedAddr(true);
708 else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
709 if (MD->isVirtual())
710 F->setUnnamedAddr(true);
711
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000712 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
713 if (alignment)
714 F->setAlignment(alignment);
715
Mike Stump3472ae52009-10-05 22:49:20 +0000716 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000717 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
718 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000719}
720
Mike Stump11289f42009-09-09 15:08:12 +0000721void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000722 llvm::GlobalValue *GV) {
Anders Carlsson072ef742011-01-29 19:41:00 +0000723 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
724 setGlobalVisibility(GV, ND);
John McCall457a04e2010-10-22 21:05:15 +0000725 else
726 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +0000727
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000728 if (D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000729 addUsedGlobal(GV);
Rafael Espindola502f65a2014-05-05 20:21:03 +0000730}
731
732void CodeGenModule::setNonAliasAttributes(const Decl *D,
733 llvm::GlobalValue *GV) {
734 assert(!isa<llvm::GlobalAlias>(GV));
735 SetCommonAttributes(D, GV);
Daniel Dunbar38932572009-04-14 08:05:55 +0000736
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000737 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000738 GV->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000739
Rafael Espindola502f65a2014-05-05 20:21:03 +0000740 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000741}
742
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000743void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
744 llvm::Function *F,
745 const CGFunctionInfo &FI) {
746 SetLLVMFunctionAttributes(D, FI, F);
747 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000748
749 F->setLinkage(llvm::Function::InternalLinkage);
750
Rafael Espindola502f65a2014-05-05 20:21:03 +0000751 setNonAliasAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000752}
753
David Majnemerf6acb762014-04-25 17:07:16 +0000754static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
755 const NamedDecl *ND) {
756 // Set linkage and visibility in case we never see a definition.
757 LinkageInfo LV = ND->getLinkageAndVisibility();
758 if (LV.getLinkage() != ExternalLinkage) {
759 // Don't set internal linkage on declarations.
760 } else {
761 if (ND->hasAttr<DLLImportAttr>()) {
762 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
763 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
764 } else if (ND->hasAttr<DLLExportAttr>()) {
765 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
766 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
767 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
768 // "extern_weak" is overloaded in LLVM; we probably should have
769 // separate linkage types for this.
770 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
771 }
772
773 // Set visibility on a declaration only if it's explicit.
774 if (LV.isVisibilityExplicit())
775 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
776 }
777}
778
Anders Carlsson6710c532010-02-06 02:44:09 +0000779void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000780 llvm::Function *F,
781 bool IsIncompleteFunction) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000782 if (unsigned IID = F->getIntrinsicID()) {
783 // If this is an intrinsic function, set the function's attributes
784 // to the intrinsic's attributes.
Bill Wendling311c8322012-10-15 04:47:45 +0000785 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
786 (llvm::Intrinsic::ID)IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000787 return;
788 }
789
Anders Carlsson6710c532010-02-06 02:44:09 +0000790 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
791
Eli Friedman895771a2009-05-26 01:22:57 +0000792 if (!IsIncompleteFunction)
John McCalla729c622012-02-17 03:33:10 +0000793 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000794
Bob Wilsonfc6297f2014-04-01 01:38:16 +0000795 // Add the Returned attribute for "this", except for iOS 5 and earlier
796 // where substantial code, including the libstdc++ dylib, was compiled with
797 // GCC and does not actually return "this".
798 if (getCXXABI().HasThisReturn(GD) &&
799 !(getTarget().getTriple().isiOS() &&
800 getTarget().getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000801 assert(!F->arg_empty() &&
802 F->arg_begin()->getType()
803 ->canLosslesslyBitCastTo(F->getReturnType()) &&
804 "unexpected this return");
805 F->addAttribute(1, llvm::Attribute::Returned);
806 }
807
Daniel Dunbar38932572009-04-14 08:05:55 +0000808 // Only a few attributes are set on declarations; these may later be
809 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000810
David Majnemerf6acb762014-04-25 17:07:16 +0000811 setLinkageAndVisibilityForGV(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +0000812
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000813 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000814 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +0000815
816 // A replaceable global allocation function does not act like a builtin by
817 // default, only if it is invoked by a new-expression or delete-expression.
818 if (FD->isReplaceableGlobalAllocationFunction())
819 F->addAttribute(llvm::AttributeSet::FunctionIndex,
820 llvm::Attribute::NoBuiltin);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000821}
822
Rafael Espindola060062a2014-03-06 22:15:10 +0000823void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000824 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000825 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000826 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000827}
828
Rafael Espindola060062a2014-03-06 22:15:10 +0000829void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
830 assert(!GV->isDeclaration() &&
831 "Only globals with definition can force usage.");
832 LLVMCompilerUsed.push_back(GV);
833}
834
835static void emitUsed(CodeGenModule &CGM, StringRef Name,
836 std::vector<llvm::WeakVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000837 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +0000838 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000839 return;
840
Rafael Espindola060062a2014-03-06 22:15:10 +0000841 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000842 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +0000843 UsedArray.resize(List.size());
844 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000845 UsedArray[i] =
Rafael Espindola060062a2014-03-06 22:15:10 +0000846 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
847 CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000848 }
Mike Stump11289f42009-09-09 15:08:12 +0000849
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000850 if (UsedArray.empty())
851 return;
Rafael Espindola060062a2014-03-06 22:15:10 +0000852 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000853
854 llvm::GlobalVariable *GV =
Rafael Espindola060062a2014-03-06 22:15:10 +0000855 new llvm::GlobalVariable(CGM.getModule(), ATy, false,
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000856 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000857 llvm::ConstantArray::get(ATy, UsedArray),
Rafael Espindola060062a2014-03-06 22:15:10 +0000858 Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000859
860 GV->setSection("llvm.metadata");
861}
862
Rafael Espindola060062a2014-03-06 22:15:10 +0000863void CodeGenModule::emitLLVMUsed() {
864 emitUsed(*this, "llvm.used", LLVMUsed);
865 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
866}
867
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000868void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
869 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
870 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
871}
872
Aaron Ballman5d041be2013-06-04 02:07:14 +0000873void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
874 llvm::SmallString<32> Opt;
875 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
876 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
877 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
878}
879
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000880void CodeGenModule::AddDependentLib(StringRef Lib) {
881 llvm::SmallString<24> Opt;
882 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
883 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
884 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
885}
886
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000887/// \brief Add link options implied by the given module, including modules
888/// it depends on, using a postorder walk.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000889static void addLinkOptionsPostorder(CodeGenModule &CGM,
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000890 Module *Mod,
Daniel Dunbar69e47462013-01-17 01:35:06 +0000891 SmallVectorImpl<llvm::Value *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000892 llvm::SmallPtrSet<Module *, 16> &Visited) {
893 // Import this module's parent.
894 if (Mod->Parent && Visited.insert(Mod->Parent)) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000895 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000896 }
897
898 // Import this module's dependencies.
899 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
900 if (Visited.insert(Mod->Imports[I-1]))
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000901 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000902 }
903
904 // Add linker options to link against the libraries/frameworks
905 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000906 llvm::LLVMContext &Context = CGM.getLLVMContext();
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000907 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000908 // Link against a framework. Frameworks are currently Darwin only, so we
909 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000910 if (Mod->LinkLibraries[I-1].IsFramework) {
911 llvm::Value *Args[2] = {
912 llvm::MDString::get(Context, "-framework"),
913 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
914 };
915
916 Metadata.push_back(llvm::MDNode::get(Context, Args));
917 continue;
918 }
919
920 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000921 llvm::SmallString<24> Opt;
922 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
923 Mod->LinkLibraries[I-1].Library, Opt);
924 llvm::Value *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000925 Metadata.push_back(llvm::MDNode::get(Context, OptString));
926 }
927}
928
929void CodeGenModule::EmitModuleLinkOptions() {
930 // Collect the set of all of the modules we want to visit to emit link
931 // options, which is essentially the imported modules and all of their
932 // non-explicit child modules.
933 llvm::SetVector<clang::Module *> LinkModules;
934 llvm::SmallPtrSet<clang::Module *, 16> Visited;
935 SmallVector<clang::Module *, 16> Stack;
936
937 // Seed the stack with imported modules.
938 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
939 MEnd = ImportedModules.end();
940 M != MEnd; ++M) {
941 if (Visited.insert(*M))
942 Stack.push_back(*M);
943 }
944
945 // Find all of the modules to import, making a little effort to prune
946 // non-leaf modules.
947 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000948 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000949
950 bool AnyChildren = false;
951
952 // Visit the submodules of this module.
953 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
954 SubEnd = Mod->submodule_end();
955 Sub != SubEnd; ++Sub) {
956 // Skip explicit children; they need to be explicitly imported to be
957 // linked against.
958 if ((*Sub)->IsExplicit)
959 continue;
960
961 if (Visited.insert(*Sub)) {
962 Stack.push_back(*Sub);
963 AnyChildren = true;
964 }
965 }
966
967 // We didn't find any children, so add this module to the list of
968 // modules to link against.
969 if (!AnyChildren) {
970 LinkModules.insert(Mod);
971 }
972 }
973
974 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000975 // order. We don't do anything to try to order import link flags with respect
976 // to linker options inserted by things like #pragma comment().
Daniel Dunbar69e47462013-01-17 01:35:06 +0000977 SmallVector<llvm::Value *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000978 Visited.clear();
979 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
980 MEnd = LinkModules.end();
981 M != MEnd; ++M) {
982 if (Visited.insert(*M))
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000983 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000984 }
Daniel Dunbar69e47462013-01-17 01:35:06 +0000985 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000986 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000987
Daniel Dunbar69e47462013-01-17 01:35:06 +0000988 // Add the linker options metadata flag.
989 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000990 llvm::MDNode::get(getLLVMContext(),
991 LinkerOptionsMetadata));
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000992}
993
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000994void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +0000995 // Emit code for any potentially referenced deferred decls. Since a
996 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +0000997 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000998
John McCall6bd2a892013-01-25 22:31:03 +0000999 while (true) {
Anders Carlsson11e51402010-04-17 20:15:18 +00001000 if (!DeferredVTables.empty()) {
John McCall6bd2a892013-01-25 22:31:03 +00001001 EmitDeferredVTables();
1002
1003 // Emitting a v-table doesn't directly cause more v-tables to
1004 // become deferred, although it can cause functions to be
1005 // emitted that then need those v-tables.
1006 assert(DeferredVTables.empty());
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001007 }
1008
John McCall6bd2a892013-01-25 22:31:03 +00001009 // Stop if we're out of both deferred v-tables and deferred declarations.
1010 if (DeferredDeclsToEmit.empty()) break;
1011
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001012 DeferredGlobal &G = DeferredDeclsToEmit.back();
1013 GlobalDecl D = G.GD;
1014 llvm::GlobalValue *GV = G.GV;
Chris Lattner45470942009-03-21 09:44:56 +00001015 DeferredDeclsToEmit.pop_back();
1016
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001017 assert(GV == GetGlobalValue(getMangledName(D)));
John McCallc2af9392010-05-27 01:45:30 +00001018 // Check to see if we've already emitted this. This is necessary
1019 // for a couple of reasons: first, decls can end up in the
1020 // deferred-decls queue multiple times, and second, decls can end
1021 // up with definitions in unusual ways (e.g. by an extern inline
1022 // function acquiring a strong function redefinition). Just
1023 // ignore these cases.
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001024 if(!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001025 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001026
Chris Lattner45470942009-03-21 09:44:56 +00001027 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001028 EmitGlobalDefinition(D, GV);
Chris Lattner45470942009-03-21 09:44:56 +00001029 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001030}
Chris Lattner09153c02007-06-22 18:48:09 +00001031
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001032void CodeGenModule::EmitGlobalAnnotations() {
1033 if (Annotations.empty())
1034 return;
1035
1036 // Create a new global variable for the ConstantStruct in the Module.
1037 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1038 Annotations[0]->getType(), Annotations.size()), Annotations);
1039 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
1040 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
1041 "llvm.global.annotations");
1042 gv->setSection(AnnotationSection);
1043}
1044
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001045llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001046 llvm::Constant *&AStr = AnnotationStrings[Str];
1047 if (AStr)
1048 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001049
1050 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001051 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001052 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
1053 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
1054 gv->setSection(AnnotationSection);
1055 gv->setUnnamedAddr(true);
Benjamin Kramereed80612013-11-10 16:55:11 +00001056 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001057 return gv;
1058}
1059
1060llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1061 SourceManager &SM = getContext().getSourceManager();
1062 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1063 if (PLoc.isValid())
1064 return EmitAnnotationString(PLoc.getFilename());
1065 return EmitAnnotationString(SM.getBufferName(Loc));
1066}
1067
1068llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1069 SourceManager &SM = getContext().getSourceManager();
1070 PresumedLoc PLoc = SM.getPresumedLoc(L);
1071 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1072 SM.getExpansionLineNumber(L);
1073 return llvm::ConstantInt::get(Int32Ty, LineNo);
1074}
1075
Mike Stump11289f42009-09-09 15:08:12 +00001076llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001077 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001078 SourceLocation L) {
1079 // Get the globals for file name, annotation, and the line number.
1080 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1081 *UnitGV = EmitAnnotationUnit(L),
1082 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001083
Daniel Dunbar346892a2009-04-14 22:41:13 +00001084 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001085 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001086 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1087 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1088 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1089 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001090 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001091 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001092}
1093
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001094void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1095 llvm::GlobalValue *GV) {
1096 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1097 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001098 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1099 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001100}
1101
Argyrios Kyrtzidisc0279a92010-07-27 22:37:14 +00001102bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001103 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001104 if (LangOpts.EmitAllDecls)
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001105 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001106
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00001107 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001108}
1109
Nico Webercf4ff5862012-10-11 10:13:44 +00001110llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1111 const CXXUuidofExpr* E) {
1112 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1113 // well-formed.
David Majnemer8eaab6f2013-08-13 06:32:20 +00001114 StringRef Uuid = E->getUuidAsStringRef(Context);
David Majnemercf963ce2013-08-09 08:35:59 +00001115 std::string Name = "_GUID_" + Uuid.lower();
1116 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00001117
1118 // Look for an existing global.
1119 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1120 return GV;
1121
1122 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1123 assert(Init && "failed to initialize as constant");
1124
David Majnemerbbecd092013-08-15 19:59:14 +00001125 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1126 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00001127 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
Nico Webercf4ff5862012-10-11 10:13:44 +00001128 return GV;
1129}
1130
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001131llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1132 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1133 assert(AA && "No alias?");
1134
Chris Lattner2192fe52011-07-18 04:24:23 +00001135 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001136
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001137 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00001138 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001139 if (Entry) {
1140 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1141 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1142 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001143
1144 llvm::Constant *Aliasee;
1145 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00001146 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1147 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00001148 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001149 else
John McCall7ec50432010-03-19 23:29:14 +00001150 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001151 llvm::PointerType::getUnqual(DeclTy), 0);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001152
1153 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1154 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1155 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001156
1157 return Aliasee;
1158}
1159
Chris Lattnere0be0df2009-05-12 21:21:08 +00001160void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +00001161 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001162
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001163 // Weak references don't produce any output by themselves.
1164 if (Global->hasAttr<WeakRefAttr>())
1165 return;
1166
Chris Lattner54041692009-03-22 21:47:11 +00001167 // If this is an alias definition (which otherwise looks like a declaration)
1168 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001169 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00001170 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001171
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001172 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001173 if (LangOpts.CUDA) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001174 if (CodeGenOpts.CUDAIsDevice) {
1175 if (!Global->hasAttr<CUDADeviceAttr>() &&
1176 !Global->hasAttr<CUDAGlobalAttr>() &&
1177 !Global->hasAttr<CUDAConstantAttr>() &&
1178 !Global->hasAttr<CUDASharedAttr>())
1179 return;
1180 } else {
1181 if (!Global->hasAttr<CUDAHostAttr>() && (
1182 Global->hasAttr<CUDADeviceAttr>() ||
1183 Global->hasAttr<CUDAConstantAttr>() ||
1184 Global->hasAttr<CUDASharedAttr>()))
1185 return;
1186 }
1187 }
1188
Chris Lattner45470942009-03-21 09:44:56 +00001189 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar4e004ed2009-03-19 08:27:24 +00001190 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001191 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001192 if (!FD->doesThisDeclarationHaveABody()) {
1193 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1194 return;
1195
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001196 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00001197
1198 // Compute the function info and LLVM type.
1199 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1200 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1201
1202 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1203 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001204 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001205 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001206 } else {
1207 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001208 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1209
Douglas Gregor61f6db52010-02-06 05:15:45 +00001210 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +00001211 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +00001212 }
1213
Chris Lattner45470942009-03-21 09:44:56 +00001214 // Defer code generation when possible if this is a static definition, inline
1215 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001216 if (!MayDeferGeneration(Global)) {
1217 // Emit the definition if it can't be deferred.
1218 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001219 return;
1220 }
John McCall70013b62010-07-15 23:40:35 +00001221
1222 // If we're deferring emission of a C++ variable with an
1223 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001224 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00001225 cast<VarDecl>(Global)->hasInit()) {
1226 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1227 CXXGlobalInits.push_back(0);
1228 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001229
1230 // If the value has already been used, add it directly to the
1231 // DeferredDeclsToEmit list.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001232 StringRef MangledName = getMangledName(GD);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001233 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName))
1234 addDeferredDeclToEmit(GV, GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001235 else {
1236 // Otherwise, remember that we saw a deferred decl with this name. The
1237 // first use of the mangled name will cause it to move into
1238 // DeferredDeclsToEmit.
1239 DeferredDecls[MangledName] = GD;
1240 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00001241}
1242
Rafael Espindolac5941352011-10-26 20:41:06 +00001243namespace {
1244 struct FunctionIsDirectlyRecursive :
1245 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1246 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001247 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00001248 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001249 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1250 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001251 }
1252 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1253
1254 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001255 const FunctionDecl *FD = E->getDirectCallee();
1256 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00001257 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001258 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1259 if (Attr && Name == Attr->getLabel()) {
1260 Result = true;
1261 return false;
1262 }
1263 unsigned BuiltinID = FD->getBuiltinID();
1264 if (!BuiltinID)
Rafael Espindolac5941352011-10-26 20:41:06 +00001265 return true;
Nick Lewycky9ed5b152012-01-18 03:41:19 +00001266 StringRef BuiltinName = BI.GetName(BuiltinID);
1267 if (BuiltinName.startswith("__builtin_") &&
1268 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001269 Result = true;
1270 return false;
1271 }
1272 return true;
1273 }
1274 };
1275}
1276
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001277// isTriviallyRecursive - Check if this function calls another
1278// decl that, because of the asm attribute or the other decl being a builtin,
1279// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00001280bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001281CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1282 StringRef Name;
1283 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00001284 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001285 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1286 if (!Attr)
1287 return false;
1288 Name = Attr->getLabel();
1289 } else {
1290 Name = FD->getName();
1291 }
Rafael Espindolac5941352011-10-26 20:41:06 +00001292
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001293 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1294 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00001295 return Walker.Result;
1296}
1297
1298bool
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001299CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1300 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00001301 return true;
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001302 const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00001303 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00001304 return false;
1305 // PR9614. Avoid cases where the source code is lying to us. An available
1306 // externally function should have an equivalent function somewhere else,
1307 // but a function that calls itself is clearly not equivalent to the real
1308 // implementation.
1309 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001310 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00001311}
1312
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001313/// If the type for the method's class was generated by
1314/// CGDebugInfo::createContextChain(), the cache contains only a
1315/// limited DIType without any declarations. Since EmitFunctionStart()
1316/// needs to find the canonical declaration for each method, we need
1317/// to construct the complete type prior to emitting the method.
1318void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1319 if (!D->isInstance())
1320 return;
1321
1322 if (CGDebugInfo *DI = getModuleDebugInfo())
1323 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1324 const PointerType *ThisPtr =
1325 cast<PointerType>(D->getThisType(getContext()));
1326 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1327 }
1328}
1329
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001330void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Anders Carlsson38988d72009-09-10 23:38:47 +00001331 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001332
Dan Gohman145f3f12010-04-19 16:39:44 +00001333 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00001334 Context.getSourceManager(),
1335 "Generating code for declaration");
1336
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001337 if (isa<FunctionDecl>(D)) {
Douglas Gregora700f682010-07-13 06:02:28 +00001338 // At -O0, don't generate IR for functions with available_externally
1339 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001340 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00001341 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00001342
Douglas Gregora700f682010-07-13 06:02:28 +00001343 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001344 CompleteDIClassType(Method);
Eli Friedman49a94b12011-05-06 17:27:27 +00001345 // Make sure to emit the definition(s) before we emit the thunks.
1346 // This is necessary for the generation of certain thunks.
1347 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1348 EmitCXXConstructor(CD, GD.getCtorType());
1349 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1350 EmitCXXDestructor(DD, GD.getDtorType());
1351 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001352 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00001353
Douglas Gregora700f682010-07-13 06:02:28 +00001354 if (Method->isVirtual())
1355 getVTables().EmitThunks(GD);
1356
Eli Friedman49a94b12011-05-06 17:27:27 +00001357 return;
Douglas Gregora700f682010-07-13 06:02:28 +00001358 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001359
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001360 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00001361 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001362
1363 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1364 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001365
David Blaikie83d382b2011-09-23 05:06:16 +00001366 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00001367}
1368
Chris Lattnerd4808922009-03-22 21:03:39 +00001369/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1370/// module, create and return an llvm Function with the specified type. If there
1371/// is something in the module with the specified name, return it potentially
1372/// bitcasted to the right type.
1373///
1374/// If D is non-null, it specifies a decl that correspond to this. This is used
1375/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001376llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001377CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001378 llvm::Type *Ty,
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001379 GlobalDecl GD, bool ForVTable,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001380 bool DontDefer,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001381 llvm::AttributeSet ExtraAttrs) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001382 const Decl *D = GD.getDecl();
1383
Chris Lattnera85d68e2009-03-21 09:25:43 +00001384 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001385 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001386 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001387 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001388 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001389 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001390 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001391 }
1392
Chris Lattnera85d68e2009-03-21 09:25:43 +00001393 if (Entry->getType()->getElementType() == Ty)
1394 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001395
Chris Lattnera85d68e2009-03-21 09:25:43 +00001396 // Make sure the result is of the correct type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001397 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00001398 }
Mike Stump11289f42009-09-09 15:08:12 +00001399
Eli Friedmancc522d92009-11-09 05:07:37 +00001400 // This function doesn't have a complete type (for example, the return
1401 // type is an incomplete struct). Use a fake type instead, and make
1402 // sure not to try to set attributes.
1403 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00001404
Chris Lattner2192fe52011-07-18 04:24:23 +00001405 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00001406 if (isa<llvm::FunctionType>(Ty)) {
1407 FTy = cast<llvm::FunctionType>(Ty);
1408 } else {
John McCall9dc0db22011-05-15 01:53:33 +00001409 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00001410 IsIncompleteFunction = true;
1411 }
Chris Lattner5c740f12010-06-30 19:14:05 +00001412
John McCalld06fb862010-04-28 00:00:30 +00001413 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +00001414 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +00001415 MangledName, &getModule());
1416 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001417 if (D)
1418 SetFunctionAttributes(GD, F, IsIncompleteFunction);
Bill Wendling8594fcb2013-01-31 00:30:05 +00001419 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1420 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
Bill Wendling9a677922013-01-23 00:21:06 +00001421 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1422 llvm::AttributeSet::get(VMContext,
1423 llvm::AttributeSet::FunctionIndex,
1424 B));
1425 }
Eli Friedmancc522d92009-11-09 05:07:37 +00001426
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001427 if (!DontDefer) {
1428 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1429 // each other bottoming out with the base dtor. Therefore we emit non-base
1430 // dtors on usage, even if there is no dtor definition in the TU.
1431 if (D && isa<CXXDestructorDecl>(D) &&
1432 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1433 GD.getDtorType()))
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001434 addDeferredDeclToEmit(F, GD);
John McCall357d0f32010-12-15 04:00:32 +00001435
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001436 // This is the first use or definition of a mangled name. If there is a
1437 // deferred decl with this name, remember that we need to emit it at the end
1438 // of the file.
1439 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1440 if (DDI != DeferredDecls.end()) {
1441 // Move the potentially referenced deferred decl to the
1442 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1443 // don't need it anymore).
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001444 addDeferredDeclToEmit(F, DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001445 DeferredDecls.erase(DDI);
Richard Smithb47c36f2013-11-05 09:12:18 +00001446
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001447 // Otherwise, if this is a sized deallocation function, emit a weak
1448 // definition
1449 // for it at the end of the translation unit.
1450 } else if (D && cast<FunctionDecl>(D)
1451 ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001452 addDeferredDeclToEmit(F, GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001453
1454 // Otherwise, there are cases we have to worry about where we're
1455 // using a declaration for which we must emit a definition but where
1456 // we might not find a top-level definition:
1457 // - member functions defined inline in their classes
1458 // - friend functions defined inline in some class
1459 // - special member functions with implicit definitions
1460 // If we ever change our AST traversal to walk into class methods,
1461 // this will be unnecessary.
1462 //
1463 // We also don't emit a definition for a function if it's going to be an
1464 // entry
1465 // in a vtable, unless it's already marked as used.
1466 } else if (getLangOpts().CPlusPlus && D) {
1467 // Look for a declaration that's lexically in a record.
1468 const FunctionDecl *FD = cast<FunctionDecl>(D);
1469 FD = FD->getMostRecentDecl();
1470 do {
1471 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1472 if (FD->isImplicit() && !ForVTable) {
1473 assert(FD->isUsed() &&
1474 "Sema didn't mark implicit function as used!");
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001475 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001476 break;
1477 } else if (FD->doesThisDeclarationHaveABody()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001478 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001479 break;
1480 }
John McCall357d0f32010-12-15 04:00:32 +00001481 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001482 FD = FD->getPreviousDecl();
1483 } while (FD);
1484 }
Chris Lattner45470942009-03-21 09:44:56 +00001485 }
Mike Stump11289f42009-09-09 15:08:12 +00001486
Robert Lytton844aeeb2014-05-02 09:33:20 +00001487 getTargetCodeGenInfo().emitTargetMD(D, F, *this);
1488
John McCalld06fb862010-04-28 00:00:30 +00001489 // Make sure the result is of the requested type.
1490 if (!IsIncompleteFunction) {
1491 assert(F->getType()->getElementType() == Ty);
1492 return F;
1493 }
1494
Chris Lattnera5f58b02011-07-09 17:41:47 +00001495 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00001496 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001497}
1498
Chris Lattnerd4808922009-03-22 21:03:39 +00001499/// GetAddrOfFunction - Return the address of the given function. If Ty is
1500/// non-null, then this function will use the specified type if it has to
1501/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00001502llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00001503 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001504 bool ForVTable,
1505 bool DontDefer) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001506 // If there was no specific requested type, just convert it now.
1507 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +00001508 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +00001509
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001510 StringRef MangledName = getMangledName(GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001511 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
Chris Lattnerd4808922009-03-22 21:03:39 +00001512}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001513
Chris Lattnerd4808922009-03-22 21:03:39 +00001514/// CreateRuntimeFunction - Create a new runtime function with the specified
1515/// type and name.
1516llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001517CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001518 StringRef Name,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001519 llvm::AttributeSet ExtraAttrs) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001520 llvm::Constant *C =
1521 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1522 /*DontDefer=*/false, ExtraAttrs);
John McCall882987f2013-02-28 19:01:20 +00001523 if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1524 if (F->empty())
1525 F->setCallingConv(getRuntimeCC());
1526 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00001527}
Daniel Dunbar9c426522008-07-29 23:18:29 +00001528
Richard Smithe070fd22012-02-17 06:48:11 +00001529/// isTypeConstant - Determine whether an object of this type can be emitted
1530/// as a constant.
1531///
1532/// If ExcludeCtor is true, the duration when the object's constructor runs
1533/// will not be considered. The caller will need to verify that the object is
1534/// not written to during its construction.
1535bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1536 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00001537 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00001538
David Blaikiebbafb8a2012-03-11 07:00:24 +00001539 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00001540 if (const CXXRecordDecl *Record
1541 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1542 return ExcludeCtor && !Record->hasMutableFields() &&
1543 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00001544 }
Richard Smithe070fd22012-02-17 06:48:11 +00001545
Eli Friedmanb095e152009-12-11 21:23:03 +00001546 return true;
1547}
1548
David Majnemer01bbd1b2014-04-25 17:08:41 +00001549static bool isVarDeclInlineInitializedStaticDataMember(const VarDecl *VD) {
1550 if (!VD->isStaticDataMember())
1551 return false;
1552 const VarDecl *InitDecl;
1553 const Expr *InitExpr = VD->getAnyInitializer(InitDecl);
1554 if (!InitExpr)
1555 return false;
1556 if (InitDecl->isThisDeclarationADefinition())
1557 return false;
1558 return true;
1559}
1560
Chris Lattnerd4808922009-03-22 21:03:39 +00001561/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1562/// create and return an llvm GlobalVariable with the specified type. If there
1563/// is something in the module with the specified name, return it potentially
1564/// bitcasted to the right type.
1565///
1566/// If D is non-null, it specifies a decl that correspond to this. This is used
1567/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001568llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001569CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001570 llvm::PointerType *Ty,
Rafael Espindolad661a852011-01-18 21:07:57 +00001571 const VarDecl *D,
1572 bool UnnamedAddr) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00001573 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001574 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00001575 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001576 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001577 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001578 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001579 }
1580
Rafael Espindolad661a852011-01-18 21:07:57 +00001581 if (UnnamedAddr)
1582 Entry->setUnnamedAddr(true);
1583
Chris Lattnerd4808922009-03-22 21:03:39 +00001584 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00001585 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001586
Chris Lattner3bfce182009-03-21 08:03:33 +00001587 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00001588 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1589 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1590
Owen Andersonade90fd2009-07-29 18:54:39 +00001591 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00001592 }
Mike Stump11289f42009-09-09 15:08:12 +00001593
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001594 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1595 llvm::GlobalVariable *GV =
1596 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1597 llvm::GlobalValue::ExternalLinkage,
1598 0, MangledName, 0,
1599 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1600
Chris Lattner45470942009-03-21 09:44:56 +00001601 // This is the first use or definition of a mangled name. If there is a
1602 // deferred decl with this name, remember that we need to emit it at the end
1603 // of the file.
John McCall7ec50432010-03-19 23:29:14 +00001604 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00001605 if (DDI != DeferredDecls.end()) {
1606 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1607 // list, and remove it from DeferredDecls (since we don't need it anymore).
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001608 addDeferredDeclToEmit(GV, DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00001609 DeferredDecls.erase(DDI);
1610 }
Mike Stump11289f42009-09-09 15:08:12 +00001611
Chris Lattner3bfce182009-03-21 08:03:33 +00001612 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00001613 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00001614 // FIXME: This code is overly simple and should be merged with other global
1615 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00001616 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00001617
David Majnemerf6acb762014-04-25 17:07:16 +00001618 setLinkageAndVisibilityForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00001619
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001620 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00001621 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1622 CXXThreadLocals.push_back(std::make_pair(D, GV));
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001623 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001624 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00001625
1626 // If required by the ABI, treat declarations of static data members with
1627 // inline initializers as definitions.
1628 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
David Majnemer01bbd1b2014-04-25 17:08:41 +00001629 isVarDeclInlineInitializedStaticDataMember(D))
Hans Wennborgfeedf852013-11-21 00:15:56 +00001630 EmitGlobalVarDefinition(D);
Robert Lyttonf80d6882014-05-02 09:33:30 +00001631
1632 // Handle XCore specific ABI requirements.
1633 if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1634 D->getLanguageLinkage() == CLanguageLinkage &&
1635 D->getType().isConstant(Context) &&
1636 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1637 GV->setSection(".cp.rodata");
Chris Lattnerd4808922009-03-22 21:03:39 +00001638 }
Mike Stump11289f42009-09-09 15:08:12 +00001639
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001640 if (AddrSpace != Ty->getAddressSpace())
Matt Arsenault00e65b22013-11-15 02:19:52 +00001641 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1642
Robert Lytton844aeeb2014-05-02 09:33:20 +00001643 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
1644
Matt Arsenault00e65b22013-11-15 02:19:52 +00001645 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001646}
1647
Chris Lattnerd4808922009-03-22 21:03:39 +00001648
Anders Carlssonda80af32011-01-29 18:20:20 +00001649llvm::GlobalVariable *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001650CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00001651 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00001652 llvm::GlobalValue::LinkageTypes Linkage) {
1653 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1654 llvm::GlobalVariable *OldGV = 0;
1655
1656
1657 if (GV) {
1658 // Check if the variable has the right type.
1659 if (GV->getType()->getElementType() == Ty)
1660 return GV;
1661
1662 // Because C++ name mangling, the only way we can end up with an already
1663 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00001664 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00001665 OldGV = GV;
1666 }
1667
1668 // Create a new variable.
1669 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1670 Linkage, 0, Name);
1671
1672 if (OldGV) {
1673 // Replace occurrences of the old variable if needed.
1674 GV->takeName(OldGV);
1675
1676 if (!OldGV->use_empty()) {
1677 llvm::Constant *NewPtrForOldDecl =
1678 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1679 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1680 }
1681
1682 OldGV->eraseFromParent();
1683 }
1684
1685 return GV;
1686}
1687
Chris Lattnerd4808922009-03-22 21:03:39 +00001688/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1689/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00001690/// then it will be created with the specified type instead of whatever the
Chris Lattnerd4808922009-03-22 21:03:39 +00001691/// normal requested type would be.
1692llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2192fe52011-07-18 04:24:23 +00001693 llvm::Type *Ty) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001694 assert(D->hasGlobalStorage() && "Not a global variable");
1695 QualType ASTTy = D->getType();
1696 if (Ty == 0)
1697 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001698
Chris Lattner2192fe52011-07-18 04:24:23 +00001699 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001700 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00001701
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001702 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001703 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001704}
1705
1706/// CreateRuntimeVariable - Create a new runtime global variable with the
1707/// specified type and name.
1708llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001709CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001710 StringRef Name) {
John McCall31996342011-04-07 08:22:57 +00001711 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolad661a852011-01-18 21:07:57 +00001712 true);
Chris Lattnerd4808922009-03-22 21:03:39 +00001713}
1714
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001715void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1716 assert(!D->getInit() && "Cannot emit definite definitions here!");
1717
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001718 if (MayDeferGeneration(D)) {
1719 // If we have not seen a reference to this variable yet, place it
1720 // into the deferred declarations table to be emitted if needed
1721 // later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001722 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001723 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001724 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001725 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001726 }
1727 }
1728
1729 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001730 EmitGlobalVarDefinition(D);
1731}
1732
Chris Lattner2192fe52011-07-18 04:24:23 +00001733CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck9a648692011-01-18 02:01:14 +00001734 return Context.toCharUnitsFromBits(
Micah Villmowdd31ca12012-10-08 16:25:52 +00001735 TheDataLayout.getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00001736}
1737
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001738unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1739 unsigned AddrSpace) {
1740 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1741 if (D->hasAttr<CUDAConstantAttr>())
1742 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1743 else if (D->hasAttr<CUDASharedAttr>())
1744 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1745 else
1746 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1747 }
1748
1749 return AddrSpace;
1750}
1751
Richard Smithdf931ce2013-04-06 05:00:46 +00001752template<typename SomeDecl>
1753void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1754 llvm::GlobalValue *GV) {
1755 if (!getLangOpts().CPlusPlus)
1756 return;
1757
1758 // Must have 'used' attribute, or else inline assembly can't rely on
1759 // the name existing.
1760 if (!D->template hasAttr<UsedAttr>())
1761 return;
1762
1763 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001764 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00001765 return;
1766
1767 // Must be in an extern "C" context. Entities declared directly within
1768 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001769 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00001770 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00001771 return;
1772
1773 // OK, this is an internal linkage entity inside an extern "C" linkage
1774 // specification. Make a note of that so we can give it the "expected"
1775 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00001776 std::pair<StaticExternCMap::iterator, bool> R =
1777 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00001778
1779 // If we have multiple internal linkage entities with the same name
1780 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00001781 if (!R.second)
1782 R.first->second = 0;
Richard Smithdf931ce2013-04-06 05:00:46 +00001783}
1784
Daniel Dunbar9c426522008-07-29 23:18:29 +00001785void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001786 llvm::Constant *Init = 0;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001787 QualType ASTTy = D->getType();
Richard Smith6331c402012-02-13 22:16:19 +00001788 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1789 bool NeedsGlobalCtor = false;
1790 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00001791
Richard Smithdafff942012-01-14 04:30:29 +00001792 const VarDecl *InitDecl;
1793 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001794
Anders Carlssonca4a5452010-01-26 17:43:42 +00001795 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001796 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001797 // implicitly initialized with { 0 }.
1798 //
1799 // Note that tentative definitions are only emitted at the end of
1800 // a translation unit, so they should never have incomplete
1801 // type. In addition, EmitTentativeDefinition makes sure that we
1802 // never attempt to emit a tentative definition if a real one
1803 // exists. A use may still exists, however, so we still may need
1804 // to do a RAUW.
1805 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001806 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001807 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00001808 initializedGlobalDecl = GlobalDecl(D);
1809 Init = EmitConstantInit(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001810
Fariborz Jahanian63628032012-06-26 16:06:38 +00001811 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001812 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001813 if (D->getType()->isReferenceType())
1814 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00001815
David Blaikiebbafb8a2012-03-11 07:00:24 +00001816 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001817 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00001818 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001819 } else {
1820 ErrorUnsupported(D, "static initializer");
1821 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1822 }
John McCall70013b62010-07-15 23:40:35 +00001823 } else {
1824 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00001825 // initializer position (just in case this entry was delayed) if we
1826 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001827 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00001828 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001829 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001830 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001831
Chris Lattner2192fe52011-07-18 04:24:23 +00001832 llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001833 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001834
Chris Lattner149927c2009-03-21 09:16:30 +00001835 // Strip off a bitcast if we got one back.
1836 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001837 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00001838 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1839 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00001840 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001841 Entry = CE->getOperand(0);
1842 }
Mike Stump11289f42009-09-09 15:08:12 +00001843
Chris Lattner149927c2009-03-21 09:16:30 +00001844 // Entry is now either a Function or GlobalVariable.
1845 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001846
Chris Lattner149927c2009-03-21 09:16:30 +00001847 // We have a definition after a declaration with the wrong type.
1848 // We must make a new GlobalVariable* and update everything that used OldGV
1849 // (a declaration or tentative definition) with the new GlobalVariable*
1850 // (which will be a definition).
1851 //
1852 // This happens if there is a prototype for a global (e.g.
1853 // "extern int x[];") and then a definition of a different type (e.g.
1854 // "int x[10];"). This also happens when an initializer has a different type
1855 // from the type of the global (this happens with unions).
Chris Lattner149927c2009-03-21 09:16:30 +00001856 if (GV == 0 ||
1857 GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001858 GV->getType()->getAddressSpace() !=
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001859 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump11289f42009-09-09 15:08:12 +00001860
John McCall7ec50432010-03-19 23:29:14 +00001861 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001862 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001863
Chris Lattner149927c2009-03-21 09:16:30 +00001864 // Make a new global with the correct type, this is now guaranteed to work.
1865 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001866
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001867 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001868 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001869 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001870 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001871
1872 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001873 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001874 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001875
Richard Smithdf931ce2013-04-06 05:00:46 +00001876 MaybeHandleStaticInExternC(D, GV);
1877
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001878 if (D->hasAttr<AnnotateAttr>())
1879 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00001880
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001881 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001882
1883 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00001884 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1885 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00001886
Ken Dyck160146e2010-01-27 17:10:57 +00001887 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00001888
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001889 // Set the llvm linkage type as appropriate.
David Majnemer27d69db2014-04-28 22:17:59 +00001890 llvm::GlobalValue::LinkageTypes Linkage =
1891 getLLVMLinkageVarDefinition(D, GV->isConstant());
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001892 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00001893 if (D->hasAttr<DLLImportAttr>())
1894 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1895 else if (D->hasAttr<DLLExportAttr>())
1896 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00001897
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001898 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnerf49573d2009-08-05 05:20:29 +00001899 // common vars aren't constant even if declared const.
1900 GV->setConstant(false);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001901
Rafael Espindola502f65a2014-05-05 20:21:03 +00001902 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001903
John McCallcdf7ef52010-11-06 09:44:32 +00001904 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00001905 if (NeedsGlobalCtor || NeedsGlobalDtor)
1906 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00001907
Kostya Serebryany28a26c82012-08-21 06:53:28 +00001908 // If we are compiling with ASan, add metadata indicating dynamically
1909 // initialized globals.
Will Dietzf54319c2013-01-18 11:30:38 +00001910 if (SanOpts.Address && NeedsGlobalCtor) {
Kostya Serebryany28a26c82012-08-21 06:53:28 +00001911 llvm::Module &M = getModule();
1912
1913 llvm::NamedMDNode *DynamicInitializers =
1914 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1915 llvm::Value *GlobalToAdd[] = { GV };
1916 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1917 DynamicInitializers->addOperand(ThisGlobal);
1918 }
1919
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001920 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00001921 if (CGDebugInfo *DI = getModuleDebugInfo())
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001922 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00001923 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001924}
Chris Lattner09153c02007-06-22 18:48:09 +00001925
David Majnemer9832a3d2014-04-10 16:53:16 +00001926static bool isVarDeclStrongDefinition(const VarDecl *D, bool NoCommon) {
1927 // Don't give variables common linkage if -fno-common was specified unless it
1928 // was overridden by a NoCommon attribute.
1929 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
1930 return true;
1931
1932 // C11 6.9.2/2:
1933 // A declaration of an identifier for an object that has file scope without
1934 // an initializer, and without a storage-class specifier or with the
1935 // storage-class specifier static, constitutes a tentative definition.
1936 if (D->getInit() || D->hasExternalStorage())
1937 return true;
1938
1939 // A variable cannot be both common and exist in a section.
1940 if (D->hasAttr<SectionAttr>())
1941 return true;
1942
1943 // Thread local vars aren't considered common linkage.
1944 if (D->getTLSKind())
1945 return true;
1946
1947 // Tentative definitions marked with WeakImportAttr are true definitions.
1948 if (D->hasAttr<WeakImportAttr>())
1949 return true;
1950
1951 return false;
1952}
1953
David Majnemer27d69db2014-04-28 22:17:59 +00001954llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageforDeclarator(
1955 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable,
1956 bool UseThunkForDtorVariant) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001957 if (Linkage == GVA_Internal)
1958 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00001959
1960 if (D->hasAttr<WeakAttr>()) {
1961 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001962 return llvm::GlobalVariable::WeakODRLinkage;
1963 else
1964 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00001965 }
1966
1967 // We are guaranteed to have a strong definition somewhere else,
1968 // so we can use available_externally linkage.
1969 if (Linkage == GVA_AvailableExternally)
1970 return llvm::Function::AvailableExternallyLinkage;
1971
1972 // LinkOnceODRLinkage is insufficient if the symbol is required to exist in
1973 // the symbol table. Promote the linkage to WeakODRLinkage to preserve the
1974 // semantics of LinkOnceODRLinkage while providing visibility in the symbol
1975 // table.
1976 llvm::GlobalValue::LinkageTypes OnceLinkage =
1977 llvm::GlobalValue::LinkOnceODRLinkage;
1978 if (D->hasAttr<DLLExportAttr>() || D->hasAttr<DLLImportAttr>())
1979 OnceLinkage = llvm::GlobalVariable::WeakODRLinkage;
1980
1981 // Note that Apple's kernel linker doesn't support symbol
1982 // coalescing, so we need to avoid linkonce and weak linkages there.
1983 // Normally, this means we just map to internal, but for explicit
1984 // instantiations we'll map to external.
1985
1986 // In C++, the compiler has to emit a definition in every translation unit
1987 // that references the function. We should use linkonce_odr because
1988 // a) if all references in this translation unit are optimized away, we
1989 // don't need to codegen it. b) if the function persists, it needs to be
1990 // merged with other definitions. c) C++ has the ODR, so we know the
1991 // definition is dependable.
1992 if (Linkage == GVA_DiscardableODR)
1993 return !Context.getLangOpts().AppleKext ? OnceLinkage
1994 : llvm::Function::InternalLinkage;
1995
1996 // An explicit instantiation of a template has weak linkage, since
1997 // explicit instantiations can occur in multiple translation units
1998 // and must all be equivalent. However, we are not allowed to
1999 // throw away these explicit instantiations.
2000 if (Linkage == GVA_StrongODR)
2001 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2002 : llvm::Function::ExternalLinkage;
2003
2004 // Destructor variants in the Microsoft C++ ABI are always linkonce_odr thunks
2005 // emitted on an as-needed basis.
2006 if (UseThunkForDtorVariant)
2007 return OnceLinkage;
2008
2009 // If required by the ABI, give definitions of static data members with inline
2010 // initializers at least linkonce_odr linkage.
2011 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
2012 isa<VarDecl>(D) &&
2013 isVarDeclInlineInitializedStaticDataMember(cast<VarDecl>(D)))
2014 return OnceLinkage;
2015
2016 // C++ doesn't have tentative definitions and thus cannot have common
2017 // linkage.
2018 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2019 !isVarDeclStrongDefinition(cast<VarDecl>(D), CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00002020 return llvm::GlobalVariable::CommonLinkage;
2021
David Majnemer27d69db2014-04-28 22:17:59 +00002022 // selectany symbols are externally visible, so use weak instead of
2023 // linkonce. MSVC optimizes away references to const selectany globals, so
2024 // all definitions should be the same and ODR linkage should be used.
2025 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2026 if (D->hasAttr<SelectAnyAttr>())
2027 return llvm::GlobalVariable::WeakODRLinkage;
2028
2029 // Otherwise, we have strong external linkage.
2030 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002031 return llvm::GlobalVariable::ExternalLinkage;
2032}
2033
David Majnemer27d69db2014-04-28 22:17:59 +00002034llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2035 const VarDecl *VD, bool IsConstant) {
2036 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2037 return getLLVMLinkageforDeclarator(VD, Linkage, IsConstant,
2038 /*UseThunkForDtorVariant=*/false);
2039}
2040
John McCall49954ca2012-12-12 22:21:47 +00002041/// Replace the uses of a function that was declared with a non-proto type.
2042/// We want to silently drop extra arguments from call sites
2043static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2044 llvm::Function *newFn) {
2045 // Fast path.
2046 if (old->use_empty()) return;
2047
2048 llvm::Type *newRetTy = newFn->getReturnType();
2049 SmallVector<llvm::Value*, 4> newArgs;
2050
2051 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2052 ui != ue; ) {
2053 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002054 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00002055
2056 // Recognize and replace uses of bitcasts. Most calls to
2057 // unprototyped functions will use bitcasts.
2058 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2059 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2060 replaceUsesOfNonProtoConstant(bitcast, newFn);
2061 continue;
2062 }
2063
2064 // Recognize calls to the function.
2065 llvm::CallSite callSite(user);
2066 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002067 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00002068
2069 // If the return types don't match exactly, then we can't
2070 // transform this call unless it's dead.
2071 if (callSite->getType() != newRetTy && !callSite->use_empty())
2072 continue;
2073
2074 // Get the call site's attribute list.
Bill Wendling290d9522013-01-27 02:46:53 +00002075 SmallVector<llvm::AttributeSet, 8> newAttrs;
John McCall49954ca2012-12-12 22:21:47 +00002076 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2077
2078 // Collect any return attributes from the call.
Bill Wendling304f6f02013-01-21 21:57:40 +00002079 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
Bill Wendlingb7abb302013-01-21 22:45:00 +00002080 newAttrs.push_back(
Bill Wendling290d9522013-01-27 02:46:53 +00002081 llvm::AttributeSet::get(newFn->getContext(),
2082 oldAttrs.getRetAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00002083
2084 // If the function was passed too few arguments, don't transform.
2085 unsigned newNumArgs = newFn->arg_size();
2086 if (callSite.arg_size() < newNumArgs) continue;
2087
2088 // If extra arguments were passed, we silently drop them.
2089 // If any of the types mismatch, we don't transform.
2090 unsigned argNo = 0;
2091 bool dontTransform = false;
2092 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2093 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2094 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2095 dontTransform = true;
2096 break;
2097 }
2098
2099 // Add any parameter attributes.
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002100 if (oldAttrs.hasAttributes(argNo + 1))
2101 newAttrs.
Bill Wendling290d9522013-01-27 02:46:53 +00002102 push_back(llvm::
2103 AttributeSet::get(newFn->getContext(),
2104 oldAttrs.getParamAttributes(argNo + 1)));
John McCall49954ca2012-12-12 22:21:47 +00002105 }
2106 if (dontTransform)
2107 continue;
2108
Bill Wendling63ffde52013-01-18 21:26:07 +00002109 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
Bill Wendling290d9522013-01-27 02:46:53 +00002110 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2111 oldAttrs.getFnAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00002112
2113 // Okay, we can transform this. Create the new call instruction and copy
2114 // over the required information.
2115 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2116
2117 llvm::CallSite newCall;
2118 if (callSite.isCall()) {
2119 newCall = llvm::CallInst::Create(newFn, newArgs, "",
2120 callSite.getInstruction());
2121 } else {
2122 llvm::InvokeInst *oldInvoke =
2123 cast<llvm::InvokeInst>(callSite.getInstruction());
2124 newCall = llvm::InvokeInst::Create(newFn,
2125 oldInvoke->getNormalDest(),
2126 oldInvoke->getUnwindDest(),
2127 newArgs, "",
2128 callSite.getInstruction());
2129 }
2130 newArgs.clear(); // for the next iteration
2131
2132 if (!newCall->getType()->isVoidTy())
2133 newCall->takeName(callSite.getInstruction());
2134 newCall.setAttributes(
2135 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2136 newCall.setCallingConv(callSite.getCallingConv());
2137
2138 // Finally, remove the old call, replacing any uses with the new one.
2139 if (!callSite->use_empty())
2140 callSite->replaceAllUsesWith(newCall.getInstruction());
2141
2142 // Copy debug location attached to CI.
2143 if (!callSite->getDebugLoc().isUnknown())
2144 newCall->setDebugLoc(callSite->getDebugLoc());
2145 callSite->eraseFromParent();
2146 }
2147}
2148
Chris Lattner36797ab2009-05-05 06:16:31 +00002149/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2150/// implement a function with no prototype, e.g. "int foo() {}". If there are
2151/// existing call uses of the old function in the module, this adjusts them to
2152/// call the new function directly.
2153///
2154/// This is not just a cleanup: the always_inline pass requires direct calls to
2155/// functions to be able to inline them. If there is a bitcast in the way, it
2156/// won't inline them. Instcombine normally deletes these calls, but it isn't
2157/// run at -O0.
2158static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2159 llvm::Function *NewFn) {
2160 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00002161 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00002162
John McCall49954ca2012-12-12 22:21:47 +00002163 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00002164}
2165
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00002166void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2167 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2168 // If we have a definition, this might be a deferred decl. If the
2169 // instantiation is explicit, make sure we emit it at the end.
2170 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2171 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00002172
2173 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00002174}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002175
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002176void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2177 llvm::GlobalValue *GV) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00002178 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00002179
John McCall46288ef2011-03-09 08:12:35 +00002180 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00002181 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2182 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00002183
Chris Lattnereb7466d2009-05-12 20:58:15 +00002184 // Get or create the prototype for the function.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002185 if (!GV) {
2186 llvm::Constant *C =
2187 GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
Mike Stump11289f42009-09-09 15:08:12 +00002188
Rafael Espindola489c66b2014-05-08 14:33:38 +00002189 // Strip off a bitcast if we got one back.
2190 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
2191 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2192 GV = cast<llvm::GlobalValue>(CE->getOperand(0));
2193 } else {
2194 GV = cast<llvm::GlobalValue>(C);
2195 }
Chris Lattnera85d68e2009-03-21 09:25:43 +00002196 }
Mike Stump11289f42009-09-09 15:08:12 +00002197
Rafael Espindola489c66b2014-05-08 14:33:38 +00002198 if (!GV->isDeclaration()) {
Argyrios Kyrtzidisf405dd62013-11-23 18:41:35 +00002199 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2200 return;
2201 }
Mike Stump11289f42009-09-09 15:08:12 +00002202
Rafael Espindola489c66b2014-05-08 14:33:38 +00002203 if (GV->getType()->getElementType() != Ty) {
Daniel Dunbar99d28352009-03-09 23:53:08 +00002204 // If the types mismatch then we have to rewrite the definition.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002205 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00002206
Chris Lattner5eaee562009-03-21 08:38:50 +00002207 // F is the Function* for the one with the wrong type, we must make a new
2208 // Function* and update everything that used F (a declaration) with the new
2209 // Function* (which will be a definition).
2210 //
2211 // This happens if there is a prototype for a function
2212 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00002213 // (e.g. "int f(int x)"). Move the old function aside so that it
2214 // doesn't interfere with GetAddrOfFunction.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002215 GV->setName(StringRef());
2216 auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00002217
John McCall49954ca2012-12-12 22:21:47 +00002218 // This might be an implementation of a function without a
2219 // prototype, in which case, try to do special replacement of
2220 // calls which match the new prototype. The really key thing here
2221 // is that we also potentially drop arguments from the call site
2222 // so as to make a direct call, which makes the inliner happier
2223 // and suppresses a number of optimizer warnings (!) about
2224 // dropping arguments.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002225 if (!GV->use_empty()) {
2226 ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
2227 GV->removeDeadConstantUsers();
Chris Lattnereb7466d2009-05-12 20:58:15 +00002228 }
Mike Stump11289f42009-09-09 15:08:12 +00002229
Chris Lattner5eaee562009-03-21 08:38:50 +00002230 // Replace uses of F with the Function we will endow with a body.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002231 if (!GV->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00002232 llvm::Constant *NewPtrForOldDecl =
Rafael Espindola489c66b2014-05-08 14:33:38 +00002233 llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
2234 GV->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattner36797ab2009-05-05 06:16:31 +00002235 }
Mike Stump11289f42009-09-09 15:08:12 +00002236
Chris Lattner5eaee562009-03-21 08:38:50 +00002237 // Ok, delete the old function now, which is dead.
Rafael Espindola489c66b2014-05-08 14:33:38 +00002238 GV->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00002239
Rafael Espindola489c66b2014-05-08 14:33:38 +00002240 GV = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002241 }
Mike Stump11289f42009-09-09 15:08:12 +00002242
John McCall8e7cb6d2010-11-02 21:04:24 +00002243 // We need to set linkage and visibility on the function before
2244 // generating code for it because various parts of IR generation
2245 // want to propagate this information down (e.g. to local static
2246 // declarations).
Rafael Espindola489c66b2014-05-08 14:33:38 +00002247 llvm::Function *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002248 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002249
John McCall8e7cb6d2010-11-02 21:04:24 +00002250 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00002251 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00002252
Richard Smithdf931ce2013-04-06 05:00:46 +00002253 MaybeHandleStaticInExternC(D, Fn);
2254
John McCalla738c252011-03-09 04:27:21 +00002255 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00002256
Daniel Dunbar38932572009-04-14 08:05:55 +00002257 SetFunctionDefinitionAttributes(D, Fn);
2258 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00002259
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002260 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002261 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002262 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002263 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002264 if (D->hasAttr<AnnotateAttr>())
2265 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002266}
2267
John McCall7ec50432010-03-19 23:29:14 +00002268void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2269 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002270 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00002271 assert(AA && "Not an alias?");
2272
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002273 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00002274
John McCall7ec50432010-03-19 23:29:14 +00002275 // If there is a definition in the module, then it wins over the alias.
2276 // This is dubious, but allow it to be safe. Just ignore the alias.
2277 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2278 if (Entry && !Entry->isDeclaration())
2279 return;
2280
Rafael Espindola208b5c02013-10-22 19:26:13 +00002281 Aliases.push_back(GD);
2282
Chris Lattner2192fe52011-07-18 04:24:23 +00002283 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00002284
2285 // Create a reference to the named value. This ensures that it is emitted
2286 // if a deferred decl.
2287 llvm::Constant *Aliasee;
2288 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002289 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00002290 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00002291 else
John McCall7ec50432010-03-19 23:29:14 +00002292 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson9793f0e2009-07-29 22:16:19 +00002293 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattner54041692009-03-22 21:47:11 +00002294
2295 // Create the new alias itself, but don't set a name yet.
Mike Stump11289f42009-09-09 15:08:12 +00002296 llvm::GlobalValue *GA =
Chris Lattner54041692009-03-22 21:47:11 +00002297 new llvm::GlobalAlias(Aliasee->getType(),
2298 llvm::Function::ExternalLinkage,
2299 "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00002300
Chris Lattner54041692009-03-22 21:47:11 +00002301 if (Entry) {
John McCall7ec50432010-03-19 23:29:14 +00002302 assert(Entry->isDeclaration());
2303
Chris Lattner54041692009-03-22 21:47:11 +00002304 // If there is a declaration in the module, then we had an extern followed
2305 // by the alias, as in:
2306 // extern int test6();
2307 // ...
2308 // int test6() __attribute__((alias("test7")));
2309 //
2310 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00002311 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002312
Owen Andersonade90fd2009-07-29 18:54:39 +00002313 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00002314 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00002315 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00002316 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00002317 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00002318 }
Mike Stump11289f42009-09-09 15:08:12 +00002319
Daniel Dunbar38932572009-04-14 08:05:55 +00002320 // Set attributes which are particular to an alias; this is a
2321 // specialization of the attributes which may be set on a global
2322 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002323 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00002324 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2325 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002326 if (FD->hasBody())
Nico Rieckbb0554f2014-01-14 15:23:53 +00002327 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar38932572009-04-14 08:05:55 +00002328 } else {
Nico Rieckbb0554f2014-01-14 15:23:53 +00002329 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar38932572009-04-14 08:05:55 +00002330 }
Mike Stump11289f42009-09-09 15:08:12 +00002331 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00002332 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002333 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00002334 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2335 }
2336
2337 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00002338}
2339
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002340llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00002341 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00002342 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002343 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00002344}
Chris Lattner1eec6602007-08-31 04:31:45 +00002345
Daniel Dunbar64509b22009-07-23 22:52:48 +00002346static llvm::StringMapEntry<llvm::Constant*> &
2347GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2348 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00002349 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00002350 bool &IsUTF16,
2351 unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002352 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002353 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002354
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002355 // Check for simple case.
2356 if (!Literal->containsNonAsciiOrNull()) {
2357 StringLength = NumBytes;
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002358 return Map.GetOrCreateValue(String);
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002359 }
2360
Bill Wendling82b87f12012-03-30 00:26:17 +00002361 // Otherwise, convert the UTF8 literals into a string of shorts.
2362 IsUTF16 = true;
2363
2364 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divackye6377112012-09-06 15:59:27 +00002365 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002366 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00002367
Fariborz Jahanian535618b2010-09-07 19:57:04 +00002368 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2369 &ToPtr, ToPtr + NumBytes,
2370 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00002371
Daniel Dunbar91ade142009-07-23 23:41:22 +00002372 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00002373 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00002374
Bill Wendling82b87f12012-03-30 00:26:17 +00002375 // Add an explicit null.
2376 *ToPtr = 0;
2377 return Map.
2378 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2379 (StringLength + 1) * 2));
Daniel Dunbar64509b22009-07-23 22:52:48 +00002380}
2381
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002382static llvm::StringMapEntry<llvm::Constant*> &
2383GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling07635cc2012-03-29 22:12:09 +00002384 const StringLiteral *Literal,
2385 unsigned &StringLength) {
2386 StringRef String = Literal->getString();
2387 StringLength = String.size();
2388 return Map.GetOrCreateValue(String);
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002389}
2390
Daniel Dunbar64509b22009-07-23 22:52:48 +00002391llvm::Constant *
2392CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2393 unsigned StringLength = 0;
2394 bool isUTF16 = false;
2395 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00002396 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002397 getDataLayout().isLittleEndian(),
Daniel Dunbar91ade142009-07-23 23:41:22 +00002398 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002399
Daniel Dunbar64509b22009-07-23 22:52:48 +00002400 if (llvm::Constant *C = Entry.getValue())
2401 return C;
Mike Stump11289f42009-09-09 15:08:12 +00002402
Chris Lattnerece04092012-02-07 00:39:47 +00002403 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00002404 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002405 llvm::Value *V;
2406
Chris Lattneraa64ca22009-07-16 16:48:25 +00002407 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00002408 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002409 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002410 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002411 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00002412 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00002413 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002414 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2415 CFConstantStringClassRef = V;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002416 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002417 else
2418 V = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00002419
Anders Carlssonc2480a52008-11-15 18:54:24 +00002420 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00002421
Chris Lattner2192fe52011-07-18 04:24:23 +00002422 llvm::StructType *STy =
Anders Carlssonc2480a52008-11-15 18:54:24 +00002423 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2424
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002425 llvm::Constant *Fields[4];
Douglas Gregor91f84212008-12-11 16:49:14 +00002426
Anders Carlssonb04ea612007-08-21 00:21:21 +00002427 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002428 Fields[0] = cast<llvm::ConstantExpr>(V);
Mike Stump11289f42009-09-09 15:08:12 +00002429
Anders Carlssonb04ea612007-08-21 00:21:21 +00002430 // Flags.
Chris Lattner2192fe52011-07-18 04:24:23 +00002431 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00002432 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00002433 llvm::ConstantInt::get(Ty, 0x07C8);
2434
Anders Carlssonb04ea612007-08-21 00:21:21 +00002435 // String pointer.
Bill Wendling82b87f12012-03-30 00:26:17 +00002436 llvm::Constant *C = 0;
2437 if (isUTF16) {
2438 ArrayRef<uint16_t> Arr =
David Greene0a528db2013-01-15 22:09:41 +00002439 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2440 const_cast<char *>(Entry.getKey().data())),
Bill Wendling82b87f12012-03-30 00:26:17 +00002441 Entry.getKey().size() / 2);
2442 C = llvm::ConstantDataArray::get(VMContext, Arr);
2443 } else {
2444 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2445 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002446
Bill Wendling86131f22012-01-10 08:46:39 +00002447 // Note: -fwritable-strings doesn't make the backing store strings of
2448 // CFStrings writable. (See <rdar://problem/10657500>)
Mike Stump11289f42009-09-09 15:08:12 +00002449 llvm::GlobalVariable *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00002450 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2451 llvm::GlobalValue::PrivateLinkage, C, ".str");
Rafael Espindolae79d43da2011-01-17 16:31:00 +00002452 GV->setUnnamedAddr(true);
Ulrich Weigandfa806422013-05-06 16:23:57 +00002453 // Don't enforce the target's minimum global alignment, since the only use
2454 // of the string is via this class initializer.
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002455 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2456 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2457 // that changes the section it ends in, which surprises ld64.
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002458 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00002459 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2460 GV->setAlignment(Align.getQuantity());
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002461 GV->setSection("__TEXT,__ustring");
Daniel Dunbar9c8cd4c2011-04-12 23:30:52 +00002462 } else {
2463 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2464 GV->setAlignment(Align.getQuantity());
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002465 GV->setSection("__TEXT,__cstring,cstring_literals");
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002466 }
Bill Wendling82b87f12012-03-30 00:26:17 +00002467
2468 // String.
Jay Foaded8db7d2011-07-21 14:31:17 +00002469 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00002470
Bill Wendling82b87f12012-03-30 00:26:17 +00002471 if (isUTF16)
2472 // Cast the UTF16 string to the correct type.
2473 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2474
Anders Carlssonb04ea612007-08-21 00:21:21 +00002475 // String length.
2476 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00002477 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002478
Anders Carlssonb04ea612007-08-21 00:21:21 +00002479 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00002480 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00002481 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2482 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00002483 "_unnamed_cfstring_");
Rafael Espindola8ff16102014-01-20 20:13:11 +00002484 GV->setSection("__DATA,__cfstring");
Daniel Dunbar64509b22009-07-23 22:52:48 +00002485 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00002486
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00002487 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002488}
Chris Lattnerfb300092007-11-28 05:34:05 +00002489
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002490llvm::Constant *
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002491CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002492 unsigned StringLength = 0;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002493 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002494 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002495
2496 if (llvm::Constant *C = Entry.getValue())
2497 return C;
2498
Chris Lattner00a10ca2012-02-06 22:47:00 +00002499 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002500 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002501 llvm::Value *V;
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00002502 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002503 if (!ConstantStringClassRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002504 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2192fe52011-07-18 04:24:23 +00002505 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002506 llvm::Constant *GV;
John McCall5fb5df92012-06-20 06:18:46 +00002507 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002508 std::string str =
2509 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2510 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002511 GV = getObjCRuntime().GetClassGlobal(str);
2512 // Make sure the result is of the correct type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002513 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002514 V = llvm::ConstantExpr::getBitCast(GV, PTy);
2515 ConstantStringClassRef = V;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002516 } else {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002517 std::string str =
2518 StringClass.empty() ? "_NSConstantStringClassReference"
2519 : "_" + StringClass + "ClassReference";
Chris Lattner2192fe52011-07-18 04:24:23 +00002520 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002521 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002522 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002523 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2524 ConstantStringClassRef = V;
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002525 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002526 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002527 else
2528 V = ConstantStringClassRef;
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002529
2530 if (!NSConstantStringType) {
2531 // Construct the type for a constant NSString.
Alp Toker2dea15b2013-12-17 01:22:38 +00002532 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002533 D->startDefinition();
2534
2535 QualType FieldTypes[3];
2536
2537 // const int *isa;
2538 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2539 // const char *str;
2540 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2541 // unsigned int length;
2542 FieldTypes[2] = Context.UnsignedIntTy;
2543
2544 // Create fields
2545 for (unsigned i = 0; i < 3; ++i) {
2546 FieldDecl *Field = FieldDecl::Create(Context, D,
2547 SourceLocation(),
2548 SourceLocation(), 0,
2549 FieldTypes[i], /*TInfo=*/0,
2550 /*BitWidth=*/0,
2551 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002552 ICIS_NoInit);
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002553 Field->setAccess(AS_public);
2554 D->addDecl(Field);
2555 }
2556
2557 D->completeDefinition();
2558 QualType NSTy = Context.getTagDeclType(D);
2559 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2560 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002561
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002562 llvm::Constant *Fields[3];
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002563
2564 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002565 Fields[0] = cast<llvm::ConstantExpr>(V);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002566
2567 // String pointer.
Chris Lattner9c818332012-02-05 02:30:40 +00002568 llvm::Constant *C =
2569 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002570
2571 llvm::GlobalValue::LinkageTypes Linkage;
2572 bool isConstant;
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002573 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002574 isConstant = !LangOpts.WritableStrings;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002575
2576 llvm::GlobalVariable *GV =
2577 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2578 ".str");
Rafael Espindolade089d42011-01-17 22:11:21 +00002579 GV->setUnnamedAddr(true);
Ulrich Weigandfa806422013-05-06 16:23:57 +00002580 // Don't enforce the target's minimum global alignment, since the only use
2581 // of the string is via this class initializer.
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002582 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2583 GV->setAlignment(Align.getQuantity());
Jay Foaded8db7d2011-07-21 14:31:17 +00002584 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002585
2586 // String length.
Chris Lattner2192fe52011-07-18 04:24:23 +00002587 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002588 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2589
2590 // The struct.
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002591 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002592 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2593 llvm::GlobalVariable::PrivateLinkage, C,
2594 "_unnamed_nsstring_");
Rafael Espindola63582d62014-01-20 15:19:43 +00002595 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2596 const char *NSStringNonFragileABISection =
Rafael Espindola8ff16102014-01-20 20:13:11 +00002597 "__DATA,__objc_stringobj,regular,no_dead_strip";
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002598 // FIXME. Fix section.
Rafael Espindola8ff16102014-01-20 20:13:11 +00002599 GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2600 ? NSStringNonFragileABISection
2601 : NSStringSection);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002602 Entry.setValue(GV);
2603
2604 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002605}
2606
Douglas Gregor636e2002011-08-09 17:23:49 +00002607QualType CodeGenModule::getObjCFastEnumerationStateType() {
2608 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00002609 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00002610 D->startDefinition();
2611
2612 QualType FieldTypes[] = {
2613 Context.UnsignedLongTy,
2614 Context.getPointerType(Context.getObjCIdType()),
2615 Context.getPointerType(Context.UnsignedLongTy),
2616 Context.getConstantArrayType(Context.UnsignedLongTy,
2617 llvm::APInt(32, 5), ArrayType::Normal, 0)
2618 };
2619
2620 for (size_t i = 0; i < 4; ++i) {
2621 FieldDecl *Field = FieldDecl::Create(Context,
2622 D,
2623 SourceLocation(),
2624 SourceLocation(), 0,
2625 FieldTypes[i], /*TInfo=*/0,
2626 /*BitWidth=*/0,
2627 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002628 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00002629 Field->setAccess(AS_public);
2630 D->addDecl(Field);
2631 }
2632
2633 D->completeDefinition();
2634 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2635 }
2636
2637 return ObjCFastEnumerationStateType;
2638}
2639
Eli Friedmanfcec6302011-11-01 02:23:42 +00002640llvm::Constant *
2641CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2642 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2643
2644 // Don't emit it as the address of the string, emit the string data itself
2645 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002646 if (E->getCharByteWidth() == 1) {
2647 SmallString<64> Str(E->getString());
2648
2649 // Resize the string to the right size, which is indicated by its type.
2650 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2651 Str.resize(CAT->getSize().getZExtValue());
2652 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2653 }
Chris Lattner9c818332012-02-05 02:30:40 +00002654
2655 llvm::ArrayType *AType =
2656 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2657 llvm::Type *ElemTy = AType->getElementType();
2658 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00002659
2660 // Wide strings have either 2-byte or 4-byte elements.
2661 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2662 SmallVector<uint16_t, 32> Elements;
2663 Elements.reserve(NumElements);
2664
2665 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2666 Elements.push_back(E->getCodeUnit(i));
2667 Elements.resize(NumElements);
2668 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00002669 }
2670
Chris Lattner02cb1712012-02-06 22:52:04 +00002671 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2672 SmallVector<uint32_t, 32> Elements;
2673 Elements.reserve(NumElements);
2674
2675 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2676 Elements.push_back(E->getCodeUnit(i));
2677 Elements.resize(NumElements);
2678 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00002679}
2680
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002681/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2682/// constant array for the given string literal.
2683llvm::Constant *
2684CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
Ulrich Weigandfa806422013-05-06 16:23:57 +00002685 CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
David Majnemer58e5bee2014-03-24 21:43:36 +00002686
2687 llvm::StringMapEntry<llvm::GlobalVariable *> *Entry = nullptr;
2688 llvm::GlobalVariable *GV = nullptr;
2689 if (!LangOpts.WritableStrings) {
2690 llvm::StringMap<llvm::GlobalVariable *> *ConstantStringMap = nullptr;
2691 switch (S->getCharByteWidth()) {
2692 case 1:
2693 ConstantStringMap = &Constant1ByteStringMap;
2694 break;
2695 case 2:
2696 ConstantStringMap = &Constant2ByteStringMap;
2697 break;
2698 case 4:
2699 ConstantStringMap = &Constant4ByteStringMap;
2700 break;
2701 default:
2702 llvm_unreachable("unhandled byte width!");
2703 }
2704 Entry = &ConstantStringMap->GetOrCreateValue(S->getBytes());
2705 GV = Entry->getValue();
Eli Friedman49ddc5f2009-11-16 05:55:46 +00002706 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00002707
David Majnemer58e5bee2014-03-24 21:43:36 +00002708 if (!GV) {
2709 SmallString<256> MangledNameBuffer;
2710 StringRef GlobalVariableName;
2711 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00002712
David Majnemer58e5bee2014-03-24 21:43:36 +00002713 // Mangle the string literal if the ABI allows for it. However, we cannot
2714 // do this if we are compiling with ASan or -fwritable-strings because they
2715 // rely on strings having normal linkage.
2716 if (!LangOpts.WritableStrings && !SanOpts.Address &&
2717 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2718 llvm::raw_svector_ostream Out(MangledNameBuffer);
2719 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2720 Out.flush();
2721
2722 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2723 GlobalVariableName = MangledNameBuffer;
2724 } else {
Alp Toker5f072d82014-04-19 23:55:49 +00002725 LT = llvm::GlobalValue::PrivateLinkage;
David Majnemer58e5bee2014-03-24 21:43:36 +00002726 GlobalVariableName = ".str";
2727 }
2728
2729 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2730 unsigned AddrSpace = 0;
2731 if (getLangOpts().OpenCL)
2732 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
2733
2734 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2735 GV = new llvm::GlobalVariable(
2736 getModule(), C->getType(), !LangOpts.WritableStrings, LT, C,
2737 GlobalVariableName, /*InsertBefore=*/nullptr,
2738 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2739 GV->setUnnamedAddr(true);
2740 if (Entry)
2741 Entry->setValue(GV);
2742 }
2743
2744 if (Align.getQuantity() > GV->getAlignment())
2745 GV->setAlignment(Align.getQuantity());
2746
Eli Friedmanfcec6302011-11-01 02:23:42 +00002747 return GV;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002748}
2749
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002750/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2751/// array for the given ObjCEncodeExpr node.
2752llvm::Constant *
2753CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2754 std::string Str;
2755 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00002756
2757 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002758}
2759
2760
Chris Lattner36fc8792008-02-11 00:02:17 +00002761/// GenerateWritableString -- Creates storage for a string literal.
John McCall9b24df42011-08-04 01:03:22 +00002762static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
Chris Lattnerfb300092007-11-28 05:34:05 +00002763 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00002764 CodeGenModule &CGM,
John McCall9b24df42011-08-04 01:03:22 +00002765 const char *GlobalName,
2766 unsigned Alignment) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002767 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00002768 llvm::Constant *C =
Chris Lattner9c818332012-02-05 02:30:40 +00002769 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00002770
David Majnemer58e5bee2014-03-24 21:43:36 +00002771 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
Joey Gouly561bba22013-11-14 18:26:10 +00002772 unsigned AddrSpace = 0;
2773 if (CGM.getLangOpts().OpenCL)
2774 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2775
Chris Lattnerfb300092007-11-28 05:34:05 +00002776 // Create a global variable for this string
Joey Gouly561bba22013-11-14 18:26:10 +00002777 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
2778 CGM.getModule(), C->getType(), constant,
2779 llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0,
2780 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall9b24df42011-08-04 01:03:22 +00002781 GV->setAlignment(Alignment);
Rafael Espindolab7f60e32011-01-10 22:34:03 +00002782 GV->setUnnamedAddr(true);
2783 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002784}
2785
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002786/// GetAddrOfConstantString - Returns a pointer to a character array
2787/// containing the literal. This contents are exactly that of the
2788/// given string, i.e. it will not be null terminated automatically;
2789/// see GetAddrOfConstantCString. Note that whether the result is
2790/// actually a pointer to an LLVM constant depends on
2791/// Feature.WriteableStrings.
2792///
2793/// The result has pointer to array type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002794llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
John McCall9b24df42011-08-04 01:03:22 +00002795 const char *GlobalName,
2796 unsigned Alignment) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002797 // Get the default prefix if a name wasn't specified.
2798 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00002799 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002800
Ulrich Weigandfa806422013-05-06 16:23:57 +00002801 if (Alignment == 0)
2802 Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2803 .getQuantity();
2804
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002805 // Don't share any string literals if strings aren't constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002806 if (LangOpts.WritableStrings)
John McCall9b24df42011-08-04 01:03:22 +00002807 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
Mike Stump11289f42009-09-09 15:08:12 +00002808
John McCall9b24df42011-08-04 01:03:22 +00002809 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
David Majnemer58e5bee2014-03-24 21:43:36 +00002810 Constant1ByteStringMap.GetOrCreateValue(Str);
Chris Lattnerfb300092007-11-28 05:34:05 +00002811
John McCall9b24df42011-08-04 01:03:22 +00002812 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2813 if (Alignment > GV->getAlignment()) {
2814 GV->setAlignment(Alignment);
2815 }
2816 return GV;
2817 }
Chris Lattnerfb300092007-11-28 05:34:05 +00002818
2819 // Create a global variable for this.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002820 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2821 Alignment);
John McCall9b24df42011-08-04 01:03:22 +00002822 Entry.setValue(GV);
2823 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002824}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002825
2826/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002827/// array containing the literal and a terminating '\0'
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002828/// character. The result has pointer to array type.
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002829llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
John McCall9b24df42011-08-04 01:03:22 +00002830 const char *GlobalName,
2831 unsigned Alignment) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002832 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall9b24df42011-08-04 01:03:22 +00002833 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002834}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002835
Richard Smithe6c01442013-06-05 00:46:14 +00002836llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00002837 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00002838 assert((E->getStorageDuration() == SD_Static ||
2839 E->getStorageDuration() == SD_Thread) && "not a global temporary");
2840 const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl());
2841
2842 // If we're not materializing a subobject of the temporary, keep the
2843 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00002844 QualType MaterializedType = Init->getType();
2845 if (Init == E->GetTemporaryExpr())
2846 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00002847
2848 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2849 if (Slot)
2850 return Slot;
2851
2852 // FIXME: If an externally-visible declaration extends multiple temporaries,
2853 // we need to give each temporary the same name in every translation unit (and
2854 // we also need to make the temporaries externally-visible).
2855 SmallString<256> Name;
2856 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00002857 getCXXABI().getMangleContext().mangleReferenceTemporary(
2858 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00002859 Out.flush();
2860
Richard Smithe6c01442013-06-05 00:46:14 +00002861 APValue *Value = 0;
2862 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00002863 // We might have a cached constant initializer for this temporary. Note
2864 // that this might have a different value from the value computed by
2865 // evaluating the initializer if the surrounding constant expression
2866 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00002867 Value = getContext().getMaterializedTemporaryValue(E, false);
2868 if (Value && Value->isUninit())
2869 Value = 0;
2870 }
2871
Richard Smitha509f2f2013-06-14 03:07:01 +00002872 // Try evaluating it now, it might have a constant initializer.
2873 Expr::EvalResult EvalResult;
2874 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2875 !EvalResult.hasSideEffects())
2876 Value = &EvalResult.Val;
2877
2878 llvm::Constant *InitialValue = 0;
2879 bool Constant = false;
2880 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00002881 if (Value) {
2882 // The temporary has a constant initializer, use it.
Richard Smitha509f2f2013-06-14 03:07:01 +00002883 InitialValue = EmitConstantValue(*Value, MaterializedType, 0);
2884 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2885 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00002886 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00002887 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00002888 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00002889 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00002890 }
2891
2892 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00002893 llvm::GlobalValue::LinkageTypes Linkage =
2894 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemer846c2832014-04-29 06:18:53 +00002895 // There is no need for this temporary to have global linkage if the global
2896 // variable has external linkage.
David Majnemer27d69db2014-04-28 22:17:59 +00002897 if (Linkage == llvm::GlobalVariable::ExternalLinkage)
2898 Linkage = llvm::GlobalVariable::PrivateLinkage;
2899 unsigned AddrSpace = GetGlobalVarAddressSpace(
2900 VD, getContext().getTargetAddressSpace(MaterializedType));
2901 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
2902 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
2903 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2904 AddrSpace);
David Majnemer846c2832014-04-29 06:18:53 +00002905 setGlobalVisibility(GV, VD);
Richard Smithe6c01442013-06-05 00:46:14 +00002906 GV->setAlignment(
Richard Smitha509f2f2013-06-14 03:07:01 +00002907 getContext().getTypeAlignInChars(MaterializedType).getQuantity());
Richard Smithe6c01442013-06-05 00:46:14 +00002908 if (VD->getTLSKind())
2909 setTLSMode(GV, *VD);
2910 Slot = GV;
2911 return GV;
2912}
2913
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002914/// EmitObjCPropertyImplementations - Emit information for synthesized
2915/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00002916void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002917 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00002918 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002919 // Dynamic is just for type-checking.
2920 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2921 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2922
2923 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00002924 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002925 // we want, that just indicates if the decl came from a
2926 // property. What we want to know is if the method is defined in
2927 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002928 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002929 CodeGenFunction(*this).GenerateObjCGetter(
2930 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002931 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002932 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002933 CodeGenFunction(*this).GenerateObjCSetter(
2934 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002935 }
2936 }
2937}
2938
John McCall6a4fa522011-03-22 07:05:39 +00002939static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002940 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2941 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00002942 ivar; ivar = ivar->getNextIvar())
2943 if (ivar->getType().isDestructedType())
2944 return true;
2945
2946 return false;
2947}
2948
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002949/// EmitObjCIvarInitializations - Emit information for ivar initialization
2950/// for an implementation.
2951void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00002952 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2953 if (needsDestructMethod(D)) {
2954 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2955 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2956 ObjCMethodDecl *DTORMethod =
2957 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002958 cxxSelector, getContext().VoidTy, 0, D,
2959 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00002960 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002961 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00002962 D->addInstanceMethod(DTORMethod);
2963 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00002964 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00002965 }
2966
2967 // If the implementation doesn't have any ivar initializers, we don't need
2968 // a .cxx_construct.
David Chisnalla9e54602011-03-17 14:19:08 +00002969 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002970 return;
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002971
John McCall6a4fa522011-03-22 07:05:39 +00002972 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2973 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002974 // The constructor returns 'self'.
2975 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2976 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002977 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002978 cxxSelector,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002979 getContext().getObjCIdType(), 0,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002980 D, /*isInstance=*/true,
2981 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00002982 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002983 /*isImplicitlyDeclared=*/true,
2984 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002985 ObjCMethodDecl::Required);
2986 D->addInstanceMethod(CTORMethod);
2987 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00002988 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002989}
2990
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002991/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00002992void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Aaron Ballman629afae2014-03-07 19:56:05 +00002993 for (auto *I : ND->decls()) {
2994 if (const auto *VD = dyn_cast<VarDecl>(I))
David Blaikieb00f3602013-09-04 21:07:37 +00002995 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2996 VD->getTemplateSpecializationKind() != TSK_Undeclared)
2997 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00002998 EmitTopLevelDecl(I);
David Blaikieb00f3602013-09-04 21:07:37 +00002999 }
Anders Carlsson237f3492009-04-01 00:58:25 +00003000}
3001
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003002// EmitLinkageSpec - Emit all declarations in a linkage spec.
3003void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00003004 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3005 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003006 ErrorUnsupported(LSD, "linkage spec");
3007 return;
3008 }
3009
Aaron Ballman629afae2014-03-07 19:56:05 +00003010 for (auto *I : LSD->decls()) {
Fariborz Jahanian9dd2e082012-10-26 22:20:25 +00003011 // Meta-data for ObjC class includes references to implemented methods.
3012 // Generate class's method definitions first.
Aaron Ballman629afae2014-03-07 19:56:05 +00003013 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003014 for (auto *M : OID->methods())
3015 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00003016 }
Aaron Ballman629afae2014-03-07 19:56:05 +00003017 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00003018 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003019}
3020
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003021/// EmitTopLevelDecl - Emit code for a single top level declaration.
3022void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003023 // Ignore dependent declarations.
3024 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3025 return;
Mike Stump11289f42009-09-09 15:08:12 +00003026
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003027 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00003028 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00003029 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003030 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00003031 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00003032 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3033 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor70d83e22009-06-29 17:30:29 +00003034 return;
Mike Stump11289f42009-09-09 15:08:12 +00003035
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003036 EmitGlobal(cast<FunctionDecl>(D));
3037 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003038
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003039 case Decl::Var:
Larisse Voufo39a1e502013-08-06 01:03:05 +00003040 // Skip variable templates
3041 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3042 return;
3043 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003044 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003045 break;
3046
John McCall32f44bd2011-04-12 01:01:22 +00003047 // Indirect fields from global anonymous structs and unions can be
3048 // ignored; only the actual variable requires IR gen support.
3049 case Decl::IndirectField:
3050 break;
3051
Anders Carlssonf7475242009-04-15 15:55:24 +00003052 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003053 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00003054 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003055 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00003056 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00003057 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003058 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00003059 case Decl::VarTemplate:
3060 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003061 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00003062 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003063 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00003064 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00003065 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00003066 case Decl::Using: // using X; [C++]
3067 if (CGDebugInfo *DI = getModuleDebugInfo())
3068 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3069 return;
David Blaikief121b932013-05-20 22:50:41 +00003070 case Decl::NamespaceAlias:
3071 if (CGDebugInfo *DI = getModuleDebugInfo())
3072 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3073 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00003074 case Decl::UsingDirective: // using namespace X; [C++]
3075 if (CGDebugInfo *DI = getModuleDebugInfo())
3076 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3077 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00003078 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00003079 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00003080 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3081 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson0ade9712009-11-24 05:16:24 +00003082 return;
3083
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00003084 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00003085 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00003086 case Decl::CXXDestructor:
Francois Pichet1c229c02011-04-22 22:18:13 +00003087 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3088 return;
Reid Klecknere7de47e2013-07-22 13:51:44 +00003089 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00003090 break;
Anders Carlsson87835432009-06-11 21:22:55 +00003091
3092 case Decl::StaticAssert:
3093 // Nothing to do.
3094 break;
3095
Anders Carlssonf7475242009-04-15 15:55:24 +00003096 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00003097
Fariborz Jahanian3654e652009-03-18 22:33:24 +00003098 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00003099 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00003100 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00003101 break;
3102
Douglas Gregorf6102672012-01-01 21:23:57 +00003103 case Decl::ObjCProtocol: {
3104 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
3105 if (Proto->isThisDeclarationADefinition())
3106 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003107 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00003108 }
3109
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003110 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003111 // Categories have properties but don't support synthesize so we
3112 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00003113 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003114 break;
3115
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003116 case Decl::ObjCImplementation: {
3117 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
3118 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003119 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00003120 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00003121 // Emit global variable debug information.
3122 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00003123 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3124 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3125 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003126 break;
Mike Stump11289f42009-09-09 15:08:12 +00003127 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003128 case Decl::ObjCMethod: {
3129 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
3130 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003131 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003132 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3133 break;
3134 }
Mike Stump11289f42009-09-09 15:08:12 +00003135 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00003136 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003137 break;
3138
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003139 case Decl::LinkageSpec:
3140 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003141 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003142
3143 case Decl::FileScopeAsm: {
3144 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003145 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00003146
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003147 const std::string &S = getModule().getModuleInlineAsm();
3148 if (S.empty())
3149 getModule().setModuleInlineAsm(AsmString);
Joerg Sonnenberger8c02a242012-08-10 10:57:52 +00003150 else if (S.end()[-1] == '\n')
Chris Lattner84037d32011-07-23 20:04:25 +00003151 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003152 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00003153 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003154 break;
3155 }
Mike Stump11289f42009-09-09 15:08:12 +00003156
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003157 case Decl::Import: {
3158 ImportDecl *Import = cast<ImportDecl>(D);
3159
3160 // Ignore import declarations that come from imported modules.
3161 if (clang::Module *Owner = Import->getOwningModule()) {
3162 if (getLangOpts().CurrentModule.empty() ||
3163 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3164 break;
3165 }
3166
Douglas Gregorbc25ff42013-01-14 20:53:57 +00003167 ImportedModules.insert(Import->getImportedModule());
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003168 break;
David Blaikie0e716b42014-03-03 23:48:23 +00003169 }
3170
3171 case Decl::ClassTemplateSpecialization: {
3172 const ClassTemplateSpecializationDecl *Spec =
3173 cast<ClassTemplateSpecializationDecl>(D);
3174 if (DebugInfo &&
3175 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition)
3176 DebugInfo->completeTemplateDefinition(*Spec);
3177 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003178
Mike Stump11289f42009-09-09 15:08:12 +00003179 default:
Mike Stump18bb9282009-05-16 07:57:57 +00003180 // Make sure we handled everything we should, every other kind is a
3181 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3182 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003183 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3184 }
3185}
John McCall09ae0322010-07-06 23:57:41 +00003186
3187/// Turns the given pointer into a constant.
3188static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3189 const void *Ptr) {
3190 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00003191 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00003192 return llvm::ConstantInt::get(i64, PtrInt);
3193}
3194
3195static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3196 llvm::NamedMDNode *&GlobalMetadata,
3197 GlobalDecl D,
3198 llvm::GlobalValue *Addr) {
3199 if (!GlobalMetadata)
3200 GlobalMetadata =
3201 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3202
3203 // TODO: should we report variant information for ctors/dtors?
3204 llvm::Value *Ops[] = {
3205 Addr,
3206 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3207 };
Jay Foadea324f12011-04-21 19:59:12 +00003208 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00003209}
3210
Richard Smithdf931ce2013-04-06 05:00:46 +00003211/// For each function which is declared within an extern "C" region and marked
3212/// as 'used', but has internal linkage, create an alias from the unmangled
3213/// name to the mangled name if possible. People expect to be able to refer
3214/// to such functions with an unmangled name from inline assembly within the
3215/// same translation unit.
3216void CodeGenModule::EmitStaticExternCAliases() {
Richard Smithf21c9612013-04-13 01:28:18 +00003217 for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3218 E = StaticExternCValues.end();
3219 I != E; ++I) {
3220 IdentifierInfo *Name = I->first;
3221 llvm::GlobalValue *Val = I->second;
Richard Smith85465e62013-04-06 07:07:44 +00003222 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola060062a2014-03-06 22:15:10 +00003223 addUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
Richard Smith85465e62013-04-06 07:07:44 +00003224 Name->getName(), Val, &getModule()));
3225 }
Richard Smithdf931ce2013-04-06 05:00:46 +00003226}
3227
John McCall09ae0322010-07-06 23:57:41 +00003228/// Emits metadata nodes associating all the global values in the
3229/// current module with the Decls they came from. This is useful for
3230/// projects using IR gen as a subroutine.
3231///
3232/// Since there's currently no way to associate an MDNode directly
3233/// with an llvm::GlobalValue, we create a global named metadata
3234/// with the name 'clang.global.decl.ptrs'.
3235void CodeGenModule::EmitDeclMetadata() {
3236 llvm::NamedMDNode *GlobalMetadata = 0;
3237
3238 // StaticLocalDeclMap
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003239 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
John McCall09ae0322010-07-06 23:57:41 +00003240 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3241 I != E; ++I) {
3242 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3243 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3244 }
3245}
3246
3247/// Emits metadata nodes for all the local variables in the current
3248/// function.
3249void CodeGenFunction::EmitDeclMetadata() {
3250 if (LocalDeclMap.empty()) return;
3251
3252 llvm::LLVMContext &Context = getLLVMContext();
3253
3254 // Find the unique metadata ID for this name.
3255 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3256
3257 llvm::NamedMDNode *GlobalMetadata = 0;
3258
3259 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3260 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3261 const Decl *D = I->first;
3262 llvm::Value *Addr = I->second;
3263
3264 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3265 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foadea324f12011-04-21 19:59:12 +00003266 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall09ae0322010-07-06 23:57:41 +00003267 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3268 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3269 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3270 }
3271 }
3272}
Daniel Dunbar900546d2010-07-16 00:00:15 +00003273
Rafael Espindola3bfa4682013-10-16 19:28:50 +00003274void CodeGenModule::EmitVersionIdentMetadata() {
3275 llvm::NamedMDNode *IdentMetadata =
3276 TheModule.getOrInsertNamedMetadata("llvm.ident");
3277 std::string Version = getClangFullVersion();
3278 llvm::LLVMContext &Ctx = TheModule.getContext();
3279
3280 llvm::Value *IdentNode[] = {
3281 llvm::MDString::get(Ctx, Version)
3282 };
3283 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3284}
3285
Nick Lewycky85c011d2011-05-05 00:08:20 +00003286void CodeGenModule::EmitCoverageFile() {
3287 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky480cb992011-05-04 20:46:58 +00003288 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3289 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3290 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky85c011d2011-05-05 00:08:20 +00003291 llvm::MDString *CoverageFile =
3292 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky480cb992011-05-04 20:46:58 +00003293 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3294 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky85c011d2011-05-05 00:08:20 +00003295 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky480cb992011-05-04 20:46:58 +00003296 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3297 GCov->addOperand(N);
3298 }
3299 }
3300 }
3301}
Nico Webercf4ff5862012-10-11 10:13:44 +00003302
3303llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3304 QualType GuidType) {
3305 // Sema has checked that all uuid strings are of the form
3306 // "12345678-1234-1234-1234-1234567890ab".
3307 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00003308 for (unsigned i = 0; i < 36; ++i) {
3309 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3310 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00003311 }
Nico Webercf4ff5862012-10-11 10:13:44 +00003312
David Majnemerbbecd092013-08-15 19:59:14 +00003313 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00003314
David Majnemerbbecd092013-08-15 19:59:14 +00003315 llvm::Constant *Field3[8];
3316 for (unsigned Idx = 0; Idx < 8; ++Idx)
3317 Field3[Idx] = llvm::ConstantInt::get(
3318 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3319
3320 llvm::Constant *Fields[4] = {
3321 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
3322 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
3323 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3324 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3325 };
3326
3327 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00003328}