blob: 6e8e439107efa05a7af5ce0067ff528cd44f93ac [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"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000021#include "CGOpenCLRuntime.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000022#include "TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000023#include "clang/Frontend/CodeGenOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/AST/ASTContext.h"
Ken Dyck687cc4a2010-01-26 13:48:07 +000025#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000026#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000027#include "clang/AST/DeclCXX.h"
Douglas Gregoraf896892010-06-21 18:41:26 +000028#include "clang/AST/DeclTemplate.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000029#include "clang/AST/Mangle.h"
Anders Carlsson1a5e0d72009-11-30 23:41:22 +000030#include "clang/AST/RecordLayout.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
Julien Lerouge77f68bb2011-09-09 22:41:49 +000047static const char AnnotationSection[] = "llvm.metadata";
48
John McCallf16aa102010-08-22 21:01:12 +000049static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000050 switch (CGM.getContext().getTargetInfo().getCXXABI()) {
John McCallf16aa102010-08-22 21:01:12 +000051 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
52 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
53 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
54 }
55
56 llvm_unreachable("invalid C++ ABI kind");
57 return *CreateItaniumCXXABI(CGM);
58}
59
Reid Spencer5f016e22007-07-11 17:01:13 +000060
Chandler Carruth2811ccf2009-11-12 17:24:48 +000061CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall468ec6c2010-03-04 04:29:44 +000062 llvm::Module &M, const llvm::TargetData &TD,
David Blaikied6471f72011-09-25 23:23:43 +000063 DiagnosticsEngine &diags)
John McCalld16c2cf2011-02-08 08:22:06 +000064 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall468ec6c2010-03-04 04:29:44 +000065 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCallf16aa102010-08-22 21:01:12 +000066 ABI(createCXXABI(*this)),
Daniel Dunbar08d47922011-06-21 18:54:39 +000067 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO),
Dan Gohman3d5aff52010-10-14 23:06:10 +000068 TBAA(0),
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000069 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), DebugInfo(0), ARCData(0),
70 RRData(0), CFConstantStringClassRef(0), ConstantStringClassRef(0),
Douglas Gregor45c4ea72011-08-09 15:54:21 +000071 NSConstantStringType(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000072 VMContext(M.getContext()),
73 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
John McCalld16c2cf2011-02-08 08:22:06 +000074 BlockObjectAssign(0), BlockObjectDispose(0),
75 BlockDescriptorType(0), GenericBlockLiteralType(0) {
David Chisnall60be6072011-03-22 21:21:24 +000076 if (Features.ObjC1)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000077 createObjCRuntime();
78 if (Features.OpenCL)
79 createOpenCLRuntime();
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000080
Dan Gohman3d5aff52010-10-14 23:06:10 +000081 // Enable TBAA unless it's suppressed.
82 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
Dan Gohman0b5c4fc2010-10-15 20:23:12 +000083 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
84 ABI.getMangleContext());
Dan Gohman3d5aff52010-10-14 23:06:10 +000085
Nick Lewyckye8ba8d72011-04-21 23:44:07 +000086 // If debug info or coverage generation is enabled, create the CGDebugInfo
87 // object.
88 if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
89 CodeGenOpts.EmitGcovNotes)
90 DebugInfo = new CGDebugInfo(*this);
John McCalld16c2cf2011-02-08 08:22:06 +000091
92 Block.GlobalUniqueCount = 0;
John McCall5936e332011-02-15 09:22:45 +000093
John McCallf85e1932011-06-15 23:02:42 +000094 if (C.getLangOptions().ObjCAutoRefCount)
95 ARCData = new ARCEntrypoints();
96 RRData = new RREntrypoints();
97
John McCall5936e332011-02-15 09:22:45 +000098 // Initialize the type cache.
99 llvm::LLVMContext &LLVMContext = M.getContext();
John McCall0774cb82011-05-15 01:53:33 +0000100 VoidTy = llvm::Type::getVoidTy(LLVMContext);
101 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
102 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
103 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000104 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
John McCall34695852011-02-22 06:44:22 +0000105 PointerAlignInBytes =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000106 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
107 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
John McCall5936e332011-02-15 09:22:45 +0000108 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
109 Int8PtrTy = Int8Ty->getPointerTo(0);
110 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Chris Lattner2b94fe32008-03-01 08:45:05 +0000111}
112
113CodeGenModule::~CodeGenModule() {
Peter Collingbournee9265232011-07-27 20:29:46 +0000114 delete ObjCRuntime;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000115 delete OpenCLRuntime;
John McCallf16aa102010-08-22 21:01:12 +0000116 delete &ABI;
Dan Gohman4376c852010-10-15 18:04:46 +0000117 delete TBAA;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000118 delete DebugInfo;
John McCallf85e1932011-06-15 23:02:42 +0000119 delete ARCData;
120 delete RRData;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000121}
122
David Chisnall0d13f6f2010-01-23 02:40:42 +0000123void CodeGenModule::createObjCRuntime() {
124 if (!Features.NeXTRuntime)
Peter Collingbournee9265232011-07-27 20:29:46 +0000125 ObjCRuntime = CreateGNUObjCRuntime(*this);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000126 else
Peter Collingbournee9265232011-07-27 20:29:46 +0000127 ObjCRuntime = CreateMacObjCRuntime(*this);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000128}
129
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000130void CodeGenModule::createOpenCLRuntime() {
131 OpenCLRuntime = new CGOpenCLRuntime(*this);
132}
133
Ted Kremenek815c78f2008-08-05 18:50:11 +0000134void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000135 EmitDeferred();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000136 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000137 EmitCXXGlobalDtorFunc();
Peter Collingbournee9265232011-07-27 20:29:46 +0000138 if (ObjCRuntime)
139 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000140 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000141 EmitCtorList(GlobalCtors, "llvm.global_ctors");
142 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000143 EmitGlobalAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +0000144 EmitLLVMUsed();
John McCall744016d2010-07-06 23:57:41 +0000145
John McCallb2593832010-09-16 06:16:50 +0000146 SimplifyPersonality();
147
John McCall744016d2010-07-06 23:57:41 +0000148 if (getCodeGenOpts().EmitDeclMetadata)
149 EmitDeclMetadata();
Nick Lewycky5ea4f442011-05-04 20:46:58 +0000150
151 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky3dc05412011-05-05 00:08:20 +0000152 EmitCoverageFile();
Devang Patelf391dbe2011-08-16 20:58:22 +0000153
154 if (DebugInfo)
155 DebugInfo->finalize();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000156}
157
Devang Patele80d5672011-03-23 16:29:39 +0000158void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
159 // Make sure that this type is translated.
160 Types.UpdateCompletedType(TD);
161 if (DebugInfo)
162 DebugInfo->UpdateCompletedType(TD);
163}
164
Dan Gohman3d5aff52010-10-14 23:06:10 +0000165llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
166 if (!TBAA)
167 return 0;
168 return TBAA->getTBAAInfo(QTy);
169}
170
171void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
172 llvm::MDNode *TBAAInfo) {
173 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
174}
175
John McCall6374c332010-03-06 00:35:14 +0000176bool CodeGenModule::isTargetDarwin() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000177 return getContext().getTargetInfo().getTriple().isOSDarwin();
John McCall6374c332010-03-06 00:35:14 +0000178}
179
Chris Lattner5f9e2722011-07-23 10:55:15 +0000180void CodeGenModule::Error(SourceLocation loc, StringRef error) {
David Blaikied6471f72011-09-25 23:23:43 +0000181 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
John McCall32096692011-03-18 02:56:14 +0000182 getDiags().Report(Context.getFullLoc(loc), diagID);
183}
184
Daniel Dunbar488e9932008-08-16 00:56:44 +0000185/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000186/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000187void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
188 bool OmitOnError) {
189 if (OmitOnError && getDiags().hasErrorOccurred())
190 return;
David Blaikied6471f72011-09-25 23:23:43 +0000191 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000192 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000193 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000194 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
195 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000196}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000197
Daniel Dunbar488e9932008-08-16 00:56:44 +0000198/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000199/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000200void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
201 bool OmitOnError) {
202 if (OmitOnError && getDiags().hasErrorOccurred())
203 return;
David Blaikied6471f72011-09-25 23:23:43 +0000204 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000205 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000206 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000207 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000208}
209
John McCallbc8d40d2011-06-24 21:55:10 +0000210llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
211 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
212}
213
Mike Stump1eb44332009-09-09 15:08:12 +0000214void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000215 const NamedDecl *D) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000216 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000217 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000218 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000219 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000220 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000221
John McCallaf146032010-10-30 11:50:40 +0000222 // Set visibility for definitions.
223 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000224 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
225 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000226}
227
John McCallcbfe5022010-08-04 08:34:44 +0000228/// Set the symbol visibility of type information (vtable and RTTI)
229/// associated with the given type.
230void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
231 const CXXRecordDecl *RD,
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000232 TypeVisibilityKind TVK) const {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000233 setGlobalVisibility(GV, RD);
John McCallcbfe5022010-08-04 08:34:44 +0000234
John McCall279b5eb2010-08-12 23:36:15 +0000235 if (!CodeGenOpts.HiddenWeakVTables)
236 return;
237
Anders Carlsson9a86a132011-01-29 20:36:11 +0000238 // We never want to drop the visibility for RTTI names.
239 if (TVK == TVK_ForRTTIName)
240 return;
241
John McCallcbfe5022010-08-04 08:34:44 +0000242 // We want to drop the visibility to hidden for weak type symbols.
243 // This isn't possible if there might be unresolved references
244 // elsewhere that rely on this symbol being visible.
245
John McCall7a536902010-08-05 20:39:18 +0000246 // This should be kept roughly in sync with setThunkVisibility
247 // in CGVTables.cpp.
248
John McCallcbfe5022010-08-04 08:34:44 +0000249 // Preconditions.
Anders Carlssonf502d932011-01-24 00:46:19 +0000250 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCallcbfe5022010-08-04 08:34:44 +0000251 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
252 return;
253
254 // Don't override an explicit visibility attribute.
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000255 if (RD->getExplicitVisibility())
John McCallcbfe5022010-08-04 08:34:44 +0000256 return;
257
258 switch (RD->getTemplateSpecializationKind()) {
259 // We have to disable the optimization if this is an EI definition
260 // because there might be EI declarations in other shared objects.
261 case TSK_ExplicitInstantiationDefinition:
262 case TSK_ExplicitInstantiationDeclaration:
263 return;
264
John McCall7a536902010-08-05 20:39:18 +0000265 // Every use of a non-template class's type information has to emit it.
John McCallcbfe5022010-08-04 08:34:44 +0000266 case TSK_Undeclared:
267 break;
268
John McCall7a536902010-08-05 20:39:18 +0000269 // In theory, implicit instantiations can ignore the possibility of
270 // an explicit instantiation declaration because there necessarily
271 // must be an EI definition somewhere with default visibility. In
272 // practice, it's possible to have an explicit instantiation for
273 // an arbitrary template class, and linkers aren't necessarily able
274 // to deal with mixed-visibility symbols.
275 case TSK_ExplicitSpecialization:
John McCallcbfe5022010-08-04 08:34:44 +0000276 case TSK_ImplicitInstantiation:
John McCall279b5eb2010-08-12 23:36:15 +0000277 if (!CodeGenOpts.HiddenWeakTemplateVTables)
John McCall7a536902010-08-05 20:39:18 +0000278 return;
John McCallcbfe5022010-08-04 08:34:44 +0000279 break;
280 }
281
282 // If there's a key function, there may be translation units
283 // that don't have the key function's definition. But ignore
284 // this if we're emitting RTTI under -fno-rtti.
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000285 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
John McCallcbfe5022010-08-04 08:34:44 +0000286 if (Context.getKeyFunction(RD))
287 return;
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000288 }
John McCallcbfe5022010-08-04 08:34:44 +0000289
290 // Otherwise, drop the visibility to hidden.
291 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1c65ff2011-01-11 21:44:37 +0000292 GV->setUnnamedAddr(true);
John McCallcbfe5022010-08-04 08:34:44 +0000293}
294
Chris Lattner5f9e2722011-07-23 10:55:15 +0000295StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000296 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
297
Chris Lattner5f9e2722011-07-23 10:55:15 +0000298 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
Anders Carlsson793a9902010-06-22 16:05:32 +0000299 if (!Str.empty())
300 return Str;
301
John McCall4c40d982010-08-31 07:33:07 +0000302 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000303 IdentifierInfo *II = ND->getIdentifier();
304 assert(II && "Attempt to mangle unnamed decl.");
305
306 Str = II->getName();
307 return Str;
308 }
309
310 llvm::SmallString<256> Buffer;
Rafael Espindolac4850c22011-02-10 23:59:36 +0000311 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000312 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000313 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000314 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000315 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000316 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000317 getCXXABI().getMangleContext().mangleBlock(BD, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000318 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000319 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000320
321 // Allocate space for the mangled name.
Rafael Espindolac4850c22011-02-10 23:59:36 +0000322 Out.flush();
Anders Carlsson793a9902010-06-22 16:05:32 +0000323 size_t Length = Buffer.size();
324 char *Name = MangledNamesAllocator.Allocate<char>(Length);
325 std::copy(Buffer.begin(), Buffer.end(), Name);
326
Chris Lattner5f9e2722011-07-23 10:55:15 +0000327 Str = StringRef(Name, Length);
Anders Carlsson793a9902010-06-22 16:05:32 +0000328
329 return Str;
330}
331
Peter Collingbourne14110472011-01-13 18:57:25 +0000332void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
333 const BlockDecl *BD) {
334 MangleContext &MangleCtx = getCXXABI().getMangleContext();
335 const Decl *D = GD.getDecl();
Rafael Espindolac4850c22011-02-10 23:59:36 +0000336 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne14110472011-01-13 18:57:25 +0000337 if (D == 0)
Rafael Espindolac4850c22011-02-10 23:59:36 +0000338 MangleCtx.mangleGlobalBlock(BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000339 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000340 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000341 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000342 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000343 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000344 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000345}
346
Chris Lattner5f9e2722011-07-23 10:55:15 +0000347llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCallf746aa62010-03-19 23:29:14 +0000348 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000349}
350
Chris Lattner6d397602008-03-14 17:18:18 +0000351/// AddGlobalCtor - Add a function to the list that will be called before
352/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000353void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000354 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000355 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000356}
357
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000358/// AddGlobalDtor - Add a function to the list that will be called
359/// when the module is unloaded.
360void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000361 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000362 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
363}
364
365void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
366 // Ctor function type is void()*.
John McCall0774cb82011-05-15 01:53:33 +0000367 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000368 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000369
370 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000371 llvm::StructType *CtorStructTy =
Chris Lattner7650d952011-06-18 22:49:11 +0000372 llvm::StructType::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson96e0fc72009-07-29 22:16:19 +0000373 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000374
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000375 // Construct the constructor and destructor arrays.
376 std::vector<llvm::Constant*> Ctors;
377 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
378 std::vector<llvm::Constant*> S;
Mike Stump1eb44332009-09-09 15:08:12 +0000379 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson0032b272009-08-13 21:57:51 +0000380 I->second, false));
Owen Anderson3c4972d2009-07-29 18:54:39 +0000381 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson08e25242009-07-27 22:29:56 +0000382 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000383 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000384
385 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000386 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000387 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000388 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000389 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000390 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000391 }
Chris Lattner6d397602008-03-14 17:18:18 +0000392}
393
John McCalld46f9852010-02-19 01:32:20 +0000394llvm::GlobalValue::LinkageTypes
395CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000396 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000397
Chris Lattnerf81530652010-06-30 16:58:07 +0000398 if (Linkage == GVA_Internal)
John McCalld46f9852010-02-19 01:32:20 +0000399 return llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000400
401 if (D->hasAttr<DLLExportAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000402 return llvm::Function::DLLExportLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000403
404 if (D->hasAttr<WeakAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000405 return llvm::Function::WeakAnyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000406
407 // In C99 mode, 'inline' functions are guaranteed to have a strong
408 // definition somewhere else, so we can use available_externally linkage.
409 if (Linkage == GVA_C99Inline)
Fariborz Jahanianfd0f89d2011-02-04 00:08:13 +0000410 return llvm::Function::AvailableExternallyLinkage;
John McCall5584d912011-09-19 18:05:26 +0000411
412 // Note that Apple's kernel linker doesn't support symbol
413 // coalescing, so we need to avoid linkonce and weak linkages there.
414 // Normally, this means we just map to internal, but for explicit
415 // instantiations we'll map to external.
416
Chris Lattnerf81530652010-06-30 16:58:07 +0000417 // In C++, the compiler has to emit a definition in every translation unit
418 // that references the function. We should use linkonce_odr because
419 // a) if all references in this translation unit are optimized away, we
420 // don't need to codegen it. b) if the function persists, it needs to be
421 // merged with other definitions. c) C++ has the ODR, so we know the
422 // definition is dependable.
423 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000424 return !Context.getLangOptions().AppleKext
425 ? llvm::Function::LinkOnceODRLinkage
426 : llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000427
428 // An explicit instantiation of a template has weak linkage, since
429 // explicit instantiations can occur in multiple translation units
430 // and must all be equivalent. However, we are not allowed to
431 // throw away these explicit instantiations.
432 if (Linkage == GVA_ExplicitTemplateInstantiation)
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000433 return !Context.getLangOptions().AppleKext
434 ? llvm::Function::WeakODRLinkage
John McCall5584d912011-09-19 18:05:26 +0000435 : llvm::Function::ExternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000436
437 // Otherwise, we have strong external linkage.
438 assert(Linkage == GVA_StrongExternal);
439 return llvm::Function::ExternalLinkage;
John McCalld46f9852010-02-19 01:32:20 +0000440}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000441
John McCalld46f9852010-02-19 01:32:20 +0000442
443/// SetFunctionDefinitionAttributes - Set attributes for a global.
444///
445/// FIXME: This is currently only done for aliases and functions, but not for
446/// variables (these details are set in EmitGlobalVarDefinition for variables).
447void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
448 llvm::GlobalValue *GV) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000449 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000450}
451
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000452void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000453 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000454 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000455 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000456 AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000457 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel761d7f72008-09-25 21:02:23 +0000458 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000459 AttributeList.size()));
460 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000461}
462
John McCalld1e40d52011-10-02 01:16:38 +0000463/// Determines whether the language options require us to model
464/// unwind exceptions. We treat -fexceptions as mandating this
465/// except under the fragile ObjC ABI with only ObjC exceptions
466/// enabled. This means, for example, that C with -fexceptions
467/// enables this.
468static bool hasUnwindExceptions(const LangOptions &Features) {
469 // If exceptions are completely disabled, obviously this is false.
470 if (!Features.Exceptions) return false;
471
472 // If C++ exceptions are enabled, this is true.
473 if (Features.CXXExceptions) return true;
474
475 // If ObjC exceptions are enabled, this depends on the ABI.
476 if (Features.ObjCExceptions) {
477 if (!Features.ObjCNonFragileABI) return false;
478 }
479
480 return true;
481}
482
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000483void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
484 llvm::Function *F) {
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000485 if (CodeGenOpts.UnwindTables)
486 F->setHasUWTable();
487
John McCalld1e40d52011-10-02 01:16:38 +0000488 if (!hasUnwindExceptions(Features))
Mike Stump1eb44332009-09-09 15:08:12 +0000489 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000490
Eli Friedman2873aee2011-08-22 23:55:33 +0000491 if (D->hasAttr<NakedAttr>()) {
492 // Naked implies noinline: we should not be inlining such functions.
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000493 F->addFnAttr(llvm::Attribute::Naked);
Eli Friedman2873aee2011-08-22 23:55:33 +0000494 F->addFnAttr(llvm::Attribute::NoInline);
495 }
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000496
Mike Stump1feade82009-08-26 22:31:08 +0000497 if (D->hasAttr<NoInlineAttr>())
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000498 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpf55314d2009-10-05 21:58:44 +0000499
Eli Friedman2873aee2011-08-22 23:55:33 +0000500 // (noinline wins over always_inline, and we can't specify both in IR)
501 if (D->hasAttr<AlwaysInlineAttr>() &&
502 !F->hasFnAttr(llvm::Attribute::NoInline))
503 F->addFnAttr(llvm::Attribute::AlwaysInline);
504
Rafael Espindolac5f657f2011-01-11 00:26:26 +0000505 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
506 F->setUnnamedAddr(true);
507
Douglas Gregore289d812011-09-13 17:21:33 +0000508 if (Features.getStackProtector() == LangOptions::SSPOn)
Anders Carlssonfd015352009-11-16 16:56:03 +0000509 F->addFnAttr(llvm::Attribute::StackProtect);
Douglas Gregore289d812011-09-13 17:21:33 +0000510 else if (Features.getStackProtector() == LangOptions::SSPReq)
Anders Carlssonfd015352009-11-16 16:56:03 +0000511 F->addFnAttr(llvm::Attribute::StackProtectReq);
512
Sean Huntcf807c42010-08-18 23:23:40 +0000513 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
514 if (alignment)
515 F->setAlignment(alignment);
516
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000517 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000518 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
519 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000520}
521
Mike Stump1eb44332009-09-09 15:08:12 +0000522void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000523 llvm::GlobalValue *GV) {
Anders Carlsson934176f2011-01-29 19:41:00 +0000524 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
525 setGlobalVisibility(GV, ND);
John McCall1fb0caa2010-10-22 21:05:15 +0000526 else
527 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000528
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000529 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000530 AddUsedGlobal(GV);
531
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000532 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000533 GV->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000534
535 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000536}
537
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000538void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
539 llvm::Function *F,
540 const CGFunctionInfo &FI) {
541 SetLLVMFunctionAttributes(D, FI, F);
542 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000543
544 F->setLinkage(llvm::Function::InternalLinkage);
545
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000546 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000547}
548
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000549void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000550 llvm::Function *F,
551 bool IsIncompleteFunction) {
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000552 if (unsigned IID = F->getIntrinsicID()) {
553 // If this is an intrinsic function, set the function's attributes
554 // to the intrinsic's attributes.
555 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
556 return;
557 }
558
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000559 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
560
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000561 if (!IsIncompleteFunction)
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000562 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000564 // Only a few attributes are set on declarations; these may later be
565 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000567 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000568 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump1eb44332009-09-09 15:08:12 +0000569 } else if (FD->hasAttr<WeakAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000570 FD->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000571 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump1eb44332009-09-09 15:08:12 +0000572 // separate linkage types for this.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000573 F->setLinkage(llvm::Function::ExternalWeakLinkage);
574 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000575 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallaf146032010-10-30 11:50:40 +0000576
577 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
578 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
579 F->setVisibility(GetLLVMVisibility(LV.visibility()));
580 }
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000581 }
582
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000583 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000584 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000585}
586
Daniel Dunbar02698712009-02-13 20:29:50 +0000587void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +0000588 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +0000589 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000590 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000591}
592
593void CodeGenModule::EmitLLVMUsed() {
594 // Don't create llvm.used if there is no need.
Chris Lattnerad64e022009-07-17 23:57:13 +0000595 if (LLVMUsed.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +0000596 return;
597
Chris Lattner2acc6e32011-07-18 04:24:23 +0000598 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Chris Lattner35f38a22009-03-31 22:37:52 +0000600 // Convert LLVMUsed to what ConstantArray needs.
601 std::vector<llvm::Constant*> UsedArray;
602 UsedArray.resize(LLVMUsed.size());
603 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000604 UsedArray[i] =
605 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000606 i8PTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000607 }
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000609 if (UsedArray.empty())
610 return;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000611 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000612
613 llvm::GlobalVariable *GV =
614 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar02698712009-02-13 20:29:50 +0000615 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000616 llvm::ConstantArray::get(ATy, UsedArray),
Owen Anderson1c431b32009-07-08 19:05:04 +0000617 "llvm.used");
Daniel Dunbar02698712009-02-13 20:29:50 +0000618
619 GV->setSection("llvm.metadata");
620}
621
622void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000623 // Emit code for any potentially referenced deferred decls. Since a
624 // previously unused static decl may become used during the generation of code
Nick Lewyckydce67a72011-07-18 05:26:13 +0000625 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000626
Anders Carlsson046c2942010-04-17 20:15:18 +0000627 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
628 if (!DeferredVTables.empty()) {
629 const CXXRecordDecl *RD = DeferredVTables.back();
630 DeferredVTables.pop_back();
631 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000632 continue;
633 }
634
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000635 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000636 DeferredDeclsToEmit.pop_back();
637
John McCallc76702c2010-05-27 01:45:30 +0000638 // Check to see if we've already emitted this. This is necessary
639 // for a couple of reasons: first, decls can end up in the
640 // deferred-decls queue multiple times, and second, decls can end
641 // up with definitions in unusual ways (e.g. by an extern inline
642 // function acquiring a strong function redefinition). Just
643 // ignore these cases.
644 //
645 // TODO: That said, looking this up multiple times is very wasteful.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000646 StringRef Name = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +0000647 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner67b00522009-03-21 09:44:56 +0000648 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Chris Lattner67b00522009-03-21 09:44:56 +0000650 if (!CGRef->isDeclaration())
651 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000652
John McCallc76702c2010-05-27 01:45:30 +0000653 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
654 // purposes an alias counts as a definition.
655 if (isa<llvm::GlobalAlias>(CGRef))
656 continue;
657
Chris Lattner67b00522009-03-21 09:44:56 +0000658 // Otherwise, emit the definition and move on to the next one.
659 EmitGlobalDefinition(D);
660 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000661}
662
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000663void CodeGenModule::EmitGlobalAnnotations() {
664 if (Annotations.empty())
665 return;
666
667 // Create a new global variable for the ConstantStruct in the Module.
668 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
669 Annotations[0]->getType(), Annotations.size()), Annotations);
670 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
671 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
672 "llvm.global.annotations");
673 gv->setSection(AnnotationSection);
674}
675
676llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
677 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
678 if (i != AnnotationStrings.end())
679 return i->second;
680
681 // Not found yet, create a new global.
682 llvm::Constant *s = llvm::ConstantArray::get(getLLVMContext(), Str, true);
683 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
684 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
685 gv->setSection(AnnotationSection);
686 gv->setUnnamedAddr(true);
687 AnnotationStrings[Str] = gv;
688 return gv;
689}
690
691llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
692 SourceManager &SM = getContext().getSourceManager();
693 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
694 if (PLoc.isValid())
695 return EmitAnnotationString(PLoc.getFilename());
696 return EmitAnnotationString(SM.getBufferName(Loc));
697}
698
699llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
700 SourceManager &SM = getContext().getSourceManager();
701 PresumedLoc PLoc = SM.getPresumedLoc(L);
702 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
703 SM.getExpansionLineNumber(L);
704 return llvm::ConstantInt::get(Int32Ty, LineNo);
705}
706
Mike Stump1eb44332009-09-09 15:08:12 +0000707llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000708 const AnnotateAttr *AA,
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000709 SourceLocation L) {
710 // Get the globals for file name, annotation, and the line number.
711 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
712 *UnitGV = EmitAnnotationUnit(L),
713 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000714
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000715 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000716 llvm::Constant *Fields[4] = {
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000717 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
718 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
719 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
720 LineNoCst
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000721 };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000722 return llvm::ConstantStruct::getAnon(Fields);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000723}
724
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000725void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
726 llvm::GlobalValue *GV) {
727 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
728 // Get the struct elements for these annotations.
729 for (specific_attr_iterator<AnnotateAttr>
730 ai = D->specific_attr_begin<AnnotateAttr>(),
731 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
732 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
733}
734
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000735bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000736 // Never defer when EmitAllDecls is specified.
737 if (Features.EmitAllDecls)
Daniel Dunbar73241df2009-02-13 21:18:01 +0000738 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000739
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +0000740 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000741}
742
Rafael Espindola6a836702010-03-04 18:17:24 +0000743llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
744 const AliasAttr *AA = VD->getAttr<AliasAttr>();
745 assert(AA && "No alias?");
746
Chris Lattner2acc6e32011-07-18 04:24:23 +0000747 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola6a836702010-03-04 18:17:24 +0000748
Rafael Espindola6a836702010-03-04 18:17:24 +0000749 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +0000750 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola6a836702010-03-04 18:17:24 +0000751
752 llvm::Constant *Aliasee;
753 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000754 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
755 /*ForVTable=*/false);
Rafael Espindola6a836702010-03-04 18:17:24 +0000756 else
John McCallf746aa62010-03-19 23:29:14 +0000757 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola6a836702010-03-04 18:17:24 +0000758 llvm::PointerType::getUnqual(DeclTy), 0);
759 if (!Entry) {
760 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
761 F->setLinkage(llvm::Function::ExternalWeakLinkage);
762 WeakRefReferences.insert(F);
763 }
764
765 return Aliasee;
766}
767
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000768void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000769 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Rafael Espindola6a836702010-03-04 18:17:24 +0000771 // Weak references don't produce any output by themselves.
772 if (Global->hasAttr<WeakRefAttr>())
773 return;
774
Chris Lattnerbd532712009-03-22 21:47:11 +0000775 // If this is an alias definition (which otherwise looks like a declaration)
776 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000777 if (Global->hasAttr<AliasAttr>())
John McCallf746aa62010-03-19 23:29:14 +0000778 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +0000779
Chris Lattner67b00522009-03-21 09:44:56 +0000780 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000781 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000782 // Forward declarations are emitted lazily on first use.
Nick Lewyckydce67a72011-07-18 05:26:13 +0000783 if (!FD->doesThisDeclarationHaveABody()) {
784 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
785 return;
786
787 const FunctionDecl *InlineDefinition = 0;
788 FD->getBody(InlineDefinition);
789
Chris Lattner5f9e2722011-07-23 10:55:15 +0000790 StringRef MangledName = getMangledName(GD);
Nick Lewyckydce67a72011-07-18 05:26:13 +0000791 llvm::StringMap<GlobalDecl>::iterator DDI =
792 DeferredDecls.find(MangledName);
793 if (DDI != DeferredDecls.end())
794 DeferredDecls.erase(DDI);
795 EmitGlobalDefinition(InlineDefinition);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000796 return;
Nick Lewyckydce67a72011-07-18 05:26:13 +0000797 }
Daniel Dunbar02698712009-02-13 20:29:50 +0000798 } else {
799 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000800 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
801
Douglas Gregora9a55c02010-02-06 05:15:45 +0000802 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000803 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000804 }
805
Chris Lattner67b00522009-03-21 09:44:56 +0000806 // Defer code generation when possible if this is a static definition, inline
807 // function etc. These we only want to emit if they are used.
Chris Lattner4357a822010-04-13 17:39:09 +0000808 if (!MayDeferGeneration(Global)) {
809 // Emit the definition if it can't be deferred.
810 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000811 return;
812 }
John McCallbf40cb52010-07-15 23:40:35 +0000813
814 // If we're deferring emission of a C++ variable with an
815 // initializer, remember the order in which it appeared in the file.
816 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
817 cast<VarDecl>(Global)->hasInit()) {
818 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
819 CXXGlobalInits.push_back(0);
820 }
Chris Lattner4357a822010-04-13 17:39:09 +0000821
822 // If the value has already been used, add it directly to the
823 // DeferredDeclsToEmit list.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000824 StringRef MangledName = getMangledName(GD);
Chris Lattner4357a822010-04-13 17:39:09 +0000825 if (GetGlobalValue(MangledName))
826 DeferredDeclsToEmit.push_back(GD);
827 else {
828 // Otherwise, remember that we saw a deferred decl with this name. The
829 // first use of the mangled name will cause it to move into
830 // DeferredDeclsToEmit.
831 DeferredDecls[MangledName] = GD;
832 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000833}
834
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000835void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000836 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Dan Gohmancb421fa2010-04-19 16:39:44 +0000838 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +0000839 Context.getSourceManager(),
840 "Generating code for declaration");
841
Douglas Gregor44eac332010-07-13 06:02:28 +0000842 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
843 // At -O0, don't generate IR for functions with available_externally
844 // linkage.
Douglas Gregor7feaeee2010-07-15 22:58:18 +0000845 if (CodeGenOpts.OptimizationLevel == 0 &&
846 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregor44eac332010-07-13 06:02:28 +0000847 getFunctionLinkage(Function)
848 == llvm::Function::AvailableExternallyLinkage)
849 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +0000850
Douglas Gregor44eac332010-07-13 06:02:28 +0000851 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000852 // Make sure to emit the definition(s) before we emit the thunks.
853 // This is necessary for the generation of certain thunks.
854 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
855 EmitCXXConstructor(CD, GD.getCtorType());
856 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
857 EmitCXXDestructor(DD, GD.getDtorType());
858 else
859 EmitGlobalFunctionDefinition(GD);
860
Douglas Gregor44eac332010-07-13 06:02:28 +0000861 if (Method->isVirtual())
862 getVTables().EmitThunks(GD);
863
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000864 return;
Douglas Gregor44eac332010-07-13 06:02:28 +0000865 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000866
Chris Lattnerb5e81562010-04-13 17:57:11 +0000867 return EmitGlobalFunctionDefinition(GD);
Douglas Gregor44eac332010-07-13 06:02:28 +0000868 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000869
870 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
871 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +0000872
David Blaikieb219cfc2011-09-23 05:06:16 +0000873 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000874}
875
Chris Lattner74391b42009-03-22 21:03:39 +0000876/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
877/// module, create and return an llvm Function with the specified type. If there
878/// is something in the module with the specified name, return it potentially
879/// bitcasted to the right type.
880///
881/// If D is non-null, it specifies a decl that correspond to this. This is used
882/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +0000883llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000884CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000885 llvm::Type *Ty,
John McCallf85e1932011-06-15 23:02:42 +0000886 GlobalDecl D, bool ForVTable,
887 llvm::Attributes ExtraAttrs) {
Chris Lattner0558e792009-03-21 09:25:43 +0000888 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +0000889 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +0000890 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +0000891 if (WeakRefReferences.count(Entry)) {
892 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
893 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +0000894 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +0000895
896 WeakRefReferences.erase(Entry);
897 }
898
Chris Lattner0558e792009-03-21 09:25:43 +0000899 if (Entry->getType()->getElementType() == Ty)
900 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Chris Lattner0558e792009-03-21 09:25:43 +0000902 // Make sure the result is of the correct type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000903 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattner0558e792009-03-21 09:25:43 +0000904 }
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Eli Friedman654ad402009-11-09 05:07:37 +0000906 // This function doesn't have a complete type (for example, the return
907 // type is an incomplete struct). Use a fake type instead, and make
908 // sure not to try to set attributes.
909 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +0000910
Chris Lattner2acc6e32011-07-18 04:24:23 +0000911 llvm::FunctionType *FTy;
John McCall784f2112010-04-28 00:00:30 +0000912 if (isa<llvm::FunctionType>(Ty)) {
913 FTy = cast<llvm::FunctionType>(Ty);
914 } else {
John McCall0774cb82011-05-15 01:53:33 +0000915 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedman654ad402009-11-09 05:07:37 +0000916 IsIncompleteFunction = true;
917 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000918
John McCall784f2112010-04-28 00:00:30 +0000919 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +0000920 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +0000921 MangledName, &getModule());
922 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedman654ad402009-11-09 05:07:37 +0000923 if (D.getDecl())
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000924 SetFunctionAttributes(D, F, IsIncompleteFunction);
John McCallf85e1932011-06-15 23:02:42 +0000925 if (ExtraAttrs != llvm::Attribute::None)
926 F->addFnAttr(ExtraAttrs);
Eli Friedman654ad402009-11-09 05:07:37 +0000927
Chris Lattner67b00522009-03-21 09:44:56 +0000928 // This is the first use or definition of a mangled name. If there is a
929 // deferred decl with this name, remember that we need to emit it at the end
930 // of the file.
John McCallf746aa62010-03-19 23:29:14 +0000931 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000932 if (DDI != DeferredDecls.end()) {
933 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
934 // list, and remove it from DeferredDecls (since we don't need it anymore).
935 DeferredDeclsToEmit.push_back(DDI->second);
936 DeferredDecls.erase(DDI);
John McCallbfdcdc82010-12-15 04:00:32 +0000937
938 // Otherwise, there are cases we have to worry about where we're
939 // using a declaration for which we must emit a definition but where
940 // we might not find a top-level definition:
941 // - member functions defined inline in their classes
942 // - friend functions defined inline in some class
943 // - special member functions with implicit definitions
944 // If we ever change our AST traversal to walk into class methods,
945 // this will be unnecessary.
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000946 //
947 // We also don't emit a definition for a function if it's going to be an entry
948 // in a vtable, unless it's already marked as used.
Rafael Espindola01de7a42011-02-03 06:30:58 +0000949 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
John McCallbfdcdc82010-12-15 04:00:32 +0000950 // Look for a declaration that's lexically in a record.
951 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
952 do {
953 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000954 if (FD->isImplicit() && !ForVTable) {
John McCallbfdcdc82010-12-15 04:00:32 +0000955 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
Douglas Gregora29bf412011-02-09 02:03:05 +0000956 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +0000957 break;
Sean Hunt10620eb2011-05-06 20:44:56 +0000958 } else if (FD->doesThisDeclarationHaveABody()) {
Douglas Gregora29bf412011-02-09 02:03:05 +0000959 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +0000960 break;
961 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000962 }
John McCallbfdcdc82010-12-15 04:00:32 +0000963 FD = FD->getPreviousDeclaration();
964 } while (FD);
Chris Lattner67b00522009-03-21 09:44:56 +0000965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
John McCall784f2112010-04-28 00:00:30 +0000967 // Make sure the result is of the requested type.
968 if (!IsIncompleteFunction) {
969 assert(F->getType()->getElementType() == Ty);
970 return F;
971 }
972
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000973 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCall784f2112010-04-28 00:00:30 +0000974 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000975}
976
Chris Lattner74391b42009-03-22 21:03:39 +0000977/// GetAddrOfFunction - Return the address of the given function. If Ty is
978/// non-null, then this function will use the specified type if it has to
979/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000980llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000981 llvm::Type *Ty,
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000982 bool ForVTable) {
Chris Lattner74391b42009-03-22 21:03:39 +0000983 // If there was no specific requested type, just convert it now.
984 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000985 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000986
Chris Lattner5f9e2722011-07-23 10:55:15 +0000987 StringRef MangledName = getMangledName(GD);
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000988 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
Chris Lattner74391b42009-03-22 21:03:39 +0000989}
Eli Friedman77ba7082008-05-30 19:50:47 +0000990
Chris Lattner74391b42009-03-22 21:03:39 +0000991/// CreateRuntimeFunction - Create a new runtime function with the specified
992/// type and name.
993llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +0000994CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000995 StringRef Name,
John McCallf85e1932011-06-15 23:02:42 +0000996 llvm::Attributes ExtraAttrs) {
997 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
998 ExtraAttrs);
Chris Lattner74391b42009-03-22 21:03:39 +0000999}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001000
Douglas Gregorda550742011-05-07 22:06:45 +00001001static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D,
1002 bool ConstantInit) {
John McCall88786862010-02-08 21:46:50 +00001003 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +00001004 return false;
Douglas Gregorda550742011-05-07 22:06:45 +00001005
1006 if (Context.getLangOptions().CPlusPlus) {
1007 if (const RecordType *Record
1008 = Context.getBaseElementType(D->getType())->getAs<RecordType>())
Douglas Gregor2bb11012011-05-13 01:05:07 +00001009 return ConstantInit &&
1010 cast<CXXRecordDecl>(Record->getDecl())->isPOD() &&
1011 !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields();
Eli Friedman20e098b2009-12-11 21:23:03 +00001012 }
Douglas Gregorda550742011-05-07 22:06:45 +00001013
Eli Friedman20e098b2009-12-11 21:23:03 +00001014 return true;
1015}
1016
Chris Lattner74391b42009-03-22 21:03:39 +00001017/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1018/// create and return an llvm GlobalVariable with the specified type. If there
1019/// is something in the module with the specified name, return it potentially
1020/// bitcasted to the right type.
1021///
1022/// If D is non-null, it specifies a decl that correspond to this. This is used
1023/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001024llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001025CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001026 llvm::PointerType *Ty,
Rafael Espindolac532b502011-01-18 21:07:57 +00001027 const VarDecl *D,
1028 bool UnnamedAddr) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +00001029 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001030 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +00001031 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001032 if (WeakRefReferences.count(Entry)) {
1033 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001034 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001035
1036 WeakRefReferences.erase(Entry);
1037 }
1038
Rafael Espindolac532b502011-01-18 21:07:57 +00001039 if (UnnamedAddr)
1040 Entry->setUnnamedAddr(true);
1041
Chris Lattner74391b42009-03-22 21:03:39 +00001042 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +00001043 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Chris Lattner99b53612009-03-21 08:03:33 +00001045 // Make sure the result is of the correct type.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001046 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +00001047 }
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Chris Lattner67b00522009-03-21 09:44:56 +00001049 // This is the first use or definition of a mangled name. If there is a
1050 // deferred decl with this name, remember that we need to emit it at the end
1051 // of the file.
John McCallf746aa62010-03-19 23:29:14 +00001052 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001053 if (DDI != DeferredDecls.end()) {
1054 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1055 // list, and remove it from DeferredDecls (since we don't need it anymore).
1056 DeferredDeclsToEmit.push_back(DDI->second);
1057 DeferredDecls.erase(DDI);
1058 }
Mike Stump1eb44332009-09-09 15:08:12 +00001059
1060 llvm::GlobalVariable *GV =
1061 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +00001062 llvm::GlobalValue::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001063 0, MangledName, 0,
Eli Friedman56ebe502009-04-19 21:05:03 +00001064 false, Ty->getAddressSpace());
Chris Lattner99b53612009-03-21 08:03:33 +00001065
1066 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +00001067 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001068 // FIXME: This code is overly simple and should be merged with other global
1069 // handling.
Douglas Gregorda550742011-05-07 22:06:45 +00001070 GV->setConstant(DeclIsConstantGlobal(Context, D, false));
Chris Lattner99b53612009-03-21 08:03:33 +00001071
John McCall110e8e52010-10-29 22:22:43 +00001072 // Set linkage and visibility in case we never see a definition.
John McCallaf146032010-10-30 11:50:40 +00001073 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1074 if (LV.linkage() != ExternalLinkage) {
John McCall15e310a2011-02-19 02:53:41 +00001075 // Don't set internal linkage on declarations.
John McCall110e8e52010-10-29 22:22:43 +00001076 } else {
1077 if (D->hasAttr<DLLImportAttr>())
1078 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001079 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
John McCall110e8e52010-10-29 22:22:43 +00001080 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner99b53612009-03-21 08:03:33 +00001081
John McCallaf146032010-10-30 11:50:40 +00001082 // Set visibility on a declaration only if it's explicit.
1083 if (LV.visibilityExplicit())
1084 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall110e8e52010-10-29 22:22:43 +00001085 }
Eli Friedman56ebe502009-04-19 21:05:03 +00001086
1087 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattner74391b42009-03-22 21:03:39 +00001088 }
Mike Stump1eb44332009-09-09 15:08:12 +00001089
John McCallf746aa62010-03-19 23:29:14 +00001090 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001091}
1092
Chris Lattner74391b42009-03-22 21:03:39 +00001093
Anders Carlsson3bd62022011-01-29 18:20:20 +00001094llvm::GlobalVariable *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001095CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001096 llvm::Type *Ty,
Anders Carlsson3bd62022011-01-29 18:20:20 +00001097 llvm::GlobalValue::LinkageTypes Linkage) {
1098 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1099 llvm::GlobalVariable *OldGV = 0;
1100
1101
1102 if (GV) {
1103 // Check if the variable has the right type.
1104 if (GV->getType()->getElementType() == Ty)
1105 return GV;
1106
1107 // Because C++ name mangling, the only way we can end up with an already
1108 // existing global with the same name is if it has been declared extern "C".
Anders Carlsson96eaf292011-01-29 18:25:07 +00001109 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlsson3bd62022011-01-29 18:20:20 +00001110 OldGV = GV;
1111 }
1112
1113 // Create a new variable.
1114 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1115 Linkage, 0, Name);
1116
1117 if (OldGV) {
1118 // Replace occurrences of the old variable if needed.
1119 GV->takeName(OldGV);
1120
1121 if (!OldGV->use_empty()) {
1122 llvm::Constant *NewPtrForOldDecl =
1123 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1124 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1125 }
1126
1127 OldGV->eraseFromParent();
1128 }
1129
1130 return GV;
1131}
1132
Chris Lattner74391b42009-03-22 21:03:39 +00001133/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1134/// given global variable. If Ty is non-null and if the global doesn't exist,
1135/// then it will be greated with the specified type instead of whatever the
1136/// normal requested type would be.
1137llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001138 llvm::Type *Ty) {
Chris Lattner74391b42009-03-22 21:03:39 +00001139 assert(D->hasGlobalStorage() && "Not a global variable");
1140 QualType ASTTy = D->getType();
1141 if (Ty == 0)
1142 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Chris Lattner2acc6e32011-07-18 04:24:23 +00001144 llvm::PointerType *PTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001145 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCallf746aa62010-03-19 23:29:14 +00001146
Chris Lattner5f9e2722011-07-23 10:55:15 +00001147 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001148 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001149}
1150
1151/// CreateRuntimeVariable - Create a new runtime global variable with the
1152/// specified type and name.
1153llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001154CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001155 StringRef Name) {
John McCall1de4d4e2011-04-07 08:22:57 +00001156 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolac532b502011-01-18 21:07:57 +00001157 true);
Chris Lattner74391b42009-03-22 21:03:39 +00001158}
1159
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001160void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1161 assert(!D->getInit() && "Cannot emit definite definitions here!");
1162
Douglas Gregor7520bd12009-04-21 19:28:58 +00001163 if (MayDeferGeneration(D)) {
1164 // If we have not seen a reference to this variable yet, place it
1165 // into the deferred declarations table to be emitted if needed
1166 // later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001167 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001168 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001169 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001170 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001171 }
1172 }
1173
1174 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001175 EmitGlobalVarDefinition(D);
1176}
1177
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001178void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1179 if (DefinitionRequired)
1180 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1181}
1182
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001183llvm::GlobalVariable::LinkageTypes
Anders Carlsson046c2942010-04-17 20:15:18 +00001184CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Eli Friedmancb5d2d02011-06-10 21:53:06 +00001185 if (RD->getLinkage() != ExternalLinkage)
Douglas Gregordffb8012010-01-06 22:00:56 +00001186 return llvm::GlobalVariable::InternalLinkage;
1187
1188 if (const CXXMethodDecl *KeyFunction
1189 = RD->getASTContext().getKeyFunction(RD)) {
1190 // If this class has a key function, use that to determine the linkage of
1191 // the vtable.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001192 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001193 if (KeyFunction->hasBody(Def))
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001194 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregordffb8012010-01-06 22:00:56 +00001195
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001196 switch (KeyFunction->getTemplateSpecializationKind()) {
1197 case TSK_Undeclared:
1198 case TSK_ExplicitSpecialization:
Anders Carlsson6d7f8472011-01-30 20:45:54 +00001199 // When compiling with optimizations turned on, we emit all vtables,
1200 // even if the key function is not defined in the current translation
1201 // unit. If this is the case, use available_externally linkage.
1202 if (!Def && CodeGenOpts.OptimizationLevel)
1203 return llvm::GlobalVariable::AvailableExternallyLinkage;
1204
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001205 if (KeyFunction->isInlined())
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001206 return !Context.getLangOptions().AppleKext ?
1207 llvm::GlobalVariable::LinkOnceODRLinkage :
1208 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001209
1210 return llvm::GlobalVariable::ExternalLinkage;
1211
1212 case TSK_ImplicitInstantiation:
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001213 return !Context.getLangOptions().AppleKext ?
1214 llvm::GlobalVariable::LinkOnceODRLinkage :
1215 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001216
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001217 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001218 return !Context.getLangOptions().AppleKext ?
1219 llvm::GlobalVariable::WeakODRLinkage :
1220 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001221
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001222 case TSK_ExplicitInstantiationDeclaration:
1223 // FIXME: Use available_externally linkage. However, this currently
1224 // breaks LLVM's build due to undefined symbols.
1225 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001226 return !Context.getLangOptions().AppleKext ?
1227 llvm::GlobalVariable::LinkOnceODRLinkage :
1228 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001229 }
Douglas Gregordffb8012010-01-06 22:00:56 +00001230 }
1231
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001232 if (Context.getLangOptions().AppleKext)
1233 return llvm::Function::InternalLinkage;
1234
Douglas Gregordffb8012010-01-06 22:00:56 +00001235 switch (RD->getTemplateSpecializationKind()) {
1236 case TSK_Undeclared:
1237 case TSK_ExplicitSpecialization:
1238 case TSK_ImplicitInstantiation:
Douglas Gregordffb8012010-01-06 22:00:56 +00001239 // FIXME: Use available_externally linkage. However, this currently
1240 // breaks LLVM's build due to undefined symbols.
1241 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001242 case TSK_ExplicitInstantiationDeclaration:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001243 return llvm::GlobalVariable::LinkOnceODRLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001244
1245 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001246 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001247 }
1248
1249 // Silence GCC warning.
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001250 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001251}
1252
Chris Lattner2acc6e32011-07-18 04:24:23 +00001253CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck06f486e2011-01-18 02:01:14 +00001254 return Context.toCharUnitsFromBits(
1255 TheTargetData.getTypeStoreSizeInBits(Ty));
Ken Dyck687cc4a2010-01-26 13:48:07 +00001256}
1257
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001258void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +00001259 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +00001260 QualType ASTTy = D->getType();
Eli Friedman6c6bda32010-01-08 00:50:11 +00001261 bool NonConstInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Sebastian Redl31310a22010-02-01 20:16:42 +00001263 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlsson3bb92692010-01-26 17:43:42 +00001264
1265 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001266 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001267 // implicitly initialized with { 0 }.
1268 //
1269 // Note that tentative definitions are only emitted at the end of
1270 // a translation unit, so they should never have incomplete
1271 // type. In addition, EmitTentativeDefinition makes sure that we
1272 // never attempt to emit a tentative definition if a real one
1273 // exists. A use may still exists, however, so we still may need
1274 // to do a RAUW.
1275 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00001276 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00001277 } else {
Douglas Gregorc446d182010-05-05 20:15:55 +00001278 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman6e656f42009-02-20 01:18:21 +00001279 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00001280 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00001281 if (D->getType()->isReferenceType())
1282 T = D->getType();
1283
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001284 if (getLangOptions().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001285 Init = EmitNullConstant(T);
Eli Friedman6c6bda32010-01-08 00:50:11 +00001286 NonConstInit = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001287 } else {
1288 ErrorUnsupported(D, "static initializer");
1289 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1290 }
John McCallbf40cb52010-07-15 23:40:35 +00001291 } else {
1292 // We don't need an initializer, so remove the entry for the delayed
1293 // initializer position (just in case this entry was delayed).
1294 if (getLangOptions().CPlusPlus)
1295 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00001296 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001297 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001298
Chris Lattner2acc6e32011-07-18 04:24:23 +00001299 llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00001300 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Chris Lattner570585c2009-03-21 09:16:30 +00001302 // Strip off a bitcast if we got one back.
1303 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001304 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1305 // all zero index gep.
1306 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00001307 Entry = CE->getOperand(0);
1308 }
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Chris Lattner570585c2009-03-21 09:16:30 +00001310 // Entry is now either a Function or GlobalVariable.
1311 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Chris Lattner570585c2009-03-21 09:16:30 +00001313 // We have a definition after a declaration with the wrong type.
1314 // We must make a new GlobalVariable* and update everything that used OldGV
1315 // (a declaration or tentative definition) with the new GlobalVariable*
1316 // (which will be a definition).
1317 //
1318 // This happens if there is a prototype for a global (e.g.
1319 // "extern int x[];") and then a definition of a different type (e.g.
1320 // "int x[10];"). This also happens when an initializer has a different type
1321 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +00001322 if (GV == 0 ||
1323 GV->getType()->getElementType() != InitType ||
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001324 GV->getType()->getAddressSpace() !=
1325 getContext().getTargetAddressSpace(ASTTy)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001326
John McCallf746aa62010-03-19 23:29:14 +00001327 // Move the old entry aside so that we'll create a new one.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001328 Entry->setName(StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00001329
Chris Lattner570585c2009-03-21 09:16:30 +00001330 // Make a new global with the correct type, this is now guaranteed to work.
1331 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00001332
Eli Friedman77ba7082008-05-30 19:50:47 +00001333 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00001334 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001335 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00001336 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00001337
1338 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00001339 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00001340 }
Devang Patel8e53e722007-10-26 16:31:40 +00001341
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001342 if (D->hasAttr<AnnotateAttr>())
1343 AddGlobalAnnotations(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001344
Chris Lattner88a69ad2007-07-13 05:13:43 +00001345 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001346
1347 // If it is safe to mark the global 'constant', do so now.
1348 GV->setConstant(false);
Douglas Gregorda550742011-05-07 22:06:45 +00001349 if (!NonConstInit && DeclIsConstantGlobal(Context, D, true))
Chris Lattnere78b86f2009-08-05 05:20:29 +00001350 GV->setConstant(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Ken Dyck8b752f12010-01-27 17:10:57 +00001352 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001353
Chris Lattner88a69ad2007-07-13 05:13:43 +00001354 // Set the llvm linkage type as appropriate.
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001355 llvm::GlobalValue::LinkageTypes Linkage =
1356 GetLLVMLinkageVarDefinition(D, GV);
1357 GV->setLinkage(Linkage);
1358 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00001359 // common vars aren't constant even if declared const.
1360 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00001361
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001362 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00001363
John McCall3030eb82010-11-06 09:44:32 +00001364 // Emit the initializer function if necessary.
1365 if (NonConstInit)
1366 EmitCXXGlobalVarDeclInitFunc(D, GV);
1367
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001368 // Emit global variable debug information.
Devang Patelaa112892011-03-07 18:45:56 +00001369 if (CGDebugInfo *DI = getModuleDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +00001370 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001371 DI->EmitGlobalVariable(GV, D);
1372 }
Chris Lattner88a69ad2007-07-13 05:13:43 +00001373}
Reid Spencer5f016e22007-07-11 17:01:13 +00001374
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001375llvm::GlobalValue::LinkageTypes
1376CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1377 llvm::GlobalVariable *GV) {
1378 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1379 if (Linkage == GVA_Internal)
1380 return llvm::Function::InternalLinkage;
1381 else if (D->hasAttr<DLLImportAttr>())
1382 return llvm::Function::DLLImportLinkage;
1383 else if (D->hasAttr<DLLExportAttr>())
1384 return llvm::Function::DLLExportLinkage;
1385 else if (D->hasAttr<WeakAttr>()) {
1386 if (GV->isConstant())
1387 return llvm::GlobalVariable::WeakODRLinkage;
1388 else
1389 return llvm::GlobalVariable::WeakAnyLinkage;
1390 } else if (Linkage == GVA_TemplateInstantiation ||
1391 Linkage == GVA_ExplicitTemplateInstantiation)
John McCall99ace162011-04-12 01:46:54 +00001392 return llvm::GlobalVariable::WeakODRLinkage;
Eric Christophera6cf1e72010-12-02 02:45:55 +00001393 else if (!getLangOptions().CPlusPlus &&
1394 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1395 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001396 !D->hasExternalStorage() && !D->getInit() &&
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00001397 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1398 !D->getAttr<WeakImportAttr>()) {
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001399 // Thread local vars aren't considered common linkage.
1400 return llvm::GlobalVariable::CommonLinkage;
1401 }
1402 return llvm::GlobalVariable::ExternalLinkage;
1403}
1404
Chris Lattnerbdb01322009-05-05 06:16:31 +00001405/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1406/// implement a function with no prototype, e.g. "int foo() {}". If there are
1407/// existing call uses of the old function in the module, this adjusts them to
1408/// call the new function directly.
1409///
1410/// This is not just a cleanup: the always_inline pass requires direct calls to
1411/// functions to be able to inline them. If there is a bitcast in the way, it
1412/// won't inline them. Instcombine normally deletes these calls, but it isn't
1413/// run at -O0.
1414static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1415 llvm::Function *NewFn) {
1416 // If we're redefining a global as a function, don't transform it.
1417 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1418 if (OldFn == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Chris Lattner2acc6e32011-07-18 04:24:23 +00001420 llvm::Type *NewRetTy = NewFn->getReturnType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001421 SmallVector<llvm::Value*, 4> ArgList;
Chris Lattnerbdb01322009-05-05 06:16:31 +00001422
1423 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001424 UI != E; ) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001425 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001426 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1427 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif8670cd32010-07-28 09:19:33 +00001428 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
Gabor Greif35db3b92010-04-10 03:45:50 +00001429 llvm::CallSite CS(CI);
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001430 if (!CI || !CS.isCallee(I)) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Chris Lattnerbdb01322009-05-05 06:16:31 +00001432 // If the return types don't match exactly, and if the call isn't dead, then
1433 // we can't transform this call.
1434 if (CI->getType() != NewRetTy && !CI->use_empty())
1435 continue;
1436
John McCall40f9c302011-08-03 00:43:55 +00001437 // Get the attribute list.
1438 llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
1439 llvm::AttrListPtr AttrList = CI->getAttributes();
1440
1441 // Get any return attributes.
1442 llvm::Attributes RAttrs = AttrList.getRetAttributes();
1443
1444 // Add the return attributes.
1445 if (RAttrs)
1446 AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
1447
Chris Lattnerbdb01322009-05-05 06:16:31 +00001448 // If the function was passed too few arguments, don't transform. If extra
1449 // arguments were passed, we silently drop them. If any of the types
1450 // mismatch, we don't transform.
1451 unsigned ArgNo = 0;
1452 bool DontTransform = false;
1453 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1454 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greif35db3b92010-04-10 03:45:50 +00001455 if (CS.arg_size() == ArgNo ||
1456 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001457 DontTransform = true;
1458 break;
1459 }
John McCall40f9c302011-08-03 00:43:55 +00001460
1461 // Add any parameter attributes.
1462 if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
1463 AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
Chris Lattnerbdb01322009-05-05 06:16:31 +00001464 }
1465 if (DontTransform)
1466 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001467
John McCall40f9c302011-08-03 00:43:55 +00001468 if (llvm::Attributes FnAttrs = AttrList.getFnAttributes())
1469 AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
1470
Chris Lattnerbdb01322009-05-05 06:16:31 +00001471 // Okay, we can transform this. Create the new call instruction and copy
1472 // over the required information.
Gabor Greif6ba728d2010-04-10 02:56:12 +00001473 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001474 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001475 ArgList.clear();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001476 if (!NewCall->getType()->isVoidTy())
Chris Lattnerbdb01322009-05-05 06:16:31 +00001477 NewCall->takeName(CI);
John McCall40f9c302011-08-03 00:43:55 +00001478 NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(),
1479 AttrVec.end()));
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001480 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001481
1482 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner00549fc2009-10-14 05:49:21 +00001483 if (!CI->use_empty())
1484 CI->replaceAllUsesWith(NewCall);
Devang Patel3b122bc2009-10-13 17:02:04 +00001485
Chris Lattnerc6034632010-04-01 06:31:43 +00001486 // Copy debug location attached to CI.
1487 if (!CI->getDebugLoc().isUnknown())
1488 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001489 CI->eraseFromParent();
1490 }
1491}
1492
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001493
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001494void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001495 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalld26bc762011-03-09 04:27:21 +00001496
John McCall1f6f9612011-03-09 08:12:35 +00001497 // Compute the function info and LLVM type.
John McCalld26bc762011-03-09 04:27:21 +00001498 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
John McCall1f6f9612011-03-09 08:12:35 +00001499 bool variadic = false;
1500 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
1501 variadic = fpt->isVariadic();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001502 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic);
John McCalld26bc762011-03-09 04:27:21 +00001503
Chris Lattner9fa959d2009-05-12 20:58:15 +00001504 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001505 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Chris Lattner0558e792009-03-21 09:25:43 +00001507 // Strip off a bitcast if we got one back.
1508 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1509 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1510 Entry = CE->getOperand(0);
1511 }
Mike Stump1eb44332009-09-09 15:08:12 +00001512
1513
Chris Lattner0558e792009-03-21 09:25:43 +00001514 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001515 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Daniel Dunbar42745812009-03-09 23:53:08 +00001517 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001518 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +00001519 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00001520
Chris Lattner62b33ea2009-03-21 08:38:50 +00001521 // F is the Function* for the one with the wrong type, we must make a new
1522 // Function* and update everything that used F (a declaration) with the new
1523 // Function* (which will be a definition).
1524 //
1525 // This happens if there is a prototype for a function
1526 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00001527 // (e.g. "int f(int x)"). Move the old function aside so that it
1528 // doesn't interfere with GetAddrOfFunction.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001529 OldFn->setName(StringRef());
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001530 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Chris Lattnerbdb01322009-05-05 06:16:31 +00001532 // If this is an implementation of a function without a prototype, try to
1533 // replace any existing uses of the function (which may be calls) with uses
1534 // of the new function
Chris Lattner9fa959d2009-05-12 20:58:15 +00001535 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001536 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001537 OldFn->removeDeadConstantUsers();
1538 }
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Chris Lattner62b33ea2009-03-21 08:38:50 +00001540 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001541 if (!Entry->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001542 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001543 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001544 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1545 }
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Chris Lattner62b33ea2009-03-21 08:38:50 +00001547 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001548 OldFn->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Chris Lattner0558e792009-03-21 09:25:43 +00001550 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552
John McCall112c9672010-11-02 21:04:24 +00001553 // We need to set linkage and visibility on the function before
1554 // generating code for it because various parts of IR generation
1555 // want to propagate this information down (e.g. to local static
1556 // declarations).
Chris Lattner0558e792009-03-21 09:25:43 +00001557 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall8b242332010-05-25 04:30:21 +00001558 setFunctionLinkage(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001559
John McCall112c9672010-11-02 21:04:24 +00001560 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlsson0ffeaad2011-01-29 19:39:23 +00001561 setGlobalVisibility(Fn, D);
John McCall112c9672010-11-02 21:04:24 +00001562
John McCalld26bc762011-03-09 04:27:21 +00001563 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00001564
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001565 SetFunctionDefinitionAttributes(D, Fn);
1566 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001568 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001569 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001570 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001571 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001572 if (D->hasAttr<AnnotateAttr>())
1573 AddGlobalAnnotations(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001574}
1575
John McCallf746aa62010-03-19 23:29:14 +00001576void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1577 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001578 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00001579 assert(AA && "Not an alias?");
1580
Chris Lattner5f9e2722011-07-23 10:55:15 +00001581 StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
John McCallf746aa62010-03-19 23:29:14 +00001583 // If there is a definition in the module, then it wins over the alias.
1584 // This is dubious, but allow it to be safe. Just ignore the alias.
1585 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1586 if (Entry && !Entry->isDeclaration())
1587 return;
1588
Chris Lattner2acc6e32011-07-18 04:24:23 +00001589 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00001590
1591 // Create a reference to the named value. This ensures that it is emitted
1592 // if a deferred decl.
1593 llvm::Constant *Aliasee;
1594 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001595 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1596 /*ForVTable=*/false);
Chris Lattnerbd532712009-03-22 21:47:11 +00001597 else
John McCallf746aa62010-03-19 23:29:14 +00001598 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson96e0fc72009-07-29 22:16:19 +00001599 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattnerbd532712009-03-22 21:47:11 +00001600
1601 // Create the new alias itself, but don't set a name yet.
Mike Stump1eb44332009-09-09 15:08:12 +00001602 llvm::GlobalValue *GA =
Chris Lattnerbd532712009-03-22 21:47:11 +00001603 new llvm::GlobalAlias(Aliasee->getType(),
1604 llvm::Function::ExternalLinkage,
1605 "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Chris Lattnerbd532712009-03-22 21:47:11 +00001607 if (Entry) {
John McCallf746aa62010-03-19 23:29:14 +00001608 assert(Entry->isDeclaration());
1609
Chris Lattnerbd532712009-03-22 21:47:11 +00001610 // If there is a declaration in the module, then we had an extern followed
1611 // by the alias, as in:
1612 // extern int test6();
1613 // ...
1614 // int test6() __attribute__((alias("test7")));
1615 //
1616 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00001617 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Owen Anderson3c4972d2009-07-29 18:54:39 +00001619 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00001620 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00001621 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00001622 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00001623 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00001624 }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001626 // Set attributes which are particular to an alias; this is a
1627 // specialization of the attributes which may be set on a global
1628 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001629 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001630 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1631 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001632 if (FD->hasBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001633 GA->setLinkage(llvm::Function::DLLExportLinkage);
1634 } else {
1635 GA->setLinkage(llvm::Function::DLLExportLinkage);
1636 }
Mike Stump1eb44332009-09-09 15:08:12 +00001637 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindola11e8ce72010-02-23 22:00:30 +00001638 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001639 D->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001640 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1641 }
1642
1643 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00001644}
1645
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00001646llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00001647 ArrayRef<llvm::Type*> Tys) {
Jay Foaddf983a82011-07-12 14:06:48 +00001648 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00001649 Tys);
Chris Lattner7acda7c2007-12-18 00:25:38 +00001650}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001651
Daniel Dunbar1d552912009-07-23 22:52:48 +00001652static llvm::StringMapEntry<llvm::Constant*> &
1653GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1654 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001655 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00001656 bool &IsUTF16,
1657 unsigned &StringLength) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001658 StringRef String = Literal->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001659 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001660
Daniel Dunbarf015b032009-09-22 10:03:52 +00001661 // Check for simple case.
1662 if (!Literal->containsNonAsciiOrNull()) {
1663 StringLength = NumBytes;
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001664 return Map.GetOrCreateValue(String);
Daniel Dunbarf015b032009-09-22 10:03:52 +00001665 }
1666
Daniel Dunbar1d552912009-07-23 22:52:48 +00001667 // Otherwise, convert the UTF8 literals into a byte string.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001668 SmallVector<UTF16, 128> ToBuf(NumBytes);
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001669 const UTF8 *FromPtr = (UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001670 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00001672 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1673 &ToPtr, ToPtr + NumBytes,
1674 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00001675
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001676 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00001677 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001678
1679 // Render the UTF-16 string into a byte array and convert to the target byte
1680 // order.
1681 //
1682 // FIXME: This isn't something we should need to do here.
1683 llvm::SmallString<128> AsBytes;
1684 AsBytes.reserve(StringLength * 2);
1685 for (unsigned i = 0; i != StringLength; ++i) {
1686 unsigned short Val = ToBuf[i];
1687 if (TargetIsLSB) {
1688 AsBytes.push_back(Val & 0xFF);
1689 AsBytes.push_back(Val >> 8);
1690 } else {
1691 AsBytes.push_back(Val >> 8);
1692 AsBytes.push_back(Val & 0xFF);
1693 }
1694 }
Daniel Dunbar434da482009-08-03 21:47:08 +00001695 // Append one extra null character, the second is automatically added by our
1696 // caller.
1697 AsBytes.push_back(0);
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001698
Daniel Dunbar1d552912009-07-23 22:52:48 +00001699 IsUTF16 = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001700 return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar1d552912009-07-23 22:52:48 +00001701}
1702
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001703static llvm::StringMapEntry<llvm::Constant*> &
1704GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1705 const StringLiteral *Literal,
1706 unsigned &StringLength)
1707{
Chris Lattner5f9e2722011-07-23 10:55:15 +00001708 StringRef String = Literal->getString();
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001709 StringLength = String.size();
1710 return Map.GetOrCreateValue(String);
1711}
1712
Daniel Dunbar1d552912009-07-23 22:52:48 +00001713llvm::Constant *
1714CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1715 unsigned StringLength = 0;
1716 bool isUTF16 = false;
1717 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00001718 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001719 getTargetData().isLittleEndian(),
1720 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Daniel Dunbar1d552912009-07-23 22:52:48 +00001722 if (llvm::Constant *C = Entry.getValue())
1723 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Owen Anderson0032b272009-08-13 21:57:51 +00001725 llvm::Constant *Zero =
1726 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001727 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001729 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00001730 if (!CFConstantStringClassRef) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001731 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001732 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001733 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001734 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001735 // Decay array -> ptr
1736 CFConstantStringClassRef =
Jay Foada5c04342011-07-21 14:31:17 +00001737 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001738 }
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Anders Carlssone3daa762008-11-15 18:54:24 +00001740 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001741
Chris Lattner2acc6e32011-07-18 04:24:23 +00001742 llvm::StructType *STy =
Anders Carlssone3daa762008-11-15 18:54:24 +00001743 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1744
Anders Carlsson5add6832009-08-16 05:55:31 +00001745 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor44b43212008-12-11 16:49:14 +00001746
Anders Carlssonc9e20912007-08-21 00:21:21 +00001747 // Class pointer.
Anders Carlsson5add6832009-08-16 05:55:31 +00001748 Fields[0] = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Anders Carlssonc9e20912007-08-21 00:21:21 +00001750 // Flags.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001751 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001752 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00001753 llvm::ConstantInt::get(Ty, 0x07C8);
1754
Anders Carlssonc9e20912007-08-21 00:21:21 +00001755 // String pointer.
Owen Anderson0032b272009-08-13 21:57:51 +00001756 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001757
Chris Lattner95b851e2009-07-16 05:03:48 +00001758 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001759 bool isConstant;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001760 if (isUTF16) {
Chris Lattner278b9f02009-10-14 05:55:45 +00001761 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner95b851e2009-07-16 05:03:48 +00001762 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001763 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1764 // does make plain ascii ones writable.
Daniel Dunbara9668e02009-04-03 00:57:44 +00001765 isConstant = true;
Chris Lattner278b9f02009-10-14 05:55:45 +00001766 } else {
Rafael Espindola584acf22011-03-14 17:55:00 +00001767 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1768 // when using private linkage. It is not clear if this is a bug in ld
1769 // or a reasonable new restriction.
Rafael Espindoladc0f1372011-03-14 21:08:19 +00001770 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001771 isConstant = !Features.WritableStrings;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001772 }
Chris Lattner278b9f02009-10-14 05:55:45 +00001773
Mike Stump1eb44332009-09-09 15:08:12 +00001774 llvm::GlobalVariable *GV =
Chris Lattner278b9f02009-10-14 05:55:45 +00001775 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1776 ".str");
Rafael Espindolab266a1f2011-01-17 16:31:00 +00001777 GV->setUnnamedAddr(true);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001778 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00001779 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1780 GV->setAlignment(Align.getQuantity());
Daniel Dunbarf7e903d2011-04-12 23:30:52 +00001781 } else {
1782 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1783 GV->setAlignment(Align.getQuantity());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001784 }
Jay Foada5c04342011-07-21 14:31:17 +00001785 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson5add6832009-08-16 05:55:31 +00001786
Anders Carlssonc9e20912007-08-21 00:21:21 +00001787 // String length.
1788 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00001789 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Anders Carlssonc9e20912007-08-21 00:21:21 +00001791 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00001792 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00001793 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1794 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00001795 "_unnamed_cfstring_");
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001796 if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001797 GV->setSection(Sect);
Daniel Dunbar1d552912009-07-23 22:52:48 +00001798 Entry.setValue(GV);
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Anders Carlsson0c678292007-11-01 00:41:52 +00001800 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001801}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001802
Douglas Gregor45c4ea72011-08-09 15:54:21 +00001803static RecordDecl *
1804CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
1805 DeclContext *DC, IdentifierInfo *Id) {
1806 SourceLocation Loc;
1807 if (Ctx.getLangOptions().CPlusPlus)
1808 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
1809 else
1810 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
1811}
1812
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001813llvm::Constant *
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001814CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001815 unsigned StringLength = 0;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001816 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001817 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001818
1819 if (llvm::Constant *C = Entry.getValue())
1820 return C;
1821
1822 llvm::Constant *Zero =
1823 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1824 llvm::Constant *Zeros[] = { Zero, Zero };
1825
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001826 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001827 if (!ConstantStringClassRef) {
1828 std::string StringClass(getLangOptions().ObjCConstantStringClass);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001829 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001830 llvm::Constant *GV;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00001831 if (Features.ObjCNonFragileABI) {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00001832 std::string str =
1833 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
1834 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00001835 GV = getObjCRuntime().GetClassGlobal(str);
1836 // Make sure the result is of the correct type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001837 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00001838 ConstantStringClassRef =
1839 llvm::ConstantExpr::getBitCast(GV, PTy);
1840 } else {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00001841 std::string str =
1842 StringClass.empty() ? "_NSConstantStringClassReference"
1843 : "_" + StringClass + "ClassReference";
Chris Lattner2acc6e32011-07-18 04:24:23 +00001844 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00001845 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00001846 // Decay array -> ptr
1847 ConstantStringClassRef =
Jay Foada5c04342011-07-21 14:31:17 +00001848 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001849 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001850 }
Douglas Gregor45c4ea72011-08-09 15:54:21 +00001851
1852 if (!NSConstantStringType) {
1853 // Construct the type for a constant NSString.
1854 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
1855 Context.getTranslationUnitDecl(),
1856 &Context.Idents.get("__builtin_NSString"));
1857 D->startDefinition();
1858
1859 QualType FieldTypes[3];
1860
1861 // const int *isa;
1862 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
1863 // const char *str;
1864 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
1865 // unsigned int length;
1866 FieldTypes[2] = Context.UnsignedIntTy;
1867
1868 // Create fields
1869 for (unsigned i = 0; i < 3; ++i) {
1870 FieldDecl *Field = FieldDecl::Create(Context, D,
1871 SourceLocation(),
1872 SourceLocation(), 0,
1873 FieldTypes[i], /*TInfo=*/0,
1874 /*BitWidth=*/0,
1875 /*Mutable=*/false,
1876 /*HasInit=*/false);
1877 Field->setAccess(AS_public);
1878 D->addDecl(Field);
1879 }
1880
1881 D->completeDefinition();
1882 QualType NSTy = Context.getTagDeclType(D);
1883 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1884 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001885
1886 std::vector<llvm::Constant*> Fields(3);
1887
1888 // Class pointer.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001889 Fields[0] = ConstantStringClassRef;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001890
1891 // String pointer.
1892 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1893
1894 llvm::GlobalValue::LinkageTypes Linkage;
1895 bool isConstant;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001896 Linkage = llvm::GlobalValue::PrivateLinkage;
1897 isConstant = !Features.WritableStrings;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001898
1899 llvm::GlobalVariable *GV =
1900 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1901 ".str");
Rafael Espindola803d3072011-01-17 22:11:21 +00001902 GV->setUnnamedAddr(true);
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001903 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1904 GV->setAlignment(Align.getQuantity());
Jay Foada5c04342011-07-21 14:31:17 +00001905 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001906
1907 // String length.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001908 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001909 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1910
1911 // The struct.
Douglas Gregor45c4ea72011-08-09 15:54:21 +00001912 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001913 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1914 llvm::GlobalVariable::PrivateLinkage, C,
1915 "_unnamed_nsstring_");
1916 // FIXME. Fix section.
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001917 if (const char *Sect =
1918 Features.ObjCNonFragileABI
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001919 ? getContext().getTargetInfo().getNSStringNonFragileABISection()
1920 : getContext().getTargetInfo().getNSStringSection())
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001921 GV->setSection(Sect);
1922 Entry.setValue(GV);
1923
1924 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001925}
1926
Douglas Gregor0815b572011-08-09 17:23:49 +00001927QualType CodeGenModule::getObjCFastEnumerationStateType() {
1928 if (ObjCFastEnumerationStateType.isNull()) {
1929 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
1930 Context.getTranslationUnitDecl(),
1931 &Context.Idents.get("__objcFastEnumerationState"));
1932 D->startDefinition();
1933
1934 QualType FieldTypes[] = {
1935 Context.UnsignedLongTy,
1936 Context.getPointerType(Context.getObjCIdType()),
1937 Context.getPointerType(Context.UnsignedLongTy),
1938 Context.getConstantArrayType(Context.UnsignedLongTy,
1939 llvm::APInt(32, 5), ArrayType::Normal, 0)
1940 };
1941
1942 for (size_t i = 0; i < 4; ++i) {
1943 FieldDecl *Field = FieldDecl::Create(Context,
1944 D,
1945 SourceLocation(),
1946 SourceLocation(), 0,
1947 FieldTypes[i], /*TInfo=*/0,
1948 /*BitWidth=*/0,
1949 /*Mutable=*/false,
1950 /*HasInit=*/false);
1951 Field->setAccess(AS_public);
1952 D->addDecl(Field);
1953 }
1954
1955 D->completeDefinition();
1956 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
1957 }
1958
1959 return ObjCFastEnumerationStateType;
1960}
1961
Daniel Dunbar61432932008-08-13 23:20:05 +00001962/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001963/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001964std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Ken Dyck3b8037a2011-01-29 17:53:12 +00001965 const ASTContext &Context = getContext();
Daniel Dunbar1e049762008-08-10 20:25:57 +00001966 const ConstantArrayType *CAT =
Ken Dyck3b8037a2011-01-29 17:53:12 +00001967 Context.getAsConstantArrayType(E->getType());
Daniel Dunbar1e049762008-08-10 20:25:57 +00001968 assert(CAT && "String isn't pointer or array!");
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001970 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001971 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Douglas Gregor5cee1192011-07-27 05:40:30 +00001973 switch (E->getKind()) {
1974 case StringLiteral::Ascii:
1975 case StringLiteral::UTF8:
1976 break;
1977 case StringLiteral::Wide:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001978 RealLen *= Context.getTargetInfo().getWCharWidth() / Context.getCharWidth();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001979 break;
1980 case StringLiteral::UTF16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001981 RealLen *= Context.getTargetInfo().getChar16Width() / Context.getCharWidth();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001982 break;
1983 case StringLiteral::UTF32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001984 RealLen *= Context.getTargetInfo().getChar32Width() / Context.getCharWidth();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001985 break;
1986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001988 std::string Str = E->getString().str();
Daniel Dunbar1e049762008-08-10 20:25:57 +00001989 Str.resize(RealLen, '\0');
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Daniel Dunbar1e049762008-08-10 20:25:57 +00001991 return Str;
1992}
1993
Daniel Dunbar61432932008-08-13 23:20:05 +00001994/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1995/// constant array for the given string literal.
1996llvm::Constant *
1997CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1998 // FIXME: This can be more efficient.
Eli Friedman7eb79c12009-11-16 05:55:46 +00001999 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
John McCalla5e19c62011-08-04 01:03:22 +00002000 CharUnits Align = getContext().getTypeAlignInChars(S->getType());
2001 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S),
2002 /* GlobalName */ 0,
2003 Align.getQuantity());
Douglas Gregor5cee1192011-07-27 05:40:30 +00002004 if (S->isWide() || S->isUTF16() || S->isUTF32()) {
Eli Friedman7eb79c12009-11-16 05:55:46 +00002005 llvm::Type *DestTy =
2006 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
2007 C = llvm::ConstantExpr::getBitCast(C, DestTy);
2008 }
2009 return C;
Daniel Dunbar61432932008-08-13 23:20:05 +00002010}
2011
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002012/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2013/// array for the given ObjCEncodeExpr node.
2014llvm::Constant *
2015CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2016 std::string Str;
2017 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00002018
2019 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002020}
2021
2022
Chris Lattnera7ad98f2008-02-11 00:02:17 +00002023/// GenerateWritableString -- Creates storage for a string literal.
John McCalla5e19c62011-08-04 01:03:22 +00002024static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002025 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00002026 CodeGenModule &CGM,
John McCalla5e19c62011-08-04 01:03:22 +00002027 const char *GlobalName,
2028 unsigned Alignment) {
Daniel Dunbar61432932008-08-13 23:20:05 +00002029 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson0032b272009-08-13 21:57:51 +00002030 llvm::Constant *C =
2031 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002033 // Create a global variable for this string
Rafael Espindola1257bc62011-01-10 22:34:03 +00002034 llvm::GlobalVariable *GV =
2035 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2036 llvm::GlobalValue::PrivateLinkage,
2037 C, GlobalName);
John McCalla5e19c62011-08-04 01:03:22 +00002038 GV->setAlignment(Alignment);
Rafael Espindola1257bc62011-01-10 22:34:03 +00002039 GV->setUnnamedAddr(true);
2040 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002041}
2042
Daniel Dunbar61432932008-08-13 23:20:05 +00002043/// GetAddrOfConstantString - Returns a pointer to a character array
2044/// containing the literal. This contents are exactly that of the
2045/// given string, i.e. it will not be null terminated automatically;
2046/// see GetAddrOfConstantCString. Note that whether the result is
2047/// actually a pointer to an LLVM constant depends on
2048/// Feature.WriteableStrings.
2049///
2050/// The result has pointer to array type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002051llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
John McCalla5e19c62011-08-04 01:03:22 +00002052 const char *GlobalName,
2053 unsigned Alignment) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002054 bool IsConstant = !Features.WritableStrings;
2055
2056 // Get the default prefix if a name wasn't specified.
2057 if (!GlobalName)
Chris Lattner95b851e2009-07-16 05:03:48 +00002058 GlobalName = ".str";
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002059
2060 // Don't share any string literals if strings aren't constant.
2061 if (!IsConstant)
John McCalla5e19c62011-08-04 01:03:22 +00002062 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
John McCalla5e19c62011-08-04 01:03:22 +00002064 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
Benjamin Kramer9de43422011-03-05 13:45:23 +00002065 ConstantStringMap.GetOrCreateValue(Str);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002066
John McCalla5e19c62011-08-04 01:03:22 +00002067 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2068 if (Alignment > GV->getAlignment()) {
2069 GV->setAlignment(Alignment);
2070 }
2071 return GV;
2072 }
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002073
2074 // Create a global variable for this.
John McCalla5e19c62011-08-04 01:03:22 +00002075 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, Alignment);
2076 Entry.setValue(GV);
2077 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002078}
Daniel Dunbar61432932008-08-13 23:20:05 +00002079
2080/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer9de43422011-03-05 13:45:23 +00002081/// array containing the literal and a terminating '\0'
Daniel Dunbar61432932008-08-13 23:20:05 +00002082/// character. The result has pointer to array type.
Benjamin Kramer9de43422011-03-05 13:45:23 +00002083llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
John McCalla5e19c62011-08-04 01:03:22 +00002084 const char *GlobalName,
2085 unsigned Alignment) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002086 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCalla5e19c62011-08-04 01:03:22 +00002087 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
Daniel Dunbar61432932008-08-13 23:20:05 +00002088}
Daniel Dunbar41071de2008-08-15 23:26:23 +00002089
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002090/// EmitObjCPropertyImplementations - Emit information for synthesized
2091/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00002092void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002093 ObjCImplementationDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00002094 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002095 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002096 ObjCPropertyImplDecl *PID = *i;
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002098 // Dynamic is just for type-checking.
2099 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2100 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2101
2102 // Determine which methods need to be implemented, some may have
2103 // been overridden. Note that ::isSynthesized is not the method
2104 // we want, that just indicates if the decl came from a
2105 // property. What we want to know is if the method is defined in
2106 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002107 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00002108 CodeGenFunction(*this).GenerateObjCGetter(
2109 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002110 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002111 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00002112 CodeGenFunction(*this).GenerateObjCSetter(
2113 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002114 }
2115 }
2116}
2117
John McCalle81ac692011-03-22 07:05:39 +00002118static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002119 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2120 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00002121 ivar; ivar = ivar->getNextIvar())
2122 if (ivar->getType().isDestructedType())
2123 return true;
2124
2125 return false;
2126}
2127
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002128/// EmitObjCIvarInitializations - Emit information for ivar initialization
2129/// for an implementation.
2130void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCalle81ac692011-03-22 07:05:39 +00002131 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2132 if (needsDestructMethod(D)) {
2133 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2134 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2135 ObjCMethodDecl *DTORMethod =
2136 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00002137 ArrayRef<SourceLocation>(),
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002138 cxxSelector, getContext().VoidTy, 0, D,
2139 /*isInstance=*/true, /*isVariadic=*/false,
2140 /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
2141 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCalle81ac692011-03-22 07:05:39 +00002142 D->addInstanceMethod(DTORMethod);
2143 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCallf85e1932011-06-15 23:02:42 +00002144 D->setHasCXXStructors(true);
John McCalle81ac692011-03-22 07:05:39 +00002145 }
2146
2147 // If the implementation doesn't have any ivar initializers, we don't need
2148 // a .cxx_construct.
David Chisnall827bbcc2011-03-17 14:19:08 +00002149 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002150 return;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002151
John McCalle81ac692011-03-22 07:05:39 +00002152 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2153 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002154 // The constructor returns 'self'.
2155 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2156 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00002157 D->getLocation(),
2158 ArrayRef<SourceLocation>(),
2159 cxxSelector,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002160 getContext().getObjCIdType(), 0,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002161 D, /*isInstance=*/true,
2162 /*isVariadic=*/false,
2163 /*isSynthesized=*/true,
2164 /*isImplicitlyDeclared=*/true,
2165 /*isDefined=*/false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002166 ObjCMethodDecl::Required);
2167 D->addInstanceMethod(CTORMethod);
2168 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCallf85e1932011-06-15 23:02:42 +00002169 D->setHasCXXStructors(true);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002170}
2171
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002172/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00002173void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002174 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00002175 I != E; ++I)
2176 EmitTopLevelDecl(*I);
2177}
2178
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002179// EmitLinkageSpec - Emit all declarations in a linkage spec.
2180void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00002181 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2182 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002183 ErrorUnsupported(LSD, "linkage spec");
2184 return;
2185 }
2186
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002187 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002188 I != E; ++I)
2189 EmitTopLevelDecl(*I);
2190}
2191
Daniel Dunbar41071de2008-08-15 23:26:23 +00002192/// EmitTopLevelDecl - Emit code for a single top level declaration.
2193void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2194 // If an error has occurred, stop code generation, but continue
2195 // parsing and semantic analysis (to ensure all warnings and errors
2196 // are emitted).
2197 if (Diags.hasErrorOccurred())
2198 return;
2199
Douglas Gregor16e8be22009-06-29 17:30:29 +00002200 // Ignore dependent declarations.
2201 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2202 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Daniel Dunbar41071de2008-08-15 23:26:23 +00002204 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00002205 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00002206 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002207 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00002208 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002209 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2210 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor16e8be22009-06-29 17:30:29 +00002211 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002213 EmitGlobal(cast<FunctionDecl>(D));
2214 break;
2215
Daniel Dunbar41071de2008-08-15 23:26:23 +00002216 case Decl::Var:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002217 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002218 break;
2219
John McCall26fbc722011-04-12 01:01:22 +00002220 // Indirect fields from global anonymous structs and unions can be
2221 // ignored; only the actual variable requires IR gen support.
2222 case Decl::IndirectField:
2223 break;
2224
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002225 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00002226 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00002227 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002228 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002229 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00002230 case Decl::UsingShadow:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002231 case Decl::Using:
Douglas Gregordd9967a2009-09-02 23:49:23 +00002232 case Decl::UsingDirective:
Douglas Gregor127102b2009-06-29 20:59:39 +00002233 case Decl::ClassTemplate:
2234 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002235 case Decl::TypeAliasTemplate:
Anders Carlsson018837b2009-09-23 19:19:16 +00002236 case Decl::NamespaceAlias:
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002237 case Decl::Block:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002238 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002239 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002240 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002241 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2242 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002243 return;
2244
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002245 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2246 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002247 case Decl::CXXDestructor:
Francois Pichet8387e2a2011-04-22 22:18:13 +00002248 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2249 return;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002250 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2251 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00002252
2253 case Decl::StaticAssert:
2254 // Nothing to do.
2255 break;
2256
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002257 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00002259 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002260 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002261 case Decl::ObjCForwardProtocol:
Chris Lattner285d0db2009-04-01 02:36:43 +00002262 case Decl::ObjCInterface:
Chris Lattner285d0db2009-04-01 02:36:43 +00002263 break;
Fariborz Jahanian000835d2010-08-23 18:51:39 +00002264
Chris Lattnerbaf101d2011-04-09 07:11:53 +00002265 case Decl::ObjCCategory: {
2266 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2267 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2268 Context.ResetObjCLayout(CD->getClassInterface());
2269 break;
2270 }
Chris Lattner285d0db2009-04-01 02:36:43 +00002271
Daniel Dunbar41071de2008-08-15 23:26:23 +00002272 case Decl::ObjCProtocol:
Peter Collingbournee9265232011-07-27 20:29:46 +00002273 ObjCRuntime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002274 break;
2275
2276 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002277 // Categories have properties but don't support synthesize so we
2278 // can ignore them here.
Peter Collingbournee9265232011-07-27 20:29:46 +00002279 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002280 break;
2281
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002282 case Decl::ObjCImplementation: {
2283 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
Fariborz Jahanian000835d2010-08-23 18:51:39 +00002284 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2285 Context.ResetObjCLayout(OMD->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002286 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002287 EmitObjCIvarInitializations(OMD);
Peter Collingbournee9265232011-07-27 20:29:46 +00002288 ObjCRuntime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00002289 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002290 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00002291 case Decl::ObjCMethod: {
2292 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2293 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002294 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00002295 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2296 break;
2297 }
Mike Stump1eb44332009-09-09 15:08:12 +00002298 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00002299 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002300 break;
2301
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002302 case Decl::LinkageSpec:
2303 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002304 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00002305
2306 case Decl::FileScopeAsm: {
2307 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002308 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Daniel Dunbar41071de2008-08-15 23:26:23 +00002310 const std::string &S = getModule().getModuleInlineAsm();
2311 if (S.empty())
2312 getModule().setModuleInlineAsm(AsmString);
Chris Lattner9f5bff02011-07-23 20:04:25 +00002313 else if (*--S.end() == '\n')
2314 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002315 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00002316 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002317 break;
2318 }
Mike Stump1eb44332009-09-09 15:08:12 +00002319
2320 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00002321 // Make sure we handled everything we should, every other kind is a
2322 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2323 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002324 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2325 }
2326}
John McCall744016d2010-07-06 23:57:41 +00002327
2328/// Turns the given pointer into a constant.
2329static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2330 const void *Ptr) {
2331 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002332 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall744016d2010-07-06 23:57:41 +00002333 return llvm::ConstantInt::get(i64, PtrInt);
2334}
2335
2336static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2337 llvm::NamedMDNode *&GlobalMetadata,
2338 GlobalDecl D,
2339 llvm::GlobalValue *Addr) {
2340 if (!GlobalMetadata)
2341 GlobalMetadata =
2342 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2343
2344 // TODO: should we report variant information for ctors/dtors?
2345 llvm::Value *Ops[] = {
2346 Addr,
2347 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2348 };
Jay Foad6f141652011-04-21 19:59:12 +00002349 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall744016d2010-07-06 23:57:41 +00002350}
2351
2352/// Emits metadata nodes associating all the global values in the
2353/// current module with the Decls they came from. This is useful for
2354/// projects using IR gen as a subroutine.
2355///
2356/// Since there's currently no way to associate an MDNode directly
2357/// with an llvm::GlobalValue, we create a global named metadata
2358/// with the name 'clang.global.decl.ptrs'.
2359void CodeGenModule::EmitDeclMetadata() {
2360 llvm::NamedMDNode *GlobalMetadata = 0;
2361
2362 // StaticLocalDeclMap
Chris Lattner5f9e2722011-07-23 10:55:15 +00002363 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
John McCall744016d2010-07-06 23:57:41 +00002364 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2365 I != E; ++I) {
2366 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2367 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2368 }
2369}
2370
2371/// Emits metadata nodes for all the local variables in the current
2372/// function.
2373void CodeGenFunction::EmitDeclMetadata() {
2374 if (LocalDeclMap.empty()) return;
2375
2376 llvm::LLVMContext &Context = getLLVMContext();
2377
2378 // Find the unique metadata ID for this name.
2379 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2380
2381 llvm::NamedMDNode *GlobalMetadata = 0;
2382
2383 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2384 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2385 const Decl *D = I->first;
2386 llvm::Value *Addr = I->second;
2387
2388 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2389 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foad6f141652011-04-21 19:59:12 +00002390 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall744016d2010-07-06 23:57:41 +00002391 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2392 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2393 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2394 }
2395 }
2396}
Daniel Dunbar673431a2010-07-16 00:00:15 +00002397
Nick Lewycky3dc05412011-05-05 00:08:20 +00002398void CodeGenModule::EmitCoverageFile() {
2399 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002400 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2401 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2402 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky3dc05412011-05-05 00:08:20 +00002403 llvm::MDString *CoverageFile =
2404 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002405 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2406 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky3dc05412011-05-05 00:08:20 +00002407 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002408 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2409 GCov->addOperand(N);
2410 }
2411 }
2412 }
2413}