blob: ea74abff54053b17b4a155d1d4b68cb3985a73f0 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Chris Lattnerbd360642009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "CodeGenFunction.h"
Dan Gohman3d5aff52010-10-14 23:06:10 +000017#include "CodeGenTBAA.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000018#include "CGCall.h"
John McCall4c40d982010-08-31 07:33:07 +000019#include "CGCXXABI.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000021#include "TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000022#include "clang/Frontend/CodeGenOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/AST/ASTContext.h"
Ken Dyck687cc4a2010-01-26 13:48:07 +000024#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000026#include "clang/AST/DeclCXX.h"
Douglas Gregoraf896892010-06-21 18:41:26 +000027#include "clang/AST/DeclTemplate.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Anders Carlsson1a5e0d72009-11-30 23:41:22 +000029#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000031#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000032#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/TargetInfo.h"
Steve Naroffe9b7d8a2009-04-01 15:50:34 +000034#include "clang/Basic/ConvertUTF.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000035#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000036#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000037#include "llvm/Intrinsics.h"
Chris Lattnerd5b89022009-12-28 21:44:41 +000038#include "llvm/LLVMContext.h"
John McCall6374c332010-03-06 00:35:14 +000039#include "llvm/ADT/Triple.h"
Rafael Espindolac4850c22011-02-10 23:59:36 +000040#include "llvm/Target/Mangler.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000041#include "llvm/Target/TargetData.h"
Gabor Greif6ba728d2010-04-10 02:56:12 +000042#include "llvm/Support/CallSite.h"
Chris Lattner78f7ece2009-11-07 09:22:46 +000043#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000044using namespace clang;
45using namespace CodeGen;
46
John McCallf16aa102010-08-22 21:01:12 +000047static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
48 switch (CGM.getContext().Target.getCXXABI()) {
49 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
50 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
51 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
52 }
53
54 llvm_unreachable("invalid C++ ABI kind");
55 return *CreateItaniumCXXABI(CGM);
56}
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058
Chandler Carruth2811ccf2009-11-12 17:24:48 +000059CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall468ec6c2010-03-04 04:29:44 +000060 llvm::Module &M, const llvm::TargetData &TD,
61 Diagnostic &diags)
John McCalld16c2cf2011-02-08 08:22:06 +000062 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall468ec6c2010-03-04 04:29:44 +000063 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCallf16aa102010-08-22 21:01:12 +000064 ABI(createCXXABI(*this)),
65 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
Dan Gohman3d5aff52010-10-14 23:06:10 +000066 TBAA(0),
Devang Patelaa112892011-03-07 18:45:56 +000067 VTables(*this), Runtime(0),
Fariborz Jahanian4c733072010-10-19 17:19:29 +000068 CFConstantStringClassRef(0), ConstantStringClassRef(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000069 VMContext(M.getContext()),
Daniel Dunbar754b9fb2010-07-16 00:00:19 +000070 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000071 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
Daniel Dunbar754b9fb2010-07-16 00:00:19 +000072 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
John McCalld16c2cf2011-02-08 08:22:06 +000073 BlockObjectAssign(0), BlockObjectDispose(0),
74 BlockDescriptorType(0), GenericBlockLiteralType(0) {
Chris Lattner3c8f1532009-03-21 07:12:05 +000075 if (!Features.ObjC1)
76 Runtime = 0;
77 else if (!Features.NeXTRuntime)
78 Runtime = CreateGNUObjCRuntime(*this);
79 else if (Features.ObjCNonFragileABI)
80 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
81 else
82 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000083
Dan Gohman3d5aff52010-10-14 23:06:10 +000084 // Enable TBAA unless it's suppressed.
85 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
Dan Gohman0b5c4fc2010-10-15 20:23:12 +000086 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
87 ABI.getMangleContext());
Dan Gohman3d5aff52010-10-14 23:06:10 +000088
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000089 // If debug info generation is enabled, create the CGDebugInfo object.
Anders Carlsson20f12a22009-12-06 18:00:51 +000090 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
John McCalld16c2cf2011-02-08 08:22:06 +000091
92 Block.GlobalUniqueCount = 0;
John McCall5936e332011-02-15 09:22:45 +000093
94 // Initialize the type cache.
95 llvm::LLVMContext &LLVMContext = M.getContext();
96 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
98 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
99 PointerWidthInBits = C.Target.getPointerWidth(0);
John McCall34695852011-02-22 06:44:22 +0000100 PointerAlignInBytes =
101 C.toCharUnitsFromBits(C.Target.getPointerAlign(0)).getQuantity();
John McCall5936e332011-02-15 09:22:45 +0000102 IntTy = llvm::IntegerType::get(LLVMContext, C.Target.getIntWidth());
103 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
104 Int8PtrTy = Int8Ty->getPointerTo(0);
105 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Chris Lattner2b94fe32008-03-01 08:45:05 +0000106}
107
108CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +0000109 delete Runtime;
John McCallf16aa102010-08-22 21:01:12 +0000110 delete &ABI;
Dan Gohman4376c852010-10-15 18:04:46 +0000111 delete TBAA;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000112 delete DebugInfo;
113}
114
David Chisnall0d13f6f2010-01-23 02:40:42 +0000115void CodeGenModule::createObjCRuntime() {
116 if (!Features.NeXTRuntime)
117 Runtime = CreateGNUObjCRuntime(*this);
118 else if (Features.ObjCNonFragileABI)
119 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
120 else
121 Runtime = CreateMacObjCRuntime(*this);
122}
123
Ted Kremenek815c78f2008-08-05 18:50:11 +0000124void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000125 EmitDeferred();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000126 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000127 EmitCXXGlobalDtorFunc();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000128 if (Runtime)
129 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
130 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000131 EmitCtorList(GlobalCtors, "llvm.global_ctors");
132 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +0000133 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +0000134 EmitLLVMUsed();
John McCall744016d2010-07-06 23:57:41 +0000135
John McCallb2593832010-09-16 06:16:50 +0000136 SimplifyPersonality();
137
John McCall744016d2010-07-06 23:57:41 +0000138 if (getCodeGenOpts().EmitDeclMetadata)
139 EmitDeclMetadata();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000140}
141
Dan Gohman3d5aff52010-10-14 23:06:10 +0000142llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
143 if (!TBAA)
144 return 0;
145 return TBAA->getTBAAInfo(QTy);
146}
147
148void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
149 llvm::MDNode *TBAAInfo) {
150 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
151}
152
John McCall6374c332010-03-06 00:35:14 +0000153bool CodeGenModule::isTargetDarwin() const {
154 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
155}
156
John McCall32096692011-03-18 02:56:14 +0000157void CodeGenModule::Error(SourceLocation loc, llvm::StringRef error) {
158 unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error);
159 getDiags().Report(Context.getFullLoc(loc), diagID);
160}
161
Daniel Dunbar488e9932008-08-16 00:56:44 +0000162/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000163/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000164void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
165 bool OmitOnError) {
166 if (OmitOnError && getDiags().hasErrorOccurred())
167 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000168 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000169 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000170 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000171 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
172 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000173}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000174
Daniel Dunbar488e9932008-08-16 00:56:44 +0000175/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000176/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000177void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
178 bool OmitOnError) {
179 if (OmitOnError && getDiags().hasErrorOccurred())
180 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000181 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000182 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000183 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000184 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000185}
186
Mike Stump1eb44332009-09-09 15:08:12 +0000187void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000188 const NamedDecl *D) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000189 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000190 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000191 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000192 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000193 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000194
John McCallaf146032010-10-30 11:50:40 +0000195 // Set visibility for definitions.
196 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola071d3af2011-02-01 05:45:26 +0000197 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
198 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000199}
200
John McCallcbfe5022010-08-04 08:34:44 +0000201/// Set the symbol visibility of type information (vtable and RTTI)
202/// associated with the given type.
203void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
204 const CXXRecordDecl *RD,
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000205 TypeVisibilityKind TVK) const {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000206 setGlobalVisibility(GV, RD);
John McCallcbfe5022010-08-04 08:34:44 +0000207
John McCall279b5eb2010-08-12 23:36:15 +0000208 if (!CodeGenOpts.HiddenWeakVTables)
209 return;
210
Anders Carlsson9a86a132011-01-29 20:36:11 +0000211 // We never want to drop the visibility for RTTI names.
212 if (TVK == TVK_ForRTTIName)
213 return;
214
John McCallcbfe5022010-08-04 08:34:44 +0000215 // We want to drop the visibility to hidden for weak type symbols.
216 // This isn't possible if there might be unresolved references
217 // elsewhere that rely on this symbol being visible.
218
John McCall7a536902010-08-05 20:39:18 +0000219 // This should be kept roughly in sync with setThunkVisibility
220 // in CGVTables.cpp.
221
John McCallcbfe5022010-08-04 08:34:44 +0000222 // Preconditions.
Anders Carlssonf502d932011-01-24 00:46:19 +0000223 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCallcbfe5022010-08-04 08:34:44 +0000224 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
225 return;
226
227 // Don't override an explicit visibility attribute.
228 if (RD->hasAttr<VisibilityAttr>())
229 return;
230
231 switch (RD->getTemplateSpecializationKind()) {
232 // We have to disable the optimization if this is an EI definition
233 // because there might be EI declarations in other shared objects.
234 case TSK_ExplicitInstantiationDefinition:
235 case TSK_ExplicitInstantiationDeclaration:
236 return;
237
John McCall7a536902010-08-05 20:39:18 +0000238 // Every use of a non-template class's type information has to emit it.
John McCallcbfe5022010-08-04 08:34:44 +0000239 case TSK_Undeclared:
240 break;
241
John McCall7a536902010-08-05 20:39:18 +0000242 // In theory, implicit instantiations can ignore the possibility of
243 // an explicit instantiation declaration because there necessarily
244 // must be an EI definition somewhere with default visibility. In
245 // practice, it's possible to have an explicit instantiation for
246 // an arbitrary template class, and linkers aren't necessarily able
247 // to deal with mixed-visibility symbols.
248 case TSK_ExplicitSpecialization:
John McCallcbfe5022010-08-04 08:34:44 +0000249 case TSK_ImplicitInstantiation:
John McCall279b5eb2010-08-12 23:36:15 +0000250 if (!CodeGenOpts.HiddenWeakTemplateVTables)
John McCall7a536902010-08-05 20:39:18 +0000251 return;
John McCallcbfe5022010-08-04 08:34:44 +0000252 break;
253 }
254
255 // If there's a key function, there may be translation units
256 // that don't have the key function's definition. But ignore
257 // this if we're emitting RTTI under -fno-rtti.
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000258 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
John McCallcbfe5022010-08-04 08:34:44 +0000259 if (Context.getKeyFunction(RD))
260 return;
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000261 }
John McCallcbfe5022010-08-04 08:34:44 +0000262
263 // Otherwise, drop the visibility to hidden.
264 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1c65ff2011-01-11 21:44:37 +0000265 GV->setUnnamedAddr(true);
John McCallcbfe5022010-08-04 08:34:44 +0000266}
267
Anders Carlsson793a9902010-06-22 16:05:32 +0000268llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
269 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
270
271 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
272 if (!Str.empty())
273 return Str;
274
John McCall4c40d982010-08-31 07:33:07 +0000275 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000276 IdentifierInfo *II = ND->getIdentifier();
277 assert(II && "Attempt to mangle unnamed decl.");
278
279 Str = II->getName();
280 return Str;
281 }
282
283 llvm::SmallString<256> Buffer;
Rafael Espindolac4850c22011-02-10 23:59:36 +0000284 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000285 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000286 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000287 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000288 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000289 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000290 getCXXABI().getMangleContext().mangleBlock(BD, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000291 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000292 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000293
294 // Allocate space for the mangled name.
Rafael Espindolac4850c22011-02-10 23:59:36 +0000295 Out.flush();
Anders Carlsson793a9902010-06-22 16:05:32 +0000296 size_t Length = Buffer.size();
297 char *Name = MangledNamesAllocator.Allocate<char>(Length);
298 std::copy(Buffer.begin(), Buffer.end(), Name);
299
300 Str = llvm::StringRef(Name, Length);
301
302 return Str;
303}
304
Peter Collingbourne14110472011-01-13 18:57:25 +0000305void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
306 const BlockDecl *BD) {
307 MangleContext &MangleCtx = getCXXABI().getMangleContext();
308 const Decl *D = GD.getDecl();
Rafael Espindolac4850c22011-02-10 23:59:36 +0000309 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne14110472011-01-13 18:57:25 +0000310 if (D == 0)
Rafael Espindolac4850c22011-02-10 23:59:36 +0000311 MangleCtx.mangleGlobalBlock(BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000312 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000313 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000314 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000315 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000316 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000317 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000318}
319
John McCallf746aa62010-03-19 23:29:14 +0000320llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
321 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000322}
323
Chris Lattner6d397602008-03-14 17:18:18 +0000324/// AddGlobalCtor - Add a function to the list that will be called before
325/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000326void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000327 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000328 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000329}
330
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000331/// AddGlobalDtor - Add a function to the list that will be called
332/// when the module is unloaded.
333void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000334 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000335 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
336}
337
338void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
339 // Ctor function type is void()*.
340 llvm::FunctionType* CtorFTy =
Benjamin Kramer15f67652011-01-22 12:15:57 +0000341 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000342 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000343
344 // Get the type of a ctor entry, { i32, void ()* }.
Mike Stump1eb44332009-09-09 15:08:12 +0000345 llvm::StructType* CtorStructTy =
346 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
Owen Anderson96e0fc72009-07-29 22:16:19 +0000347 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000348
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000349 // Construct the constructor and destructor arrays.
350 std::vector<llvm::Constant*> Ctors;
351 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
352 std::vector<llvm::Constant*> S;
Mike Stump1eb44332009-09-09 15:08:12 +0000353 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson0032b272009-08-13 21:57:51 +0000354 I->second, false));
Owen Anderson3c4972d2009-07-29 18:54:39 +0000355 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson08e25242009-07-27 22:29:56 +0000356 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000357 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000358
359 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000360 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000361 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000362 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000363 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000364 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000365 }
Chris Lattner6d397602008-03-14 17:18:18 +0000366}
367
Nate Begeman532485c2008-04-18 23:43:57 +0000368void CodeGenModule::EmitAnnotations() {
369 if (Annotations.empty())
370 return;
371
372 // Create a new global variable for the ConstantStruct in the Module.
373 llvm::Constant *Array =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000374 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
Nate Begeman532485c2008-04-18 23:43:57 +0000375 Annotations.size()),
376 Annotations);
Mike Stump1eb44332009-09-09 15:08:12 +0000377 llvm::GlobalValue *gv =
378 new llvm::GlobalVariable(TheModule, Array->getType(), false,
379 llvm::GlobalValue::AppendingLinkage, Array,
Owen Anderson1c431b32009-07-08 19:05:04 +0000380 "llvm.global.annotations");
Nate Begeman532485c2008-04-18 23:43:57 +0000381 gv->setSection("llvm.metadata");
382}
383
John McCalld46f9852010-02-19 01:32:20 +0000384llvm::GlobalValue::LinkageTypes
385CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000386 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000387
Chris Lattnerf81530652010-06-30 16:58:07 +0000388 if (Linkage == GVA_Internal)
John McCalld46f9852010-02-19 01:32:20 +0000389 return llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000390
391 if (D->hasAttr<DLLExportAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000392 return llvm::Function::DLLExportLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000393
394 if (D->hasAttr<WeakAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000395 return llvm::Function::WeakAnyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000396
397 // In C99 mode, 'inline' functions are guaranteed to have a strong
398 // definition somewhere else, so we can use available_externally linkage.
399 if (Linkage == GVA_C99Inline)
Fariborz Jahanianfd0f89d2011-02-04 00:08:13 +0000400 return llvm::Function::AvailableExternallyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000401
402 // In C++, the compiler has to emit a definition in every translation unit
403 // that references the function. We should use linkonce_odr because
404 // a) if all references in this translation unit are optimized away, we
405 // don't need to codegen it. b) if the function persists, it needs to be
406 // merged with other definitions. c) C++ has the ODR, so we know the
407 // definition is dependable.
408 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000409 return !Context.getLangOptions().AppleKext
410 ? llvm::Function::LinkOnceODRLinkage
411 : llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000412
413 // An explicit instantiation of a template has weak linkage, since
414 // explicit instantiations can occur in multiple translation units
415 // and must all be equivalent. However, we are not allowed to
416 // throw away these explicit instantiations.
417 if (Linkage == GVA_ExplicitTemplateInstantiation)
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000418 return !Context.getLangOptions().AppleKext
419 ? llvm::Function::WeakODRLinkage
420 : llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000421
422 // Otherwise, we have strong external linkage.
423 assert(Linkage == GVA_StrongExternal);
424 return llvm::Function::ExternalLinkage;
John McCalld46f9852010-02-19 01:32:20 +0000425}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000426
John McCalld46f9852010-02-19 01:32:20 +0000427
428/// SetFunctionDefinitionAttributes - Set attributes for a global.
429///
430/// FIXME: This is currently only done for aliases and functions, but not for
431/// variables (these details are set in EmitGlobalVarDefinition for variables).
432void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
433 llvm::GlobalValue *GV) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000434 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000435}
436
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000437void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000438 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000439 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000440 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000441 AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000442 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel761d7f72008-09-25 21:02:23 +0000443 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000444 AttributeList.size()));
445 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000446}
447
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000448void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
449 llvm::Function *F) {
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000450 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Mike Stump1eb44332009-09-09 15:08:12 +0000451 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000452
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000453 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000454 F->addFnAttr(llvm::Attribute::AlwaysInline);
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000456 if (D->hasAttr<NakedAttr>())
457 F->addFnAttr(llvm::Attribute::Naked);
458
Mike Stump1feade82009-08-26 22:31:08 +0000459 if (D->hasAttr<NoInlineAttr>())
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000460 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpf55314d2009-10-05 21:58:44 +0000461
Rafael Espindolac5f657f2011-01-11 00:26:26 +0000462 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
463 F->setUnnamedAddr(true);
464
Anders Carlssonfd015352009-11-16 16:56:03 +0000465 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
466 F->addFnAttr(llvm::Attribute::StackProtect);
467 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
468 F->addFnAttr(llvm::Attribute::StackProtectReq);
469
Sean Huntcf807c42010-08-18 23:23:40 +0000470 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
471 if (alignment)
472 F->setAlignment(alignment);
473
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000474 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000475 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
476 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000477}
478
Mike Stump1eb44332009-09-09 15:08:12 +0000479void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000480 llvm::GlobalValue *GV) {
Anders Carlsson934176f2011-01-29 19:41:00 +0000481 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
482 setGlobalVisibility(GV, ND);
John McCall1fb0caa2010-10-22 21:05:15 +0000483 else
484 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000485
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000486 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000487 AddUsedGlobal(GV);
488
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000489 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000490 GV->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000491
492 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000493}
494
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000495void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
496 llvm::Function *F,
497 const CGFunctionInfo &FI) {
498 SetLLVMFunctionAttributes(D, FI, F);
499 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000500
501 F->setLinkage(llvm::Function::InternalLinkage);
502
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000503 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000504}
505
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000506void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000507 llvm::Function *F,
508 bool IsIncompleteFunction) {
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000509 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
510
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000511 if (!IsIncompleteFunction)
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000512 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000514 // Only a few attributes are set on declarations; these may later be
515 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000517 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000518 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump1eb44332009-09-09 15:08:12 +0000519 } else if (FD->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000520 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000521 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump1eb44332009-09-09 15:08:12 +0000522 // separate linkage types for this.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000523 F->setLinkage(llvm::Function::ExternalWeakLinkage);
524 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000525 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallaf146032010-10-30 11:50:40 +0000526
527 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
528 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
529 F->setVisibility(GetLLVMVisibility(LV.visibility()));
530 }
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000531 }
532
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000533 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000534 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000535}
536
Daniel Dunbar02698712009-02-13 20:29:50 +0000537void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +0000538 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +0000539 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000540 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000541}
542
543void CodeGenModule::EmitLLVMUsed() {
544 // Don't create llvm.used if there is no need.
Chris Lattnerad64e022009-07-17 23:57:13 +0000545 if (LLVMUsed.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +0000546 return;
547
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000548 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Chris Lattner35f38a22009-03-31 22:37:52 +0000550 // Convert LLVMUsed to what ConstantArray needs.
551 std::vector<llvm::Constant*> UsedArray;
552 UsedArray.resize(LLVMUsed.size());
553 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000554 UsedArray[i] =
555 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000556 i8PTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000557 }
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000559 if (UsedArray.empty())
560 return;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000561 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000562
563 llvm::GlobalVariable *GV =
564 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar02698712009-02-13 20:29:50 +0000565 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000566 llvm::ConstantArray::get(ATy, UsedArray),
Owen Anderson1c431b32009-07-08 19:05:04 +0000567 "llvm.used");
Daniel Dunbar02698712009-02-13 20:29:50 +0000568
569 GV->setSection("llvm.metadata");
570}
571
572void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000573 // Emit code for any potentially referenced deferred decls. Since a
574 // previously unused static decl may become used during the generation of code
575 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000576
Anders Carlsson046c2942010-04-17 20:15:18 +0000577 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
578 if (!DeferredVTables.empty()) {
579 const CXXRecordDecl *RD = DeferredVTables.back();
580 DeferredVTables.pop_back();
581 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000582 continue;
583 }
584
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000585 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000586 DeferredDeclsToEmit.pop_back();
587
John McCallc76702c2010-05-27 01:45:30 +0000588 // Check to see if we've already emitted this. This is necessary
589 // for a couple of reasons: first, decls can end up in the
590 // deferred-decls queue multiple times, and second, decls can end
591 // up with definitions in unusual ways (e.g. by an extern inline
592 // function acquiring a strong function redefinition). Just
593 // ignore these cases.
594 //
595 // TODO: That said, looking this up multiple times is very wasteful.
Anders Carlsson9a20d552010-06-22 16:16:50 +0000596 llvm::StringRef Name = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +0000597 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner67b00522009-03-21 09:44:56 +0000598 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Chris Lattner67b00522009-03-21 09:44:56 +0000600 if (!CGRef->isDeclaration())
601 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000602
John McCallc76702c2010-05-27 01:45:30 +0000603 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
604 // purposes an alias counts as a definition.
605 if (isa<llvm::GlobalAlias>(CGRef))
606 continue;
607
Chris Lattner67b00522009-03-21 09:44:56 +0000608 // Otherwise, emit the definition and move on to the next one.
609 EmitGlobalDefinition(D);
610 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000611}
612
Mike Stump1eb44332009-09-09 15:08:12 +0000613/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000614/// annotation information for a given GlobalValue. The annotation struct is
Mike Stump1eb44332009-09-09 15:08:12 +0000615/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
616/// GlobalValue being annotated. The second field is the constant string
617/// created from the AnnotateAttr's annotation. The third field is a constant
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000618/// string containing the name of the translation unit. The fourth field is
619/// the line number in the file of the annotated value declaration.
620///
621/// FIXME: this does not unique the annotation string constants, as llvm-gcc
622/// appears to.
623///
Mike Stump1eb44332009-09-09 15:08:12 +0000624llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000625 const AnnotateAttr *AA,
626 unsigned LineNo) {
627 llvm::Module *M = &getModule();
628
629 // get [N x i8] constants for the annotation string, and the filename string
630 // which are the 2nd and 3rd elements of the global annotation structure.
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000631 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump1eb44332009-09-09 15:08:12 +0000632 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000633 AA->getAnnotation(), true);
634 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
635 M->getModuleIdentifier(),
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000636 true);
637
638 // Get the two global values corresponding to the ConstantArrays we just
639 // created to hold the bytes of the strings.
Mike Stump1eb44332009-09-09 15:08:12 +0000640 llvm::GlobalValue *annoGV =
Chris Lattner95b851e2009-07-16 05:03:48 +0000641 new llvm::GlobalVariable(*M, anno->getType(), false,
642 llvm::GlobalValue::PrivateLinkage, anno,
643 GV->getName());
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000644 // translation unit name string, emitted into the llvm.metadata section.
645 llvm::GlobalValue *unitGV =
Chris Lattner95b851e2009-07-16 05:03:48 +0000646 new llvm::GlobalVariable(*M, unit->getType(), false,
Mike Stump1eb44332009-09-09 15:08:12 +0000647 llvm::GlobalValue::PrivateLinkage, unit,
Chris Lattner95b851e2009-07-16 05:03:48 +0000648 ".str");
Rafael Espindolad3d4e1e2011-01-17 22:22:52 +0000649 unitGV->setUnnamedAddr(true);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000650
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000651 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000652 llvm::Constant *Fields[4] = {
Owen Anderson3c4972d2009-07-29 18:54:39 +0000653 llvm::ConstantExpr::getBitCast(GV, SBP),
654 llvm::ConstantExpr::getBitCast(annoGV, SBP),
655 llvm::ConstantExpr::getBitCast(unitGV, SBP),
Owen Anderson0032b272009-08-13 21:57:51 +0000656 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000657 };
Owen Anderson47a434f2009-08-05 23:18:46 +0000658 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000659}
660
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000661bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000662 // Never defer when EmitAllDecls is specified.
663 if (Features.EmitAllDecls)
Daniel Dunbar73241df2009-02-13 21:18:01 +0000664 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000665
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +0000666 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000667}
668
Rafael Espindola6a836702010-03-04 18:17:24 +0000669llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
670 const AliasAttr *AA = VD->getAttr<AliasAttr>();
671 assert(AA && "No alias?");
672
673 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
674
Rafael Espindola6a836702010-03-04 18:17:24 +0000675 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +0000676 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola6a836702010-03-04 18:17:24 +0000677
678 llvm::Constant *Aliasee;
679 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000680 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
681 /*ForVTable=*/false);
Rafael Espindola6a836702010-03-04 18:17:24 +0000682 else
John McCallf746aa62010-03-19 23:29:14 +0000683 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola6a836702010-03-04 18:17:24 +0000684 llvm::PointerType::getUnqual(DeclTy), 0);
685 if (!Entry) {
686 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
687 F->setLinkage(llvm::Function::ExternalWeakLinkage);
688 WeakRefReferences.insert(F);
689 }
690
691 return Aliasee;
692}
693
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000694void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000695 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Rafael Espindola6a836702010-03-04 18:17:24 +0000697 // Weak references don't produce any output by themselves.
698 if (Global->hasAttr<WeakRefAttr>())
699 return;
700
Chris Lattnerbd532712009-03-22 21:47:11 +0000701 // If this is an alias definition (which otherwise looks like a declaration)
702 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000703 if (Global->hasAttr<AliasAttr>())
John McCallf746aa62010-03-19 23:29:14 +0000704 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +0000705
Chris Lattner67b00522009-03-21 09:44:56 +0000706 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000707 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar754b9fb2010-07-16 00:00:19 +0000708 if (FD->getIdentifier()) {
709 llvm::StringRef Name = FD->getName();
710 if (Name == "_Block_object_assign") {
711 BlockObjectAssignDecl = FD;
712 } else if (Name == "_Block_object_dispose") {
713 BlockObjectDisposeDecl = FD;
714 }
715 }
716
Daniel Dunbar73241df2009-02-13 21:18:01 +0000717 // Forward declarations are emitted lazily on first use.
718 if (!FD->isThisDeclarationADefinition())
719 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000720 } else {
721 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000722 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
723
Daniel Dunbar754b9fb2010-07-16 00:00:19 +0000724 if (VD->getIdentifier()) {
725 llvm::StringRef Name = VD->getName();
726 if (Name == "_NSConcreteGlobalBlock") {
727 NSConcreteGlobalBlockDecl = VD;
728 } else if (Name == "_NSConcreteStackBlock") {
729 NSConcreteStackBlockDecl = VD;
730 }
731 }
732
733
Douglas Gregora9a55c02010-02-06 05:15:45 +0000734 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000735 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000736 }
737
Chris Lattner67b00522009-03-21 09:44:56 +0000738 // Defer code generation when possible if this is a static definition, inline
739 // function etc. These we only want to emit if they are used.
Chris Lattner4357a822010-04-13 17:39:09 +0000740 if (!MayDeferGeneration(Global)) {
741 // Emit the definition if it can't be deferred.
742 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000743 return;
744 }
John McCallbf40cb52010-07-15 23:40:35 +0000745
746 // If we're deferring emission of a C++ variable with an
747 // initializer, remember the order in which it appeared in the file.
748 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
749 cast<VarDecl>(Global)->hasInit()) {
750 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
751 CXXGlobalInits.push_back(0);
752 }
Chris Lattner4357a822010-04-13 17:39:09 +0000753
754 // If the value has already been used, add it directly to the
755 // DeferredDeclsToEmit list.
Anders Carlsson9a20d552010-06-22 16:16:50 +0000756 llvm::StringRef MangledName = getMangledName(GD);
Chris Lattner4357a822010-04-13 17:39:09 +0000757 if (GetGlobalValue(MangledName))
758 DeferredDeclsToEmit.push_back(GD);
759 else {
760 // Otherwise, remember that we saw a deferred decl with this name. The
761 // first use of the mangled name will cause it to move into
762 // DeferredDeclsToEmit.
763 DeferredDecls[MangledName] = GD;
764 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000765}
766
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000767void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000768 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Dan Gohmancb421fa2010-04-19 16:39:44 +0000770 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +0000771 Context.getSourceManager(),
772 "Generating code for declaration");
773
Douglas Gregor44eac332010-07-13 06:02:28 +0000774 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
775 // At -O0, don't generate IR for functions with available_externally
776 // linkage.
Douglas Gregor7feaeee2010-07-15 22:58:18 +0000777 if (CodeGenOpts.OptimizationLevel == 0 &&
778 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregor44eac332010-07-13 06:02:28 +0000779 getFunctionLinkage(Function)
780 == llvm::Function::AvailableExternallyLinkage)
781 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +0000782
Douglas Gregor44eac332010-07-13 06:02:28 +0000783 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
784 if (Method->isVirtual())
785 getVTables().EmitThunks(GD);
786
787 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
788 return EmitCXXConstructor(CD, GD.getCtorType());
Chris Lattner4357a822010-04-13 17:39:09 +0000789
Douglas Gregor44eac332010-07-13 06:02:28 +0000790 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
791 return EmitCXXDestructor(DD, GD.getDtorType());
792 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000793
Chris Lattnerb5e81562010-04-13 17:57:11 +0000794 return EmitGlobalFunctionDefinition(GD);
Douglas Gregor44eac332010-07-13 06:02:28 +0000795 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000796
797 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
798 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +0000799
800 assert(0 && "Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000801}
802
Chris Lattner74391b42009-03-22 21:03:39 +0000803/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
804/// module, create and return an llvm Function with the specified type. If there
805/// is something in the module with the specified name, return it potentially
806/// bitcasted to the right type.
807///
808/// If D is non-null, it specifies a decl that correspond to this. This is used
809/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +0000810llvm::Constant *
811CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
812 const llvm::Type *Ty,
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000813 GlobalDecl D, bool ForVTable) {
Chris Lattner0558e792009-03-21 09:25:43 +0000814 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +0000815 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +0000816 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +0000817 if (WeakRefReferences.count(Entry)) {
818 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
819 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +0000820 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +0000821
822 WeakRefReferences.erase(Entry);
823 }
824
Chris Lattner0558e792009-03-21 09:25:43 +0000825 if (Entry->getType()->getElementType() == Ty)
826 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Chris Lattner0558e792009-03-21 09:25:43 +0000828 // Make sure the result is of the correct type.
Owen Anderson96e0fc72009-07-29 22:16:19 +0000829 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000830 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000831 }
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Eli Friedman654ad402009-11-09 05:07:37 +0000833 // This function doesn't have a complete type (for example, the return
834 // type is an incomplete struct). Use a fake type instead, and make
835 // sure not to try to set attributes.
836 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +0000837
838 const llvm::FunctionType *FTy;
839 if (isa<llvm::FunctionType>(Ty)) {
840 FTy = cast<llvm::FunctionType>(Ty);
841 } else {
Benjamin Kramer15f67652011-01-22 12:15:57 +0000842 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
Eli Friedman654ad402009-11-09 05:07:37 +0000843 IsIncompleteFunction = true;
844 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000845
John McCall784f2112010-04-28 00:00:30 +0000846 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +0000847 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +0000848 MangledName, &getModule());
849 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedman654ad402009-11-09 05:07:37 +0000850 if (D.getDecl())
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000851 SetFunctionAttributes(D, F, IsIncompleteFunction);
Eli Friedman654ad402009-11-09 05:07:37 +0000852
Chris Lattner67b00522009-03-21 09:44:56 +0000853 // This is the first use or definition of a mangled name. If there is a
854 // deferred decl with this name, remember that we need to emit it at the end
855 // of the file.
John McCallf746aa62010-03-19 23:29:14 +0000856 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000857 if (DDI != DeferredDecls.end()) {
858 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
859 // list, and remove it from DeferredDecls (since we don't need it anymore).
860 DeferredDeclsToEmit.push_back(DDI->second);
861 DeferredDecls.erase(DDI);
John McCallbfdcdc82010-12-15 04:00:32 +0000862
863 // Otherwise, there are cases we have to worry about where we're
864 // using a declaration for which we must emit a definition but where
865 // we might not find a top-level definition:
866 // - member functions defined inline in their classes
867 // - friend functions defined inline in some class
868 // - special member functions with implicit definitions
869 // If we ever change our AST traversal to walk into class methods,
870 // this will be unnecessary.
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000871 //
872 // We also don't emit a definition for a function if it's going to be an entry
873 // in a vtable, unless it's already marked as used.
Rafael Espindola01de7a42011-02-03 06:30:58 +0000874 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
John McCallbfdcdc82010-12-15 04:00:32 +0000875 // Look for a declaration that's lexically in a record.
876 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
877 do {
878 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000879 if (FD->isImplicit() && !ForVTable) {
John McCallbfdcdc82010-12-15 04:00:32 +0000880 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
Douglas Gregora29bf412011-02-09 02:03:05 +0000881 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +0000882 break;
883 } else if (FD->isThisDeclarationADefinition()) {
Douglas Gregora29bf412011-02-09 02:03:05 +0000884 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +0000885 break;
886 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000887 }
John McCallbfdcdc82010-12-15 04:00:32 +0000888 FD = FD->getPreviousDeclaration();
889 } while (FD);
Chris Lattner67b00522009-03-21 09:44:56 +0000890 }
Mike Stump1eb44332009-09-09 15:08:12 +0000891
John McCall784f2112010-04-28 00:00:30 +0000892 // Make sure the result is of the requested type.
893 if (!IsIncompleteFunction) {
894 assert(F->getType()->getElementType() == Ty);
895 return F;
896 }
897
898 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
899 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000900}
901
Chris Lattner74391b42009-03-22 21:03:39 +0000902/// GetAddrOfFunction - Return the address of the given function. If Ty is
903/// non-null, then this function will use the specified type if it has to
904/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000905llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000906 const llvm::Type *Ty,
907 bool ForVTable) {
Chris Lattner74391b42009-03-22 21:03:39 +0000908 // If there was no specific requested type, just convert it now.
909 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000910 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000911
Anders Carlsson9a20d552010-06-22 16:16:50 +0000912 llvm::StringRef MangledName = getMangledName(GD);
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000913 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
Chris Lattner74391b42009-03-22 21:03:39 +0000914}
Eli Friedman77ba7082008-05-30 19:50:47 +0000915
Chris Lattner74391b42009-03-22 21:03:39 +0000916/// CreateRuntimeFunction - Create a new runtime function with the specified
917/// type and name.
918llvm::Constant *
919CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
John McCallf746aa62010-03-19 23:29:14 +0000920 llvm::StringRef Name) {
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000921 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false);
Chris Lattner74391b42009-03-22 21:03:39 +0000922}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000923
Eli Friedman20e098b2009-12-11 21:23:03 +0000924static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
John McCall88786862010-02-08 21:46:50 +0000925 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +0000926 return false;
927 if (Context.getLangOptions().CPlusPlus &&
928 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
929 // FIXME: We should do something fancier here!
930 return false;
931 }
932 return true;
933}
934
Chris Lattner74391b42009-03-22 21:03:39 +0000935/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
936/// create and return an llvm GlobalVariable with the specified type. If there
937/// is something in the module with the specified name, return it potentially
938/// bitcasted to the right type.
939///
940/// If D is non-null, it specifies a decl that correspond to this. This is used
941/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +0000942llvm::Constant *
943CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
944 const llvm::PointerType *Ty,
Rafael Espindolac532b502011-01-18 21:07:57 +0000945 const VarDecl *D,
946 bool UnnamedAddr) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000947 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +0000948 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +0000949 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +0000950 if (WeakRefReferences.count(Entry)) {
951 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +0000952 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +0000953
954 WeakRefReferences.erase(Entry);
955 }
956
Rafael Espindolac532b502011-01-18 21:07:57 +0000957 if (UnnamedAddr)
958 Entry->setUnnamedAddr(true);
959
Chris Lattner74391b42009-03-22 21:03:39 +0000960 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +0000961 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Chris Lattner99b53612009-03-21 08:03:33 +0000963 // Make sure the result is of the correct type.
Owen Anderson3c4972d2009-07-29 18:54:39 +0000964 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +0000965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Chris Lattner67b00522009-03-21 09:44:56 +0000967 // This is the first use or definition of a mangled name. If there is a
968 // deferred decl with this name, remember that we need to emit it at the end
969 // of the file.
John McCallf746aa62010-03-19 23:29:14 +0000970 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000971 if (DDI != DeferredDecls.end()) {
972 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
973 // list, and remove it from DeferredDecls (since we don't need it anymore).
974 DeferredDeclsToEmit.push_back(DDI->second);
975 DeferredDecls.erase(DDI);
976 }
Mike Stump1eb44332009-09-09 15:08:12 +0000977
978 llvm::GlobalVariable *GV =
979 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +0000980 llvm::GlobalValue::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +0000981 0, MangledName, 0,
Eli Friedman56ebe502009-04-19 21:05:03 +0000982 false, Ty->getAddressSpace());
Chris Lattner99b53612009-03-21 08:03:33 +0000983
984 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +0000985 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000986 // FIXME: This code is overly simple and should be merged with other global
987 // handling.
Eli Friedman20e098b2009-12-11 21:23:03 +0000988 GV->setConstant(DeclIsConstantGlobal(Context, D));
Chris Lattner99b53612009-03-21 08:03:33 +0000989
John McCall110e8e52010-10-29 22:22:43 +0000990 // Set linkage and visibility in case we never see a definition.
John McCallaf146032010-10-30 11:50:40 +0000991 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
992 if (LV.linkage() != ExternalLinkage) {
John McCall15e310a2011-02-19 02:53:41 +0000993 // Don't set internal linkage on declarations.
John McCall110e8e52010-10-29 22:22:43 +0000994 } else {
995 if (D->hasAttr<DLLImportAttr>())
996 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
997 else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
998 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner99b53612009-03-21 08:03:33 +0000999
John McCallaf146032010-10-30 11:50:40 +00001000 // Set visibility on a declaration only if it's explicit.
1001 if (LV.visibilityExplicit())
1002 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall110e8e52010-10-29 22:22:43 +00001003 }
Eli Friedman56ebe502009-04-19 21:05:03 +00001004
1005 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattner74391b42009-03-22 21:03:39 +00001006 }
Mike Stump1eb44332009-09-09 15:08:12 +00001007
John McCallf746aa62010-03-19 23:29:14 +00001008 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001009}
1010
Chris Lattner74391b42009-03-22 21:03:39 +00001011
Anders Carlsson3bd62022011-01-29 18:20:20 +00001012llvm::GlobalVariable *
1013CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
1014 const llvm::Type *Ty,
1015 llvm::GlobalValue::LinkageTypes Linkage) {
1016 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1017 llvm::GlobalVariable *OldGV = 0;
1018
1019
1020 if (GV) {
1021 // Check if the variable has the right type.
1022 if (GV->getType()->getElementType() == Ty)
1023 return GV;
1024
1025 // Because C++ name mangling, the only way we can end up with an already
1026 // existing global with the same name is if it has been declared extern "C".
Anders Carlsson96eaf292011-01-29 18:25:07 +00001027 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlsson3bd62022011-01-29 18:20:20 +00001028 OldGV = GV;
1029 }
1030
1031 // Create a new variable.
1032 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1033 Linkage, 0, Name);
1034
1035 if (OldGV) {
1036 // Replace occurrences of the old variable if needed.
1037 GV->takeName(OldGV);
1038
1039 if (!OldGV->use_empty()) {
1040 llvm::Constant *NewPtrForOldDecl =
1041 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1042 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1043 }
1044
1045 OldGV->eraseFromParent();
1046 }
1047
1048 return GV;
1049}
1050
Chris Lattner74391b42009-03-22 21:03:39 +00001051/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1052/// given global variable. If Ty is non-null and if the global doesn't exist,
1053/// then it will be greated with the specified type instead of whatever the
1054/// normal requested type would be.
1055llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1056 const llvm::Type *Ty) {
1057 assert(D->hasGlobalStorage() && "Not a global variable");
1058 QualType ASTTy = D->getType();
1059 if (Ty == 0)
1060 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001061
1062 const llvm::PointerType *PTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001063 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCallf746aa62010-03-19 23:29:14 +00001064
Anders Carlsson9a20d552010-06-22 16:16:50 +00001065 llvm::StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001066 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001067}
1068
1069/// CreateRuntimeVariable - Create a new runtime global variable with the
1070/// specified type and name.
1071llvm::Constant *
1072CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
John McCallf746aa62010-03-19 23:29:14 +00001073 llvm::StringRef Name) {
Rafael Espindolac532b502011-01-18 21:07:57 +00001074 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1075 true);
Chris Lattner74391b42009-03-22 21:03:39 +00001076}
1077
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001078void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1079 assert(!D->getInit() && "Cannot emit definite definitions here!");
1080
Douglas Gregor7520bd12009-04-21 19:28:58 +00001081 if (MayDeferGeneration(D)) {
1082 // If we have not seen a reference to this variable yet, place it
1083 // into the deferred declarations table to be emitted if needed
1084 // later.
Anders Carlsson9a20d552010-06-22 16:16:50 +00001085 llvm::StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001086 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001087 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001088 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001089 }
1090 }
1091
1092 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001093 EmitGlobalVarDefinition(D);
1094}
1095
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001096void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1097 if (DefinitionRequired)
1098 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1099}
1100
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001101llvm::GlobalVariable::LinkageTypes
Anders Carlsson046c2942010-04-17 20:15:18 +00001102CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Douglas Gregordffb8012010-01-06 22:00:56 +00001103 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1104 return llvm::GlobalVariable::InternalLinkage;
1105
1106 if (const CXXMethodDecl *KeyFunction
1107 = RD->getASTContext().getKeyFunction(RD)) {
1108 // If this class has a key function, use that to determine the linkage of
1109 // the vtable.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001110 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001111 if (KeyFunction->hasBody(Def))
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001112 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregordffb8012010-01-06 22:00:56 +00001113
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001114 switch (KeyFunction->getTemplateSpecializationKind()) {
1115 case TSK_Undeclared:
1116 case TSK_ExplicitSpecialization:
Anders Carlsson6d7f8472011-01-30 20:45:54 +00001117 // When compiling with optimizations turned on, we emit all vtables,
1118 // even if the key function is not defined in the current translation
1119 // unit. If this is the case, use available_externally linkage.
1120 if (!Def && CodeGenOpts.OptimizationLevel)
1121 return llvm::GlobalVariable::AvailableExternallyLinkage;
1122
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001123 if (KeyFunction->isInlined())
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001124 return !Context.getLangOptions().AppleKext ?
1125 llvm::GlobalVariable::LinkOnceODRLinkage :
1126 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001127
1128 return llvm::GlobalVariable::ExternalLinkage;
1129
1130 case TSK_ImplicitInstantiation:
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001131 return !Context.getLangOptions().AppleKext ?
1132 llvm::GlobalVariable::LinkOnceODRLinkage :
1133 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001134
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001135 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001136 return !Context.getLangOptions().AppleKext ?
1137 llvm::GlobalVariable::WeakODRLinkage :
1138 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001139
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001140 case TSK_ExplicitInstantiationDeclaration:
1141 // FIXME: Use available_externally linkage. However, this currently
1142 // breaks LLVM's build due to undefined symbols.
1143 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001144 return !Context.getLangOptions().AppleKext ?
1145 llvm::GlobalVariable::LinkOnceODRLinkage :
1146 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001147 }
Douglas Gregordffb8012010-01-06 22:00:56 +00001148 }
1149
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001150 if (Context.getLangOptions().AppleKext)
1151 return llvm::Function::InternalLinkage;
1152
Douglas Gregordffb8012010-01-06 22:00:56 +00001153 switch (RD->getTemplateSpecializationKind()) {
1154 case TSK_Undeclared:
1155 case TSK_ExplicitSpecialization:
1156 case TSK_ImplicitInstantiation:
Douglas Gregordffb8012010-01-06 22:00:56 +00001157 // FIXME: Use available_externally linkage. However, this currently
1158 // breaks LLVM's build due to undefined symbols.
1159 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001160 case TSK_ExplicitInstantiationDeclaration:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001161 return llvm::GlobalVariable::LinkOnceODRLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001162
1163 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001164 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001165 }
1166
1167 // Silence GCC warning.
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001168 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001169}
1170
Ken Dyck687cc4a2010-01-26 13:48:07 +00001171CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
Ken Dyck06f486e2011-01-18 02:01:14 +00001172 return Context.toCharUnitsFromBits(
1173 TheTargetData.getTypeStoreSizeInBits(Ty));
Ken Dyck687cc4a2010-01-26 13:48:07 +00001174}
1175
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001176void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +00001177 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +00001178 QualType ASTTy = D->getType();
Eli Friedman6c6bda32010-01-08 00:50:11 +00001179 bool NonConstInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Sebastian Redl31310a22010-02-01 20:16:42 +00001181 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlsson3bb92692010-01-26 17:43:42 +00001182
1183 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001184 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001185 // implicitly initialized with { 0 }.
1186 //
1187 // Note that tentative definitions are only emitted at the end of
1188 // a translation unit, so they should never have incomplete
1189 // type. In addition, EmitTentativeDefinition makes sure that we
1190 // never attempt to emit a tentative definition if a real one
1191 // exists. A use may still exists, however, so we still may need
1192 // to do a RAUW.
1193 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00001194 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00001195 } else {
Douglas Gregorc446d182010-05-05 20:15:55 +00001196 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman6e656f42009-02-20 01:18:21 +00001197 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00001198 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00001199 if (D->getType()->isReferenceType())
1200 T = D->getType();
1201
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001202 if (getLangOptions().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001203 Init = EmitNullConstant(T);
Eli Friedman6c6bda32010-01-08 00:50:11 +00001204 NonConstInit = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001205 } else {
1206 ErrorUnsupported(D, "static initializer");
1207 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1208 }
John McCallbf40cb52010-07-15 23:40:35 +00001209 } else {
1210 // We don't need an initializer, so remove the entry for the delayed
1211 // initializer position (just in case this entry was delayed).
1212 if (getLangOptions().CPlusPlus)
1213 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00001214 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001215 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001216
Chris Lattner2d584062009-03-21 08:13:05 +00001217 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00001218 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Chris Lattner570585c2009-03-21 09:16:30 +00001220 // Strip off a bitcast if we got one back.
1221 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001222 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1223 // all zero index gep.
1224 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00001225 Entry = CE->getOperand(0);
1226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Chris Lattner570585c2009-03-21 09:16:30 +00001228 // Entry is now either a Function or GlobalVariable.
1229 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Chris Lattner570585c2009-03-21 09:16:30 +00001231 // We have a definition after a declaration with the wrong type.
1232 // We must make a new GlobalVariable* and update everything that used OldGV
1233 // (a declaration or tentative definition) with the new GlobalVariable*
1234 // (which will be a definition).
1235 //
1236 // This happens if there is a prototype for a global (e.g.
1237 // "extern int x[];") and then a definition of a different type (e.g.
1238 // "int x[10];"). This also happens when an initializer has a different type
1239 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +00001240 if (GV == 0 ||
1241 GV->getType()->getElementType() != InitType ||
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001242 GV->getType()->getAddressSpace() !=
1243 getContext().getTargetAddressSpace(ASTTy)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001244
John McCallf746aa62010-03-19 23:29:14 +00001245 // Move the old entry aside so that we'll create a new one.
1246 Entry->setName(llvm::StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00001247
Chris Lattner570585c2009-03-21 09:16:30 +00001248 // Make a new global with the correct type, this is now guaranteed to work.
1249 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00001250
Eli Friedman77ba7082008-05-30 19:50:47 +00001251 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00001252 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001253 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00001254 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00001255
1256 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00001257 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00001258 }
Devang Patel8e53e722007-10-26 16:31:40 +00001259
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001260 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001261 SourceManager &SM = Context.getSourceManager();
1262 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00001263 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001264 }
1265
Chris Lattner88a69ad2007-07-13 05:13:43 +00001266 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001267
1268 // If it is safe to mark the global 'constant', do so now.
1269 GV->setConstant(false);
Eli Friedman6c6bda32010-01-08 00:50:11 +00001270 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
Chris Lattnere78b86f2009-08-05 05:20:29 +00001271 GV->setConstant(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Ken Dyck8b752f12010-01-27 17:10:57 +00001273 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001274
Chris Lattner88a69ad2007-07-13 05:13:43 +00001275 // Set the llvm linkage type as appropriate.
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001276 llvm::GlobalValue::LinkageTypes Linkage =
1277 GetLLVMLinkageVarDefinition(D, GV);
1278 GV->setLinkage(Linkage);
1279 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00001280 // common vars aren't constant even if declared const.
1281 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00001282
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001283 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00001284
John McCall3030eb82010-11-06 09:44:32 +00001285 // Emit the initializer function if necessary.
1286 if (NonConstInit)
1287 EmitCXXGlobalVarDeclInitFunc(D, GV);
1288
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001289 // Emit global variable debug information.
Devang Patelaa112892011-03-07 18:45:56 +00001290 if (CGDebugInfo *DI = getModuleDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +00001291 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001292 DI->EmitGlobalVariable(GV, D);
1293 }
Chris Lattner88a69ad2007-07-13 05:13:43 +00001294}
Reid Spencer5f016e22007-07-11 17:01:13 +00001295
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001296llvm::GlobalValue::LinkageTypes
1297CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1298 llvm::GlobalVariable *GV) {
1299 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1300 if (Linkage == GVA_Internal)
1301 return llvm::Function::InternalLinkage;
1302 else if (D->hasAttr<DLLImportAttr>())
1303 return llvm::Function::DLLImportLinkage;
1304 else if (D->hasAttr<DLLExportAttr>())
1305 return llvm::Function::DLLExportLinkage;
1306 else if (D->hasAttr<WeakAttr>()) {
1307 if (GV->isConstant())
1308 return llvm::GlobalVariable::WeakODRLinkage;
1309 else
1310 return llvm::GlobalVariable::WeakAnyLinkage;
1311 } else if (Linkage == GVA_TemplateInstantiation ||
1312 Linkage == GVA_ExplicitTemplateInstantiation)
1313 // FIXME: It seems like we can provide more specific linkage here
1314 // (LinkOnceODR, WeakODR).
1315 return llvm::GlobalVariable::WeakAnyLinkage;
Eric Christophera6cf1e72010-12-02 02:45:55 +00001316 else if (!getLangOptions().CPlusPlus &&
1317 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1318 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001319 !D->hasExternalStorage() && !D->getInit() &&
1320 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1321 // Thread local vars aren't considered common linkage.
1322 return llvm::GlobalVariable::CommonLinkage;
1323 }
1324 return llvm::GlobalVariable::ExternalLinkage;
1325}
1326
Chris Lattnerbdb01322009-05-05 06:16:31 +00001327/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1328/// implement a function with no prototype, e.g. "int foo() {}". If there are
1329/// existing call uses of the old function in the module, this adjusts them to
1330/// call the new function directly.
1331///
1332/// This is not just a cleanup: the always_inline pass requires direct calls to
1333/// functions to be able to inline them. If there is a bitcast in the way, it
1334/// won't inline them. Instcombine normally deletes these calls, but it isn't
1335/// run at -O0.
1336static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1337 llvm::Function *NewFn) {
1338 // If we're redefining a global as a function, don't transform it.
1339 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1340 if (OldFn == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Chris Lattnerbdb01322009-05-05 06:16:31 +00001342 const llvm::Type *NewRetTy = NewFn->getReturnType();
1343 llvm::SmallVector<llvm::Value*, 4> ArgList;
1344
1345 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001346 UI != E; ) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001347 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001348 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1349 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif8670cd32010-07-28 09:19:33 +00001350 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
Gabor Greif35db3b92010-04-10 03:45:50 +00001351 llvm::CallSite CS(CI);
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001352 if (!CI || !CS.isCallee(I)) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Chris Lattnerbdb01322009-05-05 06:16:31 +00001354 // If the return types don't match exactly, and if the call isn't dead, then
1355 // we can't transform this call.
1356 if (CI->getType() != NewRetTy && !CI->use_empty())
1357 continue;
1358
1359 // If the function was passed too few arguments, don't transform. If extra
1360 // arguments were passed, we silently drop them. If any of the types
1361 // mismatch, we don't transform.
1362 unsigned ArgNo = 0;
1363 bool DontTransform = false;
1364 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1365 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greif35db3b92010-04-10 03:45:50 +00001366 if (CS.arg_size() == ArgNo ||
1367 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001368 DontTransform = true;
1369 break;
1370 }
1371 }
1372 if (DontTransform)
1373 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Chris Lattnerbdb01322009-05-05 06:16:31 +00001375 // Okay, we can transform this. Create the new call instruction and copy
1376 // over the required information.
Gabor Greif6ba728d2010-04-10 02:56:12 +00001377 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001378 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1379 ArgList.end(), "", CI);
1380 ArgList.clear();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001381 if (!NewCall->getType()->isVoidTy())
Chris Lattnerbdb01322009-05-05 06:16:31 +00001382 NewCall->takeName(CI);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001383 NewCall->setAttributes(CI->getAttributes());
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001384 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001385
1386 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner00549fc2009-10-14 05:49:21 +00001387 if (!CI->use_empty())
1388 CI->replaceAllUsesWith(NewCall);
Devang Patel3b122bc2009-10-13 17:02:04 +00001389
Chris Lattnerc6034632010-04-01 06:31:43 +00001390 // Copy debug location attached to CI.
1391 if (!CI->getDebugLoc().isUnknown())
1392 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001393 CI->eraseFromParent();
1394 }
1395}
1396
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001397
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001398void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001399 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalld26bc762011-03-09 04:27:21 +00001400
John McCall1f6f9612011-03-09 08:12:35 +00001401 // Compute the function info and LLVM type.
John McCalld26bc762011-03-09 04:27:21 +00001402 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
John McCall1f6f9612011-03-09 08:12:35 +00001403 bool variadic = false;
1404 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
1405 variadic = fpt->isVariadic();
1406 const llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic, false);
John McCalld26bc762011-03-09 04:27:21 +00001407
Chris Lattner9fa959d2009-05-12 20:58:15 +00001408 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001409 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Chris Lattner0558e792009-03-21 09:25:43 +00001411 // Strip off a bitcast if we got one back.
1412 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1413 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1414 Entry = CE->getOperand(0);
1415 }
Mike Stump1eb44332009-09-09 15:08:12 +00001416
1417
Chris Lattner0558e792009-03-21 09:25:43 +00001418 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001419 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Daniel Dunbar42745812009-03-09 23:53:08 +00001421 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001422 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +00001423 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00001424
Chris Lattner62b33ea2009-03-21 08:38:50 +00001425 // F is the Function* for the one with the wrong type, we must make a new
1426 // Function* and update everything that used F (a declaration) with the new
1427 // Function* (which will be a definition).
1428 //
1429 // This happens if there is a prototype for a function
1430 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00001431 // (e.g. "int f(int x)"). Move the old function aside so that it
1432 // doesn't interfere with GetAddrOfFunction.
1433 OldFn->setName(llvm::StringRef());
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001434 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Chris Lattnerbdb01322009-05-05 06:16:31 +00001436 // If this is an implementation of a function without a prototype, try to
1437 // replace any existing uses of the function (which may be calls) with uses
1438 // of the new function
Chris Lattner9fa959d2009-05-12 20:58:15 +00001439 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001440 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001441 OldFn->removeDeadConstantUsers();
1442 }
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Chris Lattner62b33ea2009-03-21 08:38:50 +00001444 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001445 if (!Entry->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001446 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001447 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001448 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1449 }
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Chris Lattner62b33ea2009-03-21 08:38:50 +00001451 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001452 OldFn->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Chris Lattner0558e792009-03-21 09:25:43 +00001454 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001455 }
Mike Stump1eb44332009-09-09 15:08:12 +00001456
John McCall112c9672010-11-02 21:04:24 +00001457 // We need to set linkage and visibility on the function before
1458 // generating code for it because various parts of IR generation
1459 // want to propagate this information down (e.g. to local static
1460 // declarations).
Chris Lattner0558e792009-03-21 09:25:43 +00001461 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall8b242332010-05-25 04:30:21 +00001462 setFunctionLinkage(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001463
John McCall112c9672010-11-02 21:04:24 +00001464 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlsson0ffeaad2011-01-29 19:39:23 +00001465 setGlobalVisibility(Fn, D);
John McCall112c9672010-11-02 21:04:24 +00001466
John McCalld26bc762011-03-09 04:27:21 +00001467 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00001468
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001469 SetFunctionDefinitionAttributes(D, Fn);
1470 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001472 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001473 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001474 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001475 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001476}
1477
John McCallf746aa62010-03-19 23:29:14 +00001478void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1479 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001480 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00001481 assert(AA && "Not an alias?");
1482
Anders Carlsson9a20d552010-06-22 16:16:50 +00001483 llvm::StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00001484
John McCallf746aa62010-03-19 23:29:14 +00001485 // If there is a definition in the module, then it wins over the alias.
1486 // This is dubious, but allow it to be safe. Just ignore the alias.
1487 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1488 if (Entry && !Entry->isDeclaration())
1489 return;
1490
1491 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00001492
1493 // Create a reference to the named value. This ensures that it is emitted
1494 // if a deferred decl.
1495 llvm::Constant *Aliasee;
1496 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001497 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1498 /*ForVTable=*/false);
Chris Lattnerbd532712009-03-22 21:47:11 +00001499 else
John McCallf746aa62010-03-19 23:29:14 +00001500 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson96e0fc72009-07-29 22:16:19 +00001501 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattnerbd532712009-03-22 21:47:11 +00001502
1503 // Create the new alias itself, but don't set a name yet.
Mike Stump1eb44332009-09-09 15:08:12 +00001504 llvm::GlobalValue *GA =
Chris Lattnerbd532712009-03-22 21:47:11 +00001505 new llvm::GlobalAlias(Aliasee->getType(),
1506 llvm::Function::ExternalLinkage,
1507 "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Chris Lattnerbd532712009-03-22 21:47:11 +00001509 if (Entry) {
John McCallf746aa62010-03-19 23:29:14 +00001510 assert(Entry->isDeclaration());
1511
Chris Lattnerbd532712009-03-22 21:47:11 +00001512 // If there is a declaration in the module, then we had an extern followed
1513 // by the alias, as in:
1514 // extern int test6();
1515 // ...
1516 // int test6() __attribute__((alias("test7")));
1517 //
1518 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00001519 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Owen Anderson3c4972d2009-07-29 18:54:39 +00001521 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00001522 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00001523 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00001524 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00001525 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00001526 }
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001528 // Set attributes which are particular to an alias; this is a
1529 // specialization of the attributes which may be set on a global
1530 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001531 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001532 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1533 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001534 if (FD->hasBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001535 GA->setLinkage(llvm::Function::DLLExportLinkage);
1536 } else {
1537 GA->setLinkage(llvm::Function::DLLExportLinkage);
1538 }
Mike Stump1eb44332009-09-09 15:08:12 +00001539 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindola11e8ce72010-02-23 22:00:30 +00001540 D->hasAttr<WeakRefAttr>() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001541 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001542 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1543 }
1544
1545 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00001546}
1547
Chris Lattnerb808c952009-03-22 21:56:56 +00001548/// getBuiltinLibFunction - Given a builtin id for a function like
1549/// "__builtin_fabsf", return a Function* for "fabsf".
Daniel Dunbar34771b52009-09-14 04:33:21 +00001550llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1551 unsigned BuiltinID) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00001552 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001553 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
Douglas Gregor3e41d602009-02-13 23:20:09 +00001554 "isn't a lib fn");
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Douglas Gregor3e41d602009-02-13 23:20:09 +00001556 // Get the name, skip over the __builtin_ prefix (if necessary).
1557 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1558 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1559 Name += 10;
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Mike Stump1eb44332009-09-09 15:08:12 +00001561 const llvm::FunctionType *Ty =
Eli Friedman386ca782009-12-09 03:05:59 +00001562 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001563
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001564 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD), /*ForVTable=*/false);
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001565}
1566
Chris Lattner7acda7c2007-12-18 00:25:38 +00001567llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1568 unsigned NumTys) {
1569 return llvm::Intrinsic::getDeclaration(&getModule(),
1570 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1571}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001572
Daniel Dunbar1d552912009-07-23 22:52:48 +00001573static llvm::StringMapEntry<llvm::Constant*> &
1574GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1575 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001576 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00001577 bool &IsUTF16,
1578 unsigned &StringLength) {
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001579 llvm::StringRef String = Literal->getString();
1580 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001581
Daniel Dunbarf015b032009-09-22 10:03:52 +00001582 // Check for simple case.
1583 if (!Literal->containsNonAsciiOrNull()) {
1584 StringLength = NumBytes;
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001585 return Map.GetOrCreateValue(String);
Daniel Dunbarf015b032009-09-22 10:03:52 +00001586 }
1587
Daniel Dunbar1d552912009-07-23 22:52:48 +00001588 // Otherwise, convert the UTF8 literals into a byte string.
1589 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001590 const UTF8 *FromPtr = (UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001591 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00001593 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1594 &ToPtr, ToPtr + NumBytes,
1595 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001597 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00001598 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001599
1600 // Render the UTF-16 string into a byte array and convert to the target byte
1601 // order.
1602 //
1603 // FIXME: This isn't something we should need to do here.
1604 llvm::SmallString<128> AsBytes;
1605 AsBytes.reserve(StringLength * 2);
1606 for (unsigned i = 0; i != StringLength; ++i) {
1607 unsigned short Val = ToBuf[i];
1608 if (TargetIsLSB) {
1609 AsBytes.push_back(Val & 0xFF);
1610 AsBytes.push_back(Val >> 8);
1611 } else {
1612 AsBytes.push_back(Val >> 8);
1613 AsBytes.push_back(Val & 0xFF);
1614 }
1615 }
Daniel Dunbar434da482009-08-03 21:47:08 +00001616 // Append one extra null character, the second is automatically added by our
1617 // caller.
1618 AsBytes.push_back(0);
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001619
Daniel Dunbar1d552912009-07-23 22:52:48 +00001620 IsUTF16 = true;
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001621 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar1d552912009-07-23 22:52:48 +00001622}
1623
1624llvm::Constant *
1625CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1626 unsigned StringLength = 0;
1627 bool isUTF16 = false;
1628 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00001629 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001630 getTargetData().isLittleEndian(),
1631 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Daniel Dunbar1d552912009-07-23 22:52:48 +00001633 if (llvm::Constant *C = Entry.getValue())
1634 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Owen Anderson0032b272009-08-13 21:57:51 +00001636 llvm::Constant *Zero =
1637 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001638 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001640 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00001641 if (!CFConstantStringClassRef) {
1642 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001643 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001644 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001645 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001646 // Decay array -> ptr
1647 CFConstantStringClassRef =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001648 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001649 }
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Anders Carlssone3daa762008-11-15 18:54:24 +00001651 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001652
Mike Stump1eb44332009-09-09 15:08:12 +00001653 const llvm::StructType *STy =
Anders Carlssone3daa762008-11-15 18:54:24 +00001654 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1655
Anders Carlsson5add6832009-08-16 05:55:31 +00001656 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor44b43212008-12-11 16:49:14 +00001657
Anders Carlssonc9e20912007-08-21 00:21:21 +00001658 // Class pointer.
Anders Carlsson5add6832009-08-16 05:55:31 +00001659 Fields[0] = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Anders Carlssonc9e20912007-08-21 00:21:21 +00001661 // Flags.
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001662 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001663 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00001664 llvm::ConstantInt::get(Ty, 0x07C8);
1665
Anders Carlssonc9e20912007-08-21 00:21:21 +00001666 // String pointer.
Owen Anderson0032b272009-08-13 21:57:51 +00001667 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001668
Chris Lattner95b851e2009-07-16 05:03:48 +00001669 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001670 bool isConstant;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001671 if (isUTF16) {
Chris Lattner278b9f02009-10-14 05:55:45 +00001672 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner95b851e2009-07-16 05:03:48 +00001673 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001674 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1675 // does make plain ascii ones writable.
Daniel Dunbara9668e02009-04-03 00:57:44 +00001676 isConstant = true;
Chris Lattner278b9f02009-10-14 05:55:45 +00001677 } else {
Rafael Espindola584acf22011-03-14 17:55:00 +00001678 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1679 // when using private linkage. It is not clear if this is a bug in ld
1680 // or a reasonable new restriction.
Rafael Espindoladc0f1372011-03-14 21:08:19 +00001681 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001682 isConstant = !Features.WritableStrings;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001683 }
Chris Lattner278b9f02009-10-14 05:55:45 +00001684
Mike Stump1eb44332009-09-09 15:08:12 +00001685 llvm::GlobalVariable *GV =
Chris Lattner278b9f02009-10-14 05:55:45 +00001686 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1687 ".str");
Rafael Espindolab266a1f2011-01-17 16:31:00 +00001688 GV->setUnnamedAddr(true);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001689 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00001690 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1691 GV->setAlignment(Align.getQuantity());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001692 }
Anders Carlsson5add6832009-08-16 05:55:31 +00001693 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1694
Anders Carlssonc9e20912007-08-21 00:21:21 +00001695 // String length.
1696 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00001697 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Anders Carlssonc9e20912007-08-21 00:21:21 +00001699 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00001700 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00001701 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1702 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00001703 "_unnamed_cfstring_");
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001704 if (const char *Sect = getContext().Target.getCFStringSection())
1705 GV->setSection(Sect);
Daniel Dunbar1d552912009-07-23 22:52:48 +00001706 Entry.setValue(GV);
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Anders Carlsson0c678292007-11-01 00:41:52 +00001708 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001709}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001710
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001711llvm::Constant *
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001712CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001713 unsigned StringLength = 0;
1714 bool isUTF16 = false;
1715 llvm::StringMapEntry<llvm::Constant*> &Entry =
1716 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1717 getTargetData().isLittleEndian(),
1718 isUTF16, StringLength);
1719
1720 if (llvm::Constant *C = Entry.getValue())
1721 return C;
1722
1723 llvm::Constant *Zero =
1724 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1725 llvm::Constant *Zeros[] = { Zero, Zero };
1726
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001727 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001728 if (!ConstantStringClassRef) {
1729 std::string StringClass(getLangOptions().ObjCConstantStringClass);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001730 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1731 Ty = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001732 llvm::Constant *GV;
1733 if (StringClass.empty())
1734 GV = CreateRuntimeVariable(Ty,
1735 Features.ObjCNonFragileABI ?
1736 "OBJC_CLASS_$_NSConstantString" :
1737 "_NSConstantStringClassReference");
1738 else {
1739 std::string str;
1740 if (Features.ObjCNonFragileABI)
1741 str = "OBJC_CLASS_$_" + StringClass;
1742 else
1743 str = "_" + StringClass + "ClassReference";
1744 GV = CreateRuntimeVariable(Ty, str);
1745 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001746 // Decay array -> ptr
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001747 ConstantStringClassRef =
1748 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001749 }
1750
1751 QualType NSTy = getContext().getNSConstantStringType();
1752
1753 const llvm::StructType *STy =
1754 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1755
1756 std::vector<llvm::Constant*> Fields(3);
1757
1758 // Class pointer.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001759 Fields[0] = ConstantStringClassRef;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001760
1761 // String pointer.
1762 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1763
1764 llvm::GlobalValue::LinkageTypes Linkage;
1765 bool isConstant;
1766 if (isUTF16) {
1767 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1768 Linkage = llvm::GlobalValue::InternalLinkage;
1769 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1770 // does make plain ascii ones writable.
1771 isConstant = true;
1772 } else {
1773 Linkage = llvm::GlobalValue::PrivateLinkage;
1774 isConstant = !Features.WritableStrings;
1775 }
1776
1777 llvm::GlobalVariable *GV =
1778 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1779 ".str");
Rafael Espindola803d3072011-01-17 22:11:21 +00001780 GV->setUnnamedAddr(true);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001781 if (isUTF16) {
1782 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1783 GV->setAlignment(Align.getQuantity());
1784 }
1785 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1786
1787 // String length.
1788 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1789 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1790
1791 // The struct.
1792 C = llvm::ConstantStruct::get(STy, Fields);
1793 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1794 llvm::GlobalVariable::PrivateLinkage, C,
1795 "_unnamed_nsstring_");
1796 // FIXME. Fix section.
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001797 if (const char *Sect =
1798 Features.ObjCNonFragileABI
1799 ? getContext().Target.getNSStringNonFragileABISection()
1800 : getContext().Target.getNSStringSection())
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001801 GV->setSection(Sect);
1802 Entry.setValue(GV);
1803
1804 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001805}
1806
Daniel Dunbar61432932008-08-13 23:20:05 +00001807/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001808/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001809std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Ken Dyck3b8037a2011-01-29 17:53:12 +00001810 const ASTContext &Context = getContext();
Daniel Dunbar1e049762008-08-10 20:25:57 +00001811 const ConstantArrayType *CAT =
Ken Dyck3b8037a2011-01-29 17:53:12 +00001812 Context.getAsConstantArrayType(E->getType());
Daniel Dunbar1e049762008-08-10 20:25:57 +00001813 assert(CAT && "String isn't pointer or array!");
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001815 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001816 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001818 if (E->isWide())
Ken Dyck3b8037a2011-01-29 17:53:12 +00001819 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001821 std::string Str = E->getString().str();
Daniel Dunbar1e049762008-08-10 20:25:57 +00001822 Str.resize(RealLen, '\0');
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Daniel Dunbar1e049762008-08-10 20:25:57 +00001824 return Str;
1825}
1826
Daniel Dunbar61432932008-08-13 23:20:05 +00001827/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1828/// constant array for the given string literal.
1829llvm::Constant *
1830CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1831 // FIXME: This can be more efficient.
Eli Friedman7eb79c12009-11-16 05:55:46 +00001832 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1833 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1834 if (S->isWide()) {
1835 llvm::Type *DestTy =
1836 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1837 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1838 }
1839 return C;
Daniel Dunbar61432932008-08-13 23:20:05 +00001840}
1841
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001842/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1843/// array for the given ObjCEncodeExpr node.
1844llvm::Constant *
1845CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1846 std::string Str;
1847 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001848
1849 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001850}
1851
1852
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001853/// GenerateWritableString -- Creates storage for a string literal.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001854static llvm::Constant *GenerateStringLiteral(llvm::StringRef str,
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001855 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001856 CodeGenModule &CGM,
1857 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001858 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson0032b272009-08-13 21:57:51 +00001859 llvm::Constant *C =
1860 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001862 // Create a global variable for this string
Rafael Espindola1257bc62011-01-10 22:34:03 +00001863 llvm::GlobalVariable *GV =
1864 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1865 llvm::GlobalValue::PrivateLinkage,
1866 C, GlobalName);
1867 GV->setUnnamedAddr(true);
1868 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001869}
1870
Daniel Dunbar61432932008-08-13 23:20:05 +00001871/// GetAddrOfConstantString - Returns a pointer to a character array
1872/// containing the literal. This contents are exactly that of the
1873/// given string, i.e. it will not be null terminated automatically;
1874/// see GetAddrOfConstantCString. Note that whether the result is
1875/// actually a pointer to an LLVM constant depends on
1876/// Feature.WriteableStrings.
1877///
1878/// The result has pointer to array type.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001879llvm::Constant *CodeGenModule::GetAddrOfConstantString(llvm::StringRef Str,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001880 const char *GlobalName) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001881 bool IsConstant = !Features.WritableStrings;
1882
1883 // Get the default prefix if a name wasn't specified.
1884 if (!GlobalName)
Chris Lattner95b851e2009-07-16 05:03:48 +00001885 GlobalName = ".str";
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001886
1887 // Don't share any string literals if strings aren't constant.
1888 if (!IsConstant)
Benjamin Kramer9de43422011-03-05 13:45:23 +00001889 return GenerateStringLiteral(Str, false, *this, GlobalName);
Mike Stump1eb44332009-09-09 15:08:12 +00001890
1891 llvm::StringMapEntry<llvm::Constant *> &Entry =
Benjamin Kramer9de43422011-03-05 13:45:23 +00001892 ConstantStringMap.GetOrCreateValue(Str);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001893
1894 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001895 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001896
1897 // Create a global variable for this.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001898 llvm::Constant *C = GenerateStringLiteral(Str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001899 Entry.setValue(C);
1900 return C;
1901}
Daniel Dunbar61432932008-08-13 23:20:05 +00001902
1903/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer9de43422011-03-05 13:45:23 +00001904/// array containing the literal and a terminating '\0'
Daniel Dunbar61432932008-08-13 23:20:05 +00001905/// character. The result has pointer to array type.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001906llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001907 const char *GlobalName){
Benjamin Kramer9de43422011-03-05 13:45:23 +00001908 llvm::StringRef StrWithNull(Str.c_str(), Str.size() + 1);
1909 return GetAddrOfConstantString(StrWithNull, GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001910}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001911
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001912/// EmitObjCPropertyImplementations - Emit information for synthesized
1913/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00001914void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001915 ObjCImplementationDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001916 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001917 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001918 ObjCPropertyImplDecl *PID = *i;
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001920 // Dynamic is just for type-checking.
1921 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1922 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1923
1924 // Determine which methods need to be implemented, some may have
1925 // been overridden. Note that ::isSynthesized is not the method
1926 // we want, that just indicates if the decl came from a
1927 // property. What we want to know is if the method is defined in
1928 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001929 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001930 CodeGenFunction(*this).GenerateObjCGetter(
1931 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001932 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001933 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001934 CodeGenFunction(*this).GenerateObjCSetter(
1935 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001936 }
1937 }
1938}
1939
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001940/// EmitObjCIvarInitializations - Emit information for ivar initialization
1941/// for an implementation.
1942void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
David Chisnall827bbcc2011-03-17 14:19:08 +00001943 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001944 return;
1945 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1946 assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1947 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1948 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1949 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1950 D->getLocation(),
1951 D->getLocation(), cxxSelector,
1952 getContext().VoidTy, 0,
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00001953 DC, true, false, true, false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001954 ObjCMethodDecl::Required);
1955 D->addInstanceMethod(DTORMethod);
1956 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1957
1958 II = &getContext().Idents.get(".cxx_construct");
1959 cxxSelector = getContext().Selectors.getSelector(0, &II);
1960 // The constructor returns 'self'.
1961 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1962 D->getLocation(),
1963 D->getLocation(), cxxSelector,
1964 getContext().getObjCIdType(), 0,
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00001965 DC, true, false, true, false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001966 ObjCMethodDecl::Required);
1967 D->addInstanceMethod(CTORMethod);
1968 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1969
1970
1971}
1972
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001973/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00001974void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001975 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00001976 I != E; ++I)
1977 EmitTopLevelDecl(*I);
1978}
1979
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001980// EmitLinkageSpec - Emit all declarations in a linkage spec.
1981void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00001982 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1983 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001984 ErrorUnsupported(LSD, "linkage spec");
1985 return;
1986 }
1987
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001988 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001989 I != E; ++I)
1990 EmitTopLevelDecl(*I);
1991}
1992
Daniel Dunbar41071de2008-08-15 23:26:23 +00001993/// EmitTopLevelDecl - Emit code for a single top level declaration.
1994void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1995 // If an error has occurred, stop code generation, but continue
1996 // parsing and semantic analysis (to ensure all warnings and errors
1997 // are emitted).
1998 if (Diags.hasErrorOccurred())
1999 return;
2000
Douglas Gregor16e8be22009-06-29 17:30:29 +00002001 // Ignore dependent declarations.
2002 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2003 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Daniel Dunbar41071de2008-08-15 23:26:23 +00002005 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00002006 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00002007 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002008 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00002009 // Skip function templates
2010 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
2011 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002013 EmitGlobal(cast<FunctionDecl>(D));
2014 break;
2015
Daniel Dunbar41071de2008-08-15 23:26:23 +00002016 case Decl::Var:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002017 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002018 break;
2019
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002020 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00002021 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00002022 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002023 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002024 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00002025 case Decl::UsingShadow:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002026 case Decl::Using:
Douglas Gregordd9967a2009-09-02 23:49:23 +00002027 case Decl::UsingDirective:
Douglas Gregor127102b2009-06-29 20:59:39 +00002028 case Decl::ClassTemplate:
2029 case Decl::FunctionTemplate:
Anders Carlsson018837b2009-09-23 19:19:16 +00002030 case Decl::NamespaceAlias:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002031 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002032 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002033 // Skip function templates
2034 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
2035 return;
2036
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002037 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2038 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002039 case Decl::CXXDestructor:
2040 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2041 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00002042
2043 case Decl::StaticAssert:
2044 // Nothing to do.
2045 break;
2046
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002047 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00002049 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002050 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002051 case Decl::ObjCForwardProtocol:
Chris Lattner285d0db2009-04-01 02:36:43 +00002052 case Decl::ObjCInterface:
Chris Lattner285d0db2009-04-01 02:36:43 +00002053 break;
Fariborz Jahanian000835d2010-08-23 18:51:39 +00002054
2055 case Decl::ObjCCategory: {
2056 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2057 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2058 Context.ResetObjCLayout(CD->getClassInterface());
2059 break;
2060 }
2061
Chris Lattner285d0db2009-04-01 02:36:43 +00002062
Daniel Dunbar41071de2008-08-15 23:26:23 +00002063 case Decl::ObjCProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00002064 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002065 break;
2066
2067 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002068 // Categories have properties but don't support synthesize so we
2069 // can ignore them here.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002070 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2071 break;
2072
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002073 case Decl::ObjCImplementation: {
2074 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
Fariborz Jahanian000835d2010-08-23 18:51:39 +00002075 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2076 Context.ResetObjCLayout(OMD->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002077 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002078 EmitObjCIvarInitializations(OMD);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002079 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00002080 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002081 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00002082 case Decl::ObjCMethod: {
2083 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2084 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002085 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00002086 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2087 break;
2088 }
Mike Stump1eb44332009-09-09 15:08:12 +00002089 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00002090 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002091 break;
2092
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002093 case Decl::LinkageSpec:
2094 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002095 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00002096
2097 case Decl::FileScopeAsm: {
2098 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Benjamin Kramer8d042582009-12-11 13:33:18 +00002099 llvm::StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Daniel Dunbar41071de2008-08-15 23:26:23 +00002101 const std::string &S = getModule().getModuleInlineAsm();
2102 if (S.empty())
2103 getModule().setModuleInlineAsm(AsmString);
2104 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00002105 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002106 break;
2107 }
Mike Stump1eb44332009-09-09 15:08:12 +00002108
2109 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00002110 // Make sure we handled everything we should, every other kind is a
2111 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2112 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002113 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2114 }
2115}
John McCall744016d2010-07-06 23:57:41 +00002116
2117/// Turns the given pointer into a constant.
2118static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2119 const void *Ptr) {
2120 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2121 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2122 return llvm::ConstantInt::get(i64, PtrInt);
2123}
2124
2125static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2126 llvm::NamedMDNode *&GlobalMetadata,
2127 GlobalDecl D,
2128 llvm::GlobalValue *Addr) {
2129 if (!GlobalMetadata)
2130 GlobalMetadata =
2131 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2132
2133 // TODO: should we report variant information for ctors/dtors?
2134 llvm::Value *Ops[] = {
2135 Addr,
2136 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2137 };
2138 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2139}
2140
2141/// Emits metadata nodes associating all the global values in the
2142/// current module with the Decls they came from. This is useful for
2143/// projects using IR gen as a subroutine.
2144///
2145/// Since there's currently no way to associate an MDNode directly
2146/// with an llvm::GlobalValue, we create a global named metadata
2147/// with the name 'clang.global.decl.ptrs'.
2148void CodeGenModule::EmitDeclMetadata() {
2149 llvm::NamedMDNode *GlobalMetadata = 0;
2150
2151 // StaticLocalDeclMap
2152 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2153 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2154 I != E; ++I) {
2155 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2156 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2157 }
2158}
2159
2160/// Emits metadata nodes for all the local variables in the current
2161/// function.
2162void CodeGenFunction::EmitDeclMetadata() {
2163 if (LocalDeclMap.empty()) return;
2164
2165 llvm::LLVMContext &Context = getLLVMContext();
2166
2167 // Find the unique metadata ID for this name.
2168 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2169
2170 llvm::NamedMDNode *GlobalMetadata = 0;
2171
2172 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2173 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2174 const Decl *D = I->first;
2175 llvm::Value *Addr = I->second;
2176
2177 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2178 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2179 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2180 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2181 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2182 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2183 }
2184 }
2185}
Daniel Dunbar673431a2010-07-16 00:00:15 +00002186
2187///@name Custom Runtime Function Interfaces
2188///@{
2189//
2190// FIXME: These can be eliminated once we can have clients just get the required
2191// AST nodes from the builtin tables.
2192
2193llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2194 if (BlockObjectDispose)
2195 return BlockObjectDispose;
2196
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002197 // If we saw an explicit decl, use that.
2198 if (BlockObjectDisposeDecl) {
2199 return BlockObjectDispose = GetAddrOfFunction(
2200 BlockObjectDisposeDecl,
2201 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2202 }
2203
2204 // Otherwise construct the function by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002205 const llvm::FunctionType *FTy;
2206 std::vector<const llvm::Type*> ArgTys;
2207 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
John McCalld16c2cf2011-02-08 08:22:06 +00002208 ArgTys.push_back(Int8PtrTy);
Daniel Dunbar673431a2010-07-16 00:00:15 +00002209 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2210 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2211 return BlockObjectDispose =
2212 CreateRuntimeFunction(FTy, "_Block_object_dispose");
2213}
2214
2215llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2216 if (BlockObjectAssign)
2217 return BlockObjectAssign;
2218
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002219 // If we saw an explicit decl, use that.
2220 if (BlockObjectAssignDecl) {
2221 return BlockObjectAssign = GetAddrOfFunction(
2222 BlockObjectAssignDecl,
2223 getTypes().GetFunctionType(BlockObjectAssignDecl));
2224 }
2225
2226 // Otherwise construct the function by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002227 const llvm::FunctionType *FTy;
2228 std::vector<const llvm::Type*> ArgTys;
2229 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
John McCalld16c2cf2011-02-08 08:22:06 +00002230 ArgTys.push_back(Int8PtrTy);
2231 ArgTys.push_back(Int8PtrTy);
Daniel Dunbar673431a2010-07-16 00:00:15 +00002232 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2233 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2234 return BlockObjectAssign =
2235 CreateRuntimeFunction(FTy, "_Block_object_assign");
2236}
2237
2238llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2239 if (NSConcreteGlobalBlock)
2240 return NSConcreteGlobalBlock;
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002241
2242 // If we saw an explicit decl, use that.
2243 if (NSConcreteGlobalBlockDecl) {
2244 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2245 NSConcreteGlobalBlockDecl,
2246 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2247 }
2248
2249 // Otherwise construct the variable by hand.
John McCalld16c2cf2011-02-08 08:22:06 +00002250 return NSConcreteGlobalBlock =
2251 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteGlobalBlock");
Daniel Dunbar673431a2010-07-16 00:00:15 +00002252}
2253
2254llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2255 if (NSConcreteStackBlock)
2256 return NSConcreteStackBlock;
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002257
2258 // If we saw an explicit decl, use that.
2259 if (NSConcreteStackBlockDecl) {
2260 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2261 NSConcreteStackBlockDecl,
2262 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2263 }
2264
2265 // Otherwise construct the variable by hand.
John McCalld16c2cf2011-02-08 08:22:06 +00002266 return NSConcreteStackBlock =
2267 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteStackBlock");
Daniel Dunbar673431a2010-07-16 00:00:15 +00002268}
2269
2270///@}