blob: 03fb18177aa3bfe45eecb4a4c27081753b53985e [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"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000019#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000020#include "CGCXXABI.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000021#include "CGObjCRuntime.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000022#include "CGOpenCLRuntime.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000023#include "TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/AST/ASTContext.h"
Ken Dyck687cc4a2010-01-26 13:48:07 +000026#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000027#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000028#include "clang/AST/DeclCXX.h"
Douglas Gregoraf896892010-06-21 18:41:26 +000029#include "clang/AST/DeclTemplate.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000030#include "clang/AST/Mangle.h"
Anders Carlsson1a5e0d72009-11-30 23:41:22 +000031#include "clang/AST/RecordLayout.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000032#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000033#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/TargetInfo.h"
Steve Naroffe9b7d8a2009-04-01 15:50:34 +000035#include "clang/Basic/ConvertUTF.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000036#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000037#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038#include "llvm/Intrinsics.h"
Chris Lattnerd5b89022009-12-28 21:44:41 +000039#include "llvm/LLVMContext.h"
John McCall6374c332010-03-06 00:35:14 +000040#include "llvm/ADT/Triple.h"
Rafael Espindolac4850c22011-02-10 23:59:36 +000041#include "llvm/Target/Mangler.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000042#include "llvm/Target/TargetData.h"
Gabor Greif6ba728d2010-04-10 02:56:12 +000043#include "llvm/Support/CallSite.h"
Chris Lattner78f7ece2009-11-07 09:22:46 +000044#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045using namespace clang;
46using namespace CodeGen;
47
Julien Lerouge77f68bb2011-09-09 22:41:49 +000048static const char AnnotationSection[] = "llvm.metadata";
49
John McCallf16aa102010-08-22 21:01:12 +000050static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000051 switch (CGM.getContext().getTargetInfo().getCXXABI()) {
John McCallf16aa102010-08-22 21:01:12 +000052 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
53 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
54 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
55 }
56
57 llvm_unreachable("invalid C++ ABI kind");
58 return *CreateItaniumCXXABI(CGM);
59}
60
Reid Spencer5f016e22007-07-11 17:01:13 +000061
Chandler Carruth2811ccf2009-11-12 17:24:48 +000062CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall468ec6c2010-03-04 04:29:44 +000063 llvm::Module &M, const llvm::TargetData &TD,
David Blaikied6471f72011-09-25 23:23:43 +000064 DiagnosticsEngine &diags)
John McCalld16c2cf2011-02-08 08:22:06 +000065 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall468ec6c2010-03-04 04:29:44 +000066 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCallf16aa102010-08-22 21:01:12 +000067 ABI(createCXXABI(*this)),
Daniel Dunbar08d47922011-06-21 18:54:39 +000068 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO),
Dan Gohman3d5aff52010-10-14 23:06:10 +000069 TBAA(0),
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000070 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
71 DebugInfo(0), ARCData(0), RRData(0), CFConstantStringClassRef(0),
72 ConstantStringClassRef(0), NSConstantStringType(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000073 VMContext(M.getContext()),
74 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
John McCalld16c2cf2011-02-08 08:22:06 +000075 BlockObjectAssign(0), BlockObjectDispose(0),
76 BlockDescriptorType(0), GenericBlockLiteralType(0) {
David Chisnall60be6072011-03-22 21:21:24 +000077 if (Features.ObjC1)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000078 createObjCRuntime();
79 if (Features.OpenCL)
80 createOpenCLRuntime();
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000081 if (Features.CUDA)
82 createCUDARuntime();
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000083
Dan Gohman3d5aff52010-10-14 23:06:10 +000084 // Enable TBAA unless it's suppressed.
85 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
Dan Gohman0b5c4fc2010-10-15 20:23:12 +000086 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
87 ABI.getMangleContext());
Dan Gohman3d5aff52010-10-14 23:06:10 +000088
Nick Lewyckye8ba8d72011-04-21 23:44:07 +000089 // If debug info or coverage generation is enabled, create the CGDebugInfo
90 // object.
91 if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
92 CodeGenOpts.EmitGcovNotes)
93 DebugInfo = new CGDebugInfo(*this);
John McCalld16c2cf2011-02-08 08:22:06 +000094
95 Block.GlobalUniqueCount = 0;
John McCall5936e332011-02-15 09:22:45 +000096
John McCallf85e1932011-06-15 23:02:42 +000097 if (C.getLangOptions().ObjCAutoRefCount)
98 ARCData = new ARCEntrypoints();
99 RRData = new RREntrypoints();
100
John McCall5936e332011-02-15 09:22:45 +0000101 // Initialize the type cache.
102 llvm::LLVMContext &LLVMContext = M.getContext();
John McCall0774cb82011-05-15 01:53:33 +0000103 VoidTy = llvm::Type::getVoidTy(LLVMContext);
104 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
105 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
106 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000107 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
John McCall34695852011-02-22 06:44:22 +0000108 PointerAlignInBytes =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000109 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
110 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
John McCall5936e332011-02-15 09:22:45 +0000111 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
112 Int8PtrTy = Int8Ty->getPointerTo(0);
113 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Chris Lattner2b94fe32008-03-01 08:45:05 +0000114}
115
116CodeGenModule::~CodeGenModule() {
Peter Collingbournee9265232011-07-27 20:29:46 +0000117 delete ObjCRuntime;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000118 delete OpenCLRuntime;
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000119 delete CUDARuntime;
Ted Kremenek0628b722011-10-08 05:28:26 +0000120 delete TheTargetCodeGenInfo;
John McCallf16aa102010-08-22 21:01:12 +0000121 delete &ABI;
Dan Gohman4376c852010-10-15 18:04:46 +0000122 delete TBAA;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000123 delete DebugInfo;
John McCallf85e1932011-06-15 23:02:42 +0000124 delete ARCData;
125 delete RRData;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000126}
127
David Chisnall0d13f6f2010-01-23 02:40:42 +0000128void CodeGenModule::createObjCRuntime() {
129 if (!Features.NeXTRuntime)
Peter Collingbournee9265232011-07-27 20:29:46 +0000130 ObjCRuntime = CreateGNUObjCRuntime(*this);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000131 else
Peter Collingbournee9265232011-07-27 20:29:46 +0000132 ObjCRuntime = CreateMacObjCRuntime(*this);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000133}
134
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000135void CodeGenModule::createOpenCLRuntime() {
136 OpenCLRuntime = new CGOpenCLRuntime(*this);
137}
138
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000139void CodeGenModule::createCUDARuntime() {
140 CUDARuntime = CreateNVCUDARuntime(*this);
141}
142
Ted Kremenek815c78f2008-08-05 18:50:11 +0000143void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000144 EmitDeferred();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000145 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000146 EmitCXXGlobalDtorFunc();
Peter Collingbournee9265232011-07-27 20:29:46 +0000147 if (ObjCRuntime)
148 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000149 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000150 EmitCtorList(GlobalCtors, "llvm.global_ctors");
151 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000152 EmitGlobalAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +0000153 EmitLLVMUsed();
John McCall744016d2010-07-06 23:57:41 +0000154
John McCallb2593832010-09-16 06:16:50 +0000155 SimplifyPersonality();
156
John McCall744016d2010-07-06 23:57:41 +0000157 if (getCodeGenOpts().EmitDeclMetadata)
158 EmitDeclMetadata();
Nick Lewycky5ea4f442011-05-04 20:46:58 +0000159
160 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky3dc05412011-05-05 00:08:20 +0000161 EmitCoverageFile();
Devang Patelf391dbe2011-08-16 20:58:22 +0000162
163 if (DebugInfo)
164 DebugInfo->finalize();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000165}
166
Devang Patele80d5672011-03-23 16:29:39 +0000167void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
168 // Make sure that this type is translated.
169 Types.UpdateCompletedType(TD);
170 if (DebugInfo)
171 DebugInfo->UpdateCompletedType(TD);
172}
173
Dan Gohman3d5aff52010-10-14 23:06:10 +0000174llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
175 if (!TBAA)
176 return 0;
177 return TBAA->getTBAAInfo(QTy);
178}
179
180void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
181 llvm::MDNode *TBAAInfo) {
182 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
183}
184
John McCall6374c332010-03-06 00:35:14 +0000185bool CodeGenModule::isTargetDarwin() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000186 return getContext().getTargetInfo().getTriple().isOSDarwin();
John McCall6374c332010-03-06 00:35:14 +0000187}
188
Chris Lattner5f9e2722011-07-23 10:55:15 +0000189void CodeGenModule::Error(SourceLocation loc, StringRef error) {
David Blaikied6471f72011-09-25 23:23:43 +0000190 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
John McCall32096692011-03-18 02:56:14 +0000191 getDiags().Report(Context.getFullLoc(loc), diagID);
192}
193
Daniel Dunbar488e9932008-08-16 00:56:44 +0000194/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000195/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000196void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
197 bool OmitOnError) {
198 if (OmitOnError && getDiags().hasErrorOccurred())
199 return;
David Blaikied6471f72011-09-25 23:23:43 +0000200 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000201 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000202 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000203 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
204 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000205}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000206
Daniel Dunbar488e9932008-08-16 00:56:44 +0000207/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000208/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000209void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
210 bool OmitOnError) {
211 if (OmitOnError && getDiags().hasErrorOccurred())
212 return;
David Blaikied6471f72011-09-25 23:23:43 +0000213 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000214 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000215 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000216 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000217}
218
John McCallbc8d40d2011-06-24 21:55:10 +0000219llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
220 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
221}
222
Mike Stump1eb44332009-09-09 15:08:12 +0000223void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000224 const NamedDecl *D) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000225 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000226 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000227 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000228 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000229 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000230
John McCallaf146032010-10-30 11:50:40 +0000231 // Set visibility for definitions.
232 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000233 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
234 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000235}
236
John McCallcbfe5022010-08-04 08:34:44 +0000237/// Set the symbol visibility of type information (vtable and RTTI)
238/// associated with the given type.
239void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
240 const CXXRecordDecl *RD,
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000241 TypeVisibilityKind TVK) const {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000242 setGlobalVisibility(GV, RD);
John McCallcbfe5022010-08-04 08:34:44 +0000243
John McCall279b5eb2010-08-12 23:36:15 +0000244 if (!CodeGenOpts.HiddenWeakVTables)
245 return;
246
Anders Carlsson9a86a132011-01-29 20:36:11 +0000247 // We never want to drop the visibility for RTTI names.
248 if (TVK == TVK_ForRTTIName)
249 return;
250
John McCallcbfe5022010-08-04 08:34:44 +0000251 // We want to drop the visibility to hidden for weak type symbols.
252 // This isn't possible if there might be unresolved references
253 // elsewhere that rely on this symbol being visible.
254
John McCall7a536902010-08-05 20:39:18 +0000255 // This should be kept roughly in sync with setThunkVisibility
256 // in CGVTables.cpp.
257
John McCallcbfe5022010-08-04 08:34:44 +0000258 // Preconditions.
Anders Carlssonf502d932011-01-24 00:46:19 +0000259 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCallcbfe5022010-08-04 08:34:44 +0000260 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
261 return;
262
263 // Don't override an explicit visibility attribute.
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000264 if (RD->getExplicitVisibility())
John McCallcbfe5022010-08-04 08:34:44 +0000265 return;
266
267 switch (RD->getTemplateSpecializationKind()) {
268 // We have to disable the optimization if this is an EI definition
269 // because there might be EI declarations in other shared objects.
270 case TSK_ExplicitInstantiationDefinition:
271 case TSK_ExplicitInstantiationDeclaration:
272 return;
273
John McCall7a536902010-08-05 20:39:18 +0000274 // Every use of a non-template class's type information has to emit it.
John McCallcbfe5022010-08-04 08:34:44 +0000275 case TSK_Undeclared:
276 break;
277
John McCall7a536902010-08-05 20:39:18 +0000278 // In theory, implicit instantiations can ignore the possibility of
279 // an explicit instantiation declaration because there necessarily
280 // must be an EI definition somewhere with default visibility. In
281 // practice, it's possible to have an explicit instantiation for
282 // an arbitrary template class, and linkers aren't necessarily able
283 // to deal with mixed-visibility symbols.
284 case TSK_ExplicitSpecialization:
John McCallcbfe5022010-08-04 08:34:44 +0000285 case TSK_ImplicitInstantiation:
John McCall279b5eb2010-08-12 23:36:15 +0000286 if (!CodeGenOpts.HiddenWeakTemplateVTables)
John McCall7a536902010-08-05 20:39:18 +0000287 return;
John McCallcbfe5022010-08-04 08:34:44 +0000288 break;
289 }
290
291 // If there's a key function, there may be translation units
292 // that don't have the key function's definition. But ignore
293 // this if we're emitting RTTI under -fno-rtti.
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000294 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
John McCallcbfe5022010-08-04 08:34:44 +0000295 if (Context.getKeyFunction(RD))
296 return;
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000297 }
John McCallcbfe5022010-08-04 08:34:44 +0000298
299 // Otherwise, drop the visibility to hidden.
300 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1c65ff2011-01-11 21:44:37 +0000301 GV->setUnnamedAddr(true);
John McCallcbfe5022010-08-04 08:34:44 +0000302}
303
Chris Lattner5f9e2722011-07-23 10:55:15 +0000304StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000305 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
306
Chris Lattner5f9e2722011-07-23 10:55:15 +0000307 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
Anders Carlsson793a9902010-06-22 16:05:32 +0000308 if (!Str.empty())
309 return Str;
310
John McCall4c40d982010-08-31 07:33:07 +0000311 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000312 IdentifierInfo *II = ND->getIdentifier();
313 assert(II && "Attempt to mangle unnamed decl.");
314
315 Str = II->getName();
316 return Str;
317 }
318
319 llvm::SmallString<256> Buffer;
Rafael Espindolac4850c22011-02-10 23:59:36 +0000320 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000321 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000322 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000323 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000324 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000325 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000326 getCXXABI().getMangleContext().mangleBlock(BD, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000327 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000328 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000329
330 // Allocate space for the mangled name.
Rafael Espindolac4850c22011-02-10 23:59:36 +0000331 Out.flush();
Anders Carlsson793a9902010-06-22 16:05:32 +0000332 size_t Length = Buffer.size();
333 char *Name = MangledNamesAllocator.Allocate<char>(Length);
334 std::copy(Buffer.begin(), Buffer.end(), Name);
335
Chris Lattner5f9e2722011-07-23 10:55:15 +0000336 Str = StringRef(Name, Length);
Anders Carlsson793a9902010-06-22 16:05:32 +0000337
338 return Str;
339}
340
Peter Collingbourne14110472011-01-13 18:57:25 +0000341void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
342 const BlockDecl *BD) {
343 MangleContext &MangleCtx = getCXXABI().getMangleContext();
344 const Decl *D = GD.getDecl();
Rafael Espindolac4850c22011-02-10 23:59:36 +0000345 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne14110472011-01-13 18:57:25 +0000346 if (D == 0)
Rafael Espindolac4850c22011-02-10 23:59:36 +0000347 MangleCtx.mangleGlobalBlock(BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000348 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000349 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000350 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000351 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000352 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000353 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000354}
355
Chris Lattner5f9e2722011-07-23 10:55:15 +0000356llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCallf746aa62010-03-19 23:29:14 +0000357 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000358}
359
Chris Lattner6d397602008-03-14 17:18:18 +0000360/// AddGlobalCtor - Add a function to the list that will be called before
361/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000362void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000363 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000364 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000365}
366
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000367/// AddGlobalDtor - Add a function to the list that will be called
368/// when the module is unloaded.
369void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000370 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000371 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
372}
373
374void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
375 // Ctor function type is void()*.
John McCall0774cb82011-05-15 01:53:33 +0000376 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000377 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000378
379 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000380 llvm::StructType *CtorStructTy =
Chris Lattner7650d952011-06-18 22:49:11 +0000381 llvm::StructType::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson96e0fc72009-07-29 22:16:19 +0000382 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000383
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000384 // Construct the constructor and destructor arrays.
385 std::vector<llvm::Constant*> Ctors;
386 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
387 std::vector<llvm::Constant*> S;
Mike Stump1eb44332009-09-09 15:08:12 +0000388 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson0032b272009-08-13 21:57:51 +0000389 I->second, false));
Owen Anderson3c4972d2009-07-29 18:54:39 +0000390 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson08e25242009-07-27 22:29:56 +0000391 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000392 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000393
394 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000395 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000396 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000397 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000398 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000399 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000400 }
Chris Lattner6d397602008-03-14 17:18:18 +0000401}
402
John McCalld46f9852010-02-19 01:32:20 +0000403llvm::GlobalValue::LinkageTypes
404CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000405 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000406
Chris Lattnerf81530652010-06-30 16:58:07 +0000407 if (Linkage == GVA_Internal)
John McCalld46f9852010-02-19 01:32:20 +0000408 return llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000409
410 if (D->hasAttr<DLLExportAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000411 return llvm::Function::DLLExportLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000412
413 if (D->hasAttr<WeakAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000414 return llvm::Function::WeakAnyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000415
416 // In C99 mode, 'inline' functions are guaranteed to have a strong
417 // definition somewhere else, so we can use available_externally linkage.
418 if (Linkage == GVA_C99Inline)
Fariborz Jahanianfd0f89d2011-02-04 00:08:13 +0000419 return llvm::Function::AvailableExternallyLinkage;
John McCall5584d912011-09-19 18:05:26 +0000420
421 // Note that Apple's kernel linker doesn't support symbol
422 // coalescing, so we need to avoid linkonce and weak linkages there.
423 // Normally, this means we just map to internal, but for explicit
424 // instantiations we'll map to external.
425
Chris Lattnerf81530652010-06-30 16:58:07 +0000426 // In C++, the compiler has to emit a definition in every translation unit
427 // that references the function. We should use linkonce_odr because
428 // a) if all references in this translation unit are optimized away, we
429 // don't need to codegen it. b) if the function persists, it needs to be
430 // merged with other definitions. c) C++ has the ODR, so we know the
431 // definition is dependable.
432 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000433 return !Context.getLangOptions().AppleKext
434 ? llvm::Function::LinkOnceODRLinkage
435 : llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000436
437 // An explicit instantiation of a template has weak linkage, since
438 // explicit instantiations can occur in multiple translation units
439 // and must all be equivalent. However, we are not allowed to
440 // throw away these explicit instantiations.
441 if (Linkage == GVA_ExplicitTemplateInstantiation)
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000442 return !Context.getLangOptions().AppleKext
443 ? llvm::Function::WeakODRLinkage
John McCall5584d912011-09-19 18:05:26 +0000444 : llvm::Function::ExternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000445
446 // Otherwise, we have strong external linkage.
447 assert(Linkage == GVA_StrongExternal);
448 return llvm::Function::ExternalLinkage;
John McCalld46f9852010-02-19 01:32:20 +0000449}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000450
John McCalld46f9852010-02-19 01:32:20 +0000451
452/// SetFunctionDefinitionAttributes - Set attributes for a global.
453///
454/// FIXME: This is currently only done for aliases and functions, but not for
455/// variables (these details are set in EmitGlobalVarDefinition for variables).
456void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
457 llvm::GlobalValue *GV) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000458 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000459}
460
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000461void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000462 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000463 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000464 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000465 AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000466 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel761d7f72008-09-25 21:02:23 +0000467 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000468 AttributeList.size()));
469 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000470}
471
John McCalld1e40d52011-10-02 01:16:38 +0000472/// Determines whether the language options require us to model
473/// unwind exceptions. We treat -fexceptions as mandating this
474/// except under the fragile ObjC ABI with only ObjC exceptions
475/// enabled. This means, for example, that C with -fexceptions
476/// enables this.
477static bool hasUnwindExceptions(const LangOptions &Features) {
478 // If exceptions are completely disabled, obviously this is false.
479 if (!Features.Exceptions) return false;
480
481 // If C++ exceptions are enabled, this is true.
482 if (Features.CXXExceptions) return true;
483
484 // If ObjC exceptions are enabled, this depends on the ABI.
485 if (Features.ObjCExceptions) {
486 if (!Features.ObjCNonFragileABI) return false;
487 }
488
489 return true;
490}
491
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000492void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
493 llvm::Function *F) {
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000494 if (CodeGenOpts.UnwindTables)
495 F->setHasUWTable();
496
John McCalld1e40d52011-10-02 01:16:38 +0000497 if (!hasUnwindExceptions(Features))
Mike Stump1eb44332009-09-09 15:08:12 +0000498 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000499
Eli Friedman2873aee2011-08-22 23:55:33 +0000500 if (D->hasAttr<NakedAttr>()) {
501 // Naked implies noinline: we should not be inlining such functions.
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000502 F->addFnAttr(llvm::Attribute::Naked);
Eli Friedman2873aee2011-08-22 23:55:33 +0000503 F->addFnAttr(llvm::Attribute::NoInline);
504 }
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000505
Mike Stump1feade82009-08-26 22:31:08 +0000506 if (D->hasAttr<NoInlineAttr>())
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000507 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpf55314d2009-10-05 21:58:44 +0000508
Eli Friedman2873aee2011-08-22 23:55:33 +0000509 // (noinline wins over always_inline, and we can't specify both in IR)
510 if (D->hasAttr<AlwaysInlineAttr>() &&
511 !F->hasFnAttr(llvm::Attribute::NoInline))
512 F->addFnAttr(llvm::Attribute::AlwaysInline);
513
Rafael Espindolac5f657f2011-01-11 00:26:26 +0000514 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
515 F->setUnnamedAddr(true);
516
Douglas Gregore289d812011-09-13 17:21:33 +0000517 if (Features.getStackProtector() == LangOptions::SSPOn)
Anders Carlssonfd015352009-11-16 16:56:03 +0000518 F->addFnAttr(llvm::Attribute::StackProtect);
Douglas Gregore289d812011-09-13 17:21:33 +0000519 else if (Features.getStackProtector() == LangOptions::SSPReq)
Anders Carlssonfd015352009-11-16 16:56:03 +0000520 F->addFnAttr(llvm::Attribute::StackProtectReq);
521
Sean Huntcf807c42010-08-18 23:23:40 +0000522 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
523 if (alignment)
524 F->setAlignment(alignment);
525
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000526 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000527 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
528 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000529}
530
Mike Stump1eb44332009-09-09 15:08:12 +0000531void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000532 llvm::GlobalValue *GV) {
Anders Carlsson934176f2011-01-29 19:41:00 +0000533 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
534 setGlobalVisibility(GV, ND);
John McCall1fb0caa2010-10-22 21:05:15 +0000535 else
536 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000537
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000538 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000539 AddUsedGlobal(GV);
540
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000541 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000542 GV->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000543
544 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000545}
546
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000547void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
548 llvm::Function *F,
549 const CGFunctionInfo &FI) {
550 SetLLVMFunctionAttributes(D, FI, F);
551 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000552
553 F->setLinkage(llvm::Function::InternalLinkage);
554
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000555 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000556}
557
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000558void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000559 llvm::Function *F,
560 bool IsIncompleteFunction) {
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000561 if (unsigned IID = F->getIntrinsicID()) {
562 // If this is an intrinsic function, set the function's attributes
563 // to the intrinsic's attributes.
564 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
565 return;
566 }
567
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000568 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
569
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000570 if (!IsIncompleteFunction)
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000571 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000573 // Only a few attributes are set on declarations; these may later be
574 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000576 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000577 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump1eb44332009-09-09 15:08:12 +0000578 } else if (FD->hasAttr<WeakAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000579 FD->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000580 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump1eb44332009-09-09 15:08:12 +0000581 // separate linkage types for this.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000582 F->setLinkage(llvm::Function::ExternalWeakLinkage);
583 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000584 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallaf146032010-10-30 11:50:40 +0000585
586 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
587 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
588 F->setVisibility(GetLLVMVisibility(LV.visibility()));
589 }
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000590 }
591
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000592 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000593 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000594}
595
Daniel Dunbar02698712009-02-13 20:29:50 +0000596void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +0000597 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +0000598 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000599 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000600}
601
602void CodeGenModule::EmitLLVMUsed() {
603 // Don't create llvm.used if there is no need.
Chris Lattnerad64e022009-07-17 23:57:13 +0000604 if (LLVMUsed.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +0000605 return;
606
Chris Lattner2acc6e32011-07-18 04:24:23 +0000607 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattner35f38a22009-03-31 22:37:52 +0000609 // Convert LLVMUsed to what ConstantArray needs.
610 std::vector<llvm::Constant*> UsedArray;
611 UsedArray.resize(LLVMUsed.size());
612 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000613 UsedArray[i] =
614 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000615 i8PTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000616 }
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000618 if (UsedArray.empty())
619 return;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000620 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000621
622 llvm::GlobalVariable *GV =
623 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar02698712009-02-13 20:29:50 +0000624 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000625 llvm::ConstantArray::get(ATy, UsedArray),
Owen Anderson1c431b32009-07-08 19:05:04 +0000626 "llvm.used");
Daniel Dunbar02698712009-02-13 20:29:50 +0000627
628 GV->setSection("llvm.metadata");
629}
630
631void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000632 // Emit code for any potentially referenced deferred decls. Since a
633 // previously unused static decl may become used during the generation of code
Nick Lewyckydce67a72011-07-18 05:26:13 +0000634 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000635
Anders Carlsson046c2942010-04-17 20:15:18 +0000636 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
637 if (!DeferredVTables.empty()) {
638 const CXXRecordDecl *RD = DeferredVTables.back();
639 DeferredVTables.pop_back();
640 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000641 continue;
642 }
643
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000644 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000645 DeferredDeclsToEmit.pop_back();
646
John McCallc76702c2010-05-27 01:45:30 +0000647 // Check to see if we've already emitted this. This is necessary
648 // for a couple of reasons: first, decls can end up in the
649 // deferred-decls queue multiple times, and second, decls can end
650 // up with definitions in unusual ways (e.g. by an extern inline
651 // function acquiring a strong function redefinition). Just
652 // ignore these cases.
653 //
654 // TODO: That said, looking this up multiple times is very wasteful.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000655 StringRef Name = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +0000656 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner67b00522009-03-21 09:44:56 +0000657 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Chris Lattner67b00522009-03-21 09:44:56 +0000659 if (!CGRef->isDeclaration())
660 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000661
John McCallc76702c2010-05-27 01:45:30 +0000662 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
663 // purposes an alias counts as a definition.
664 if (isa<llvm::GlobalAlias>(CGRef))
665 continue;
666
Chris Lattner67b00522009-03-21 09:44:56 +0000667 // Otherwise, emit the definition and move on to the next one.
668 EmitGlobalDefinition(D);
669 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000670}
671
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000672void CodeGenModule::EmitGlobalAnnotations() {
673 if (Annotations.empty())
674 return;
675
676 // Create a new global variable for the ConstantStruct in the Module.
677 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
678 Annotations[0]->getType(), Annotations.size()), Annotations);
679 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
680 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
681 "llvm.global.annotations");
682 gv->setSection(AnnotationSection);
683}
684
685llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
686 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
687 if (i != AnnotationStrings.end())
688 return i->second;
689
690 // Not found yet, create a new global.
691 llvm::Constant *s = llvm::ConstantArray::get(getLLVMContext(), Str, true);
692 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
693 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
694 gv->setSection(AnnotationSection);
695 gv->setUnnamedAddr(true);
696 AnnotationStrings[Str] = gv;
697 return gv;
698}
699
700llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
701 SourceManager &SM = getContext().getSourceManager();
702 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
703 if (PLoc.isValid())
704 return EmitAnnotationString(PLoc.getFilename());
705 return EmitAnnotationString(SM.getBufferName(Loc));
706}
707
708llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
709 SourceManager &SM = getContext().getSourceManager();
710 PresumedLoc PLoc = SM.getPresumedLoc(L);
711 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
712 SM.getExpansionLineNumber(L);
713 return llvm::ConstantInt::get(Int32Ty, LineNo);
714}
715
Mike Stump1eb44332009-09-09 15:08:12 +0000716llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000717 const AnnotateAttr *AA,
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000718 SourceLocation L) {
719 // Get the globals for file name, annotation, and the line number.
720 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
721 *UnitGV = EmitAnnotationUnit(L),
722 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000723
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000724 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000725 llvm::Constant *Fields[4] = {
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000726 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
727 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
728 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
729 LineNoCst
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000730 };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000731 return llvm::ConstantStruct::getAnon(Fields);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000732}
733
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000734void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
735 llvm::GlobalValue *GV) {
736 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
737 // Get the struct elements for these annotations.
738 for (specific_attr_iterator<AnnotateAttr>
739 ai = D->specific_attr_begin<AnnotateAttr>(),
740 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
741 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
742}
743
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000744bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000745 // Never defer when EmitAllDecls is specified.
746 if (Features.EmitAllDecls)
Daniel Dunbar73241df2009-02-13 21:18:01 +0000747 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000748
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +0000749 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000750}
751
Rafael Espindola6a836702010-03-04 18:17:24 +0000752llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
753 const AliasAttr *AA = VD->getAttr<AliasAttr>();
754 assert(AA && "No alias?");
755
Chris Lattner2acc6e32011-07-18 04:24:23 +0000756 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola6a836702010-03-04 18:17:24 +0000757
Rafael Espindola6a836702010-03-04 18:17:24 +0000758 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +0000759 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola6a836702010-03-04 18:17:24 +0000760
761 llvm::Constant *Aliasee;
762 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000763 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
764 /*ForVTable=*/false);
Rafael Espindola6a836702010-03-04 18:17:24 +0000765 else
John McCallf746aa62010-03-19 23:29:14 +0000766 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola6a836702010-03-04 18:17:24 +0000767 llvm::PointerType::getUnqual(DeclTy), 0);
768 if (!Entry) {
769 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
770 F->setLinkage(llvm::Function::ExternalWeakLinkage);
771 WeakRefReferences.insert(F);
772 }
773
774 return Aliasee;
775}
776
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000777void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000778 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Rafael Espindola6a836702010-03-04 18:17:24 +0000780 // Weak references don't produce any output by themselves.
781 if (Global->hasAttr<WeakRefAttr>())
782 return;
783
Chris Lattnerbd532712009-03-22 21:47:11 +0000784 // If this is an alias definition (which otherwise looks like a declaration)
785 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000786 if (Global->hasAttr<AliasAttr>())
John McCallf746aa62010-03-19 23:29:14 +0000787 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +0000788
Peter Collingbourned51e43a2011-10-06 18:29:46 +0000789 // If this is CUDA, be selective about which declarations we emit.
790 if (Features.CUDA) {
791 if (CodeGenOpts.CUDAIsDevice) {
792 if (!Global->hasAttr<CUDADeviceAttr>() &&
793 !Global->hasAttr<CUDAGlobalAttr>() &&
794 !Global->hasAttr<CUDAConstantAttr>() &&
795 !Global->hasAttr<CUDASharedAttr>())
796 return;
797 } else {
798 if (!Global->hasAttr<CUDAHostAttr>() && (
799 Global->hasAttr<CUDADeviceAttr>() ||
800 Global->hasAttr<CUDAConstantAttr>() ||
801 Global->hasAttr<CUDASharedAttr>()))
802 return;
803 }
804 }
805
Chris Lattner67b00522009-03-21 09:44:56 +0000806 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000807 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000808 // Forward declarations are emitted lazily on first use.
Nick Lewyckydce67a72011-07-18 05:26:13 +0000809 if (!FD->doesThisDeclarationHaveABody()) {
810 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
811 return;
812
813 const FunctionDecl *InlineDefinition = 0;
814 FD->getBody(InlineDefinition);
815
Chris Lattner5f9e2722011-07-23 10:55:15 +0000816 StringRef MangledName = getMangledName(GD);
Nick Lewyckydce67a72011-07-18 05:26:13 +0000817 llvm::StringMap<GlobalDecl>::iterator DDI =
818 DeferredDecls.find(MangledName);
819 if (DDI != DeferredDecls.end())
820 DeferredDecls.erase(DDI);
821 EmitGlobalDefinition(InlineDefinition);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000822 return;
Nick Lewyckydce67a72011-07-18 05:26:13 +0000823 }
Daniel Dunbar02698712009-02-13 20:29:50 +0000824 } else {
825 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000826 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
827
Douglas Gregora9a55c02010-02-06 05:15:45 +0000828 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000829 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000830 }
831
Chris Lattner67b00522009-03-21 09:44:56 +0000832 // Defer code generation when possible if this is a static definition, inline
833 // function etc. These we only want to emit if they are used.
Chris Lattner4357a822010-04-13 17:39:09 +0000834 if (!MayDeferGeneration(Global)) {
835 // Emit the definition if it can't be deferred.
836 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000837 return;
838 }
John McCallbf40cb52010-07-15 23:40:35 +0000839
840 // If we're deferring emission of a C++ variable with an
841 // initializer, remember the order in which it appeared in the file.
842 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
843 cast<VarDecl>(Global)->hasInit()) {
844 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
845 CXXGlobalInits.push_back(0);
846 }
Chris Lattner4357a822010-04-13 17:39:09 +0000847
848 // If the value has already been used, add it directly to the
849 // DeferredDeclsToEmit list.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000850 StringRef MangledName = getMangledName(GD);
Chris Lattner4357a822010-04-13 17:39:09 +0000851 if (GetGlobalValue(MangledName))
852 DeferredDeclsToEmit.push_back(GD);
853 else {
854 // Otherwise, remember that we saw a deferred decl with this name. The
855 // first use of the mangled name will cause it to move into
856 // DeferredDeclsToEmit.
857 DeferredDecls[MangledName] = GD;
858 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000859}
860
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000861void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000862 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Dan Gohmancb421fa2010-04-19 16:39:44 +0000864 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +0000865 Context.getSourceManager(),
866 "Generating code for declaration");
867
Douglas Gregor44eac332010-07-13 06:02:28 +0000868 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
869 // At -O0, don't generate IR for functions with available_externally
870 // linkage.
Douglas Gregor7feaeee2010-07-15 22:58:18 +0000871 if (CodeGenOpts.OptimizationLevel == 0 &&
872 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregor44eac332010-07-13 06:02:28 +0000873 getFunctionLinkage(Function)
874 == llvm::Function::AvailableExternallyLinkage)
875 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +0000876
Douglas Gregor44eac332010-07-13 06:02:28 +0000877 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000878 // Make sure to emit the definition(s) before we emit the thunks.
879 // This is necessary for the generation of certain thunks.
880 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
881 EmitCXXConstructor(CD, GD.getCtorType());
882 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
883 EmitCXXDestructor(DD, GD.getDtorType());
884 else
885 EmitGlobalFunctionDefinition(GD);
886
Douglas Gregor44eac332010-07-13 06:02:28 +0000887 if (Method->isVirtual())
888 getVTables().EmitThunks(GD);
889
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000890 return;
Douglas Gregor44eac332010-07-13 06:02:28 +0000891 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000892
Chris Lattnerb5e81562010-04-13 17:57:11 +0000893 return EmitGlobalFunctionDefinition(GD);
Douglas Gregor44eac332010-07-13 06:02:28 +0000894 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000895
896 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
897 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +0000898
David Blaikieb219cfc2011-09-23 05:06:16 +0000899 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000900}
901
Chris Lattner74391b42009-03-22 21:03:39 +0000902/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
903/// module, create and return an llvm Function with the specified type. If there
904/// is something in the module with the specified name, return it potentially
905/// bitcasted to the right type.
906///
907/// If D is non-null, it specifies a decl that correspond to this. This is used
908/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +0000909llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000910CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000911 llvm::Type *Ty,
John McCallf85e1932011-06-15 23:02:42 +0000912 GlobalDecl D, bool ForVTable,
913 llvm::Attributes ExtraAttrs) {
Chris Lattner0558e792009-03-21 09:25:43 +0000914 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +0000915 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +0000916 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +0000917 if (WeakRefReferences.count(Entry)) {
918 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
919 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +0000920 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +0000921
922 WeakRefReferences.erase(Entry);
923 }
924
Chris Lattner0558e792009-03-21 09:25:43 +0000925 if (Entry->getType()->getElementType() == Ty)
926 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Chris Lattner0558e792009-03-21 09:25:43 +0000928 // Make sure the result is of the correct type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000929 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattner0558e792009-03-21 09:25:43 +0000930 }
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Eli Friedman654ad402009-11-09 05:07:37 +0000932 // This function doesn't have a complete type (for example, the return
933 // type is an incomplete struct). Use a fake type instead, and make
934 // sure not to try to set attributes.
935 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +0000936
Chris Lattner2acc6e32011-07-18 04:24:23 +0000937 llvm::FunctionType *FTy;
John McCall784f2112010-04-28 00:00:30 +0000938 if (isa<llvm::FunctionType>(Ty)) {
939 FTy = cast<llvm::FunctionType>(Ty);
940 } else {
John McCall0774cb82011-05-15 01:53:33 +0000941 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedman654ad402009-11-09 05:07:37 +0000942 IsIncompleteFunction = true;
943 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000944
John McCall784f2112010-04-28 00:00:30 +0000945 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +0000946 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +0000947 MangledName, &getModule());
948 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedman654ad402009-11-09 05:07:37 +0000949 if (D.getDecl())
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000950 SetFunctionAttributes(D, F, IsIncompleteFunction);
John McCallf85e1932011-06-15 23:02:42 +0000951 if (ExtraAttrs != llvm::Attribute::None)
952 F->addFnAttr(ExtraAttrs);
Eli Friedman654ad402009-11-09 05:07:37 +0000953
Chris Lattner67b00522009-03-21 09:44:56 +0000954 // This is the first use or definition of a mangled name. If there is a
955 // deferred decl with this name, remember that we need to emit it at the end
956 // of the file.
John McCallf746aa62010-03-19 23:29:14 +0000957 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000958 if (DDI != DeferredDecls.end()) {
959 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
960 // list, and remove it from DeferredDecls (since we don't need it anymore).
961 DeferredDeclsToEmit.push_back(DDI->second);
962 DeferredDecls.erase(DDI);
John McCallbfdcdc82010-12-15 04:00:32 +0000963
964 // Otherwise, there are cases we have to worry about where we're
965 // using a declaration for which we must emit a definition but where
966 // we might not find a top-level definition:
967 // - member functions defined inline in their classes
968 // - friend functions defined inline in some class
969 // - special member functions with implicit definitions
970 // If we ever change our AST traversal to walk into class methods,
971 // this will be unnecessary.
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000972 //
973 // We also don't emit a definition for a function if it's going to be an entry
974 // in a vtable, unless it's already marked as used.
Rafael Espindola01de7a42011-02-03 06:30:58 +0000975 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
John McCallbfdcdc82010-12-15 04:00:32 +0000976 // Look for a declaration that's lexically in a record.
977 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
978 do {
979 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000980 if (FD->isImplicit() && !ForVTable) {
John McCallbfdcdc82010-12-15 04:00:32 +0000981 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
Douglas Gregora29bf412011-02-09 02:03:05 +0000982 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +0000983 break;
Sean Hunt10620eb2011-05-06 20:44:56 +0000984 } else if (FD->doesThisDeclarationHaveABody()) {
Douglas Gregora29bf412011-02-09 02:03:05 +0000985 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +0000986 break;
987 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000988 }
John McCallbfdcdc82010-12-15 04:00:32 +0000989 FD = FD->getPreviousDeclaration();
990 } while (FD);
Chris Lattner67b00522009-03-21 09:44:56 +0000991 }
Mike Stump1eb44332009-09-09 15:08:12 +0000992
John McCall784f2112010-04-28 00:00:30 +0000993 // Make sure the result is of the requested type.
994 if (!IsIncompleteFunction) {
995 assert(F->getType()->getElementType() == Ty);
996 return F;
997 }
998
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000999 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCall784f2112010-04-28 00:00:30 +00001000 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +00001001}
1002
Chris Lattner74391b42009-03-22 21:03:39 +00001003/// GetAddrOfFunction - Return the address of the given function. If Ty is
1004/// non-null, then this function will use the specified type if it has to
1005/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001006llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001007 llvm::Type *Ty,
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001008 bool ForVTable) {
Chris Lattner74391b42009-03-22 21:03:39 +00001009 // If there was no specific requested type, just convert it now.
1010 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +00001011 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001012
Chris Lattner5f9e2722011-07-23 10:55:15 +00001013 StringRef MangledName = getMangledName(GD);
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001014 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
Chris Lattner74391b42009-03-22 21:03:39 +00001015}
Eli Friedman77ba7082008-05-30 19:50:47 +00001016
Chris Lattner74391b42009-03-22 21:03:39 +00001017/// CreateRuntimeFunction - Create a new runtime function with the specified
1018/// type and name.
1019llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001020CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001021 StringRef Name,
John McCallf85e1932011-06-15 23:02:42 +00001022 llvm::Attributes ExtraAttrs) {
1023 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1024 ExtraAttrs);
Chris Lattner74391b42009-03-22 21:03:39 +00001025}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001026
Douglas Gregorda550742011-05-07 22:06:45 +00001027static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D,
1028 bool ConstantInit) {
John McCall88786862010-02-08 21:46:50 +00001029 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +00001030 return false;
Douglas Gregorda550742011-05-07 22:06:45 +00001031
1032 if (Context.getLangOptions().CPlusPlus) {
1033 if (const RecordType *Record
1034 = Context.getBaseElementType(D->getType())->getAs<RecordType>())
Douglas Gregor2bb11012011-05-13 01:05:07 +00001035 return ConstantInit &&
1036 cast<CXXRecordDecl>(Record->getDecl())->isPOD() &&
1037 !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields();
Eli Friedman20e098b2009-12-11 21:23:03 +00001038 }
Douglas Gregorda550742011-05-07 22:06:45 +00001039
Eli Friedman20e098b2009-12-11 21:23:03 +00001040 return true;
1041}
1042
Chris Lattner74391b42009-03-22 21:03:39 +00001043/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1044/// create and return an llvm GlobalVariable with the specified type. If there
1045/// is something in the module with the specified name, return it potentially
1046/// bitcasted to the right type.
1047///
1048/// If D is non-null, it specifies a decl that correspond to this. This is used
1049/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001050llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001051CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001052 llvm::PointerType *Ty,
Rafael Espindolac532b502011-01-18 21:07:57 +00001053 const VarDecl *D,
1054 bool UnnamedAddr) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +00001055 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001056 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +00001057 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001058 if (WeakRefReferences.count(Entry)) {
1059 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001060 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001061
1062 WeakRefReferences.erase(Entry);
1063 }
1064
Rafael Espindolac532b502011-01-18 21:07:57 +00001065 if (UnnamedAddr)
1066 Entry->setUnnamedAddr(true);
1067
Chris Lattner74391b42009-03-22 21:03:39 +00001068 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +00001069 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Chris Lattner99b53612009-03-21 08:03:33 +00001071 // Make sure the result is of the correct type.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001072 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +00001073 }
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Chris Lattner67b00522009-03-21 09:44:56 +00001075 // This is the first use or definition of a mangled name. If there is a
1076 // deferred decl with this name, remember that we need to emit it at the end
1077 // of the file.
John McCallf746aa62010-03-19 23:29:14 +00001078 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001079 if (DDI != DeferredDecls.end()) {
1080 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1081 // list, and remove it from DeferredDecls (since we don't need it anymore).
1082 DeferredDeclsToEmit.push_back(DDI->second);
1083 DeferredDecls.erase(DDI);
1084 }
Mike Stump1eb44332009-09-09 15:08:12 +00001085
1086 llvm::GlobalVariable *GV =
1087 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +00001088 llvm::GlobalValue::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001089 0, MangledName, 0,
Eli Friedman56ebe502009-04-19 21:05:03 +00001090 false, Ty->getAddressSpace());
Chris Lattner99b53612009-03-21 08:03:33 +00001091
1092 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +00001093 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001094 // FIXME: This code is overly simple and should be merged with other global
1095 // handling.
Douglas Gregorda550742011-05-07 22:06:45 +00001096 GV->setConstant(DeclIsConstantGlobal(Context, D, false));
Chris Lattner99b53612009-03-21 08:03:33 +00001097
John McCall110e8e52010-10-29 22:22:43 +00001098 // Set linkage and visibility in case we never see a definition.
John McCallaf146032010-10-30 11:50:40 +00001099 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1100 if (LV.linkage() != ExternalLinkage) {
John McCall15e310a2011-02-19 02:53:41 +00001101 // Don't set internal linkage on declarations.
John McCall110e8e52010-10-29 22:22:43 +00001102 } else {
1103 if (D->hasAttr<DLLImportAttr>())
1104 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001105 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
John McCall110e8e52010-10-29 22:22:43 +00001106 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner99b53612009-03-21 08:03:33 +00001107
John McCallaf146032010-10-30 11:50:40 +00001108 // Set visibility on a declaration only if it's explicit.
1109 if (LV.visibilityExplicit())
1110 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall110e8e52010-10-29 22:22:43 +00001111 }
Eli Friedman56ebe502009-04-19 21:05:03 +00001112
1113 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattner74391b42009-03-22 21:03:39 +00001114 }
Mike Stump1eb44332009-09-09 15:08:12 +00001115
John McCallf746aa62010-03-19 23:29:14 +00001116 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001117}
1118
Chris Lattner74391b42009-03-22 21:03:39 +00001119
Anders Carlsson3bd62022011-01-29 18:20:20 +00001120llvm::GlobalVariable *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001121CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001122 llvm::Type *Ty,
Anders Carlsson3bd62022011-01-29 18:20:20 +00001123 llvm::GlobalValue::LinkageTypes Linkage) {
1124 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1125 llvm::GlobalVariable *OldGV = 0;
1126
1127
1128 if (GV) {
1129 // Check if the variable has the right type.
1130 if (GV->getType()->getElementType() == Ty)
1131 return GV;
1132
1133 // Because C++ name mangling, the only way we can end up with an already
1134 // existing global with the same name is if it has been declared extern "C".
Anders Carlsson96eaf292011-01-29 18:25:07 +00001135 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlsson3bd62022011-01-29 18:20:20 +00001136 OldGV = GV;
1137 }
1138
1139 // Create a new variable.
1140 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1141 Linkage, 0, Name);
1142
1143 if (OldGV) {
1144 // Replace occurrences of the old variable if needed.
1145 GV->takeName(OldGV);
1146
1147 if (!OldGV->use_empty()) {
1148 llvm::Constant *NewPtrForOldDecl =
1149 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1150 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1151 }
1152
1153 OldGV->eraseFromParent();
1154 }
1155
1156 return GV;
1157}
1158
Chris Lattner74391b42009-03-22 21:03:39 +00001159/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1160/// given global variable. If Ty is non-null and if the global doesn't exist,
1161/// then it will be greated with the specified type instead of whatever the
1162/// normal requested type would be.
1163llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001164 llvm::Type *Ty) {
Chris Lattner74391b42009-03-22 21:03:39 +00001165 assert(D->hasGlobalStorage() && "Not a global variable");
1166 QualType ASTTy = D->getType();
1167 if (Ty == 0)
1168 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Chris Lattner2acc6e32011-07-18 04:24:23 +00001170 llvm::PointerType *PTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001171 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCallf746aa62010-03-19 23:29:14 +00001172
Chris Lattner5f9e2722011-07-23 10:55:15 +00001173 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001174 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001175}
1176
1177/// CreateRuntimeVariable - Create a new runtime global variable with the
1178/// specified type and name.
1179llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001180CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001181 StringRef Name) {
John McCall1de4d4e2011-04-07 08:22:57 +00001182 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolac532b502011-01-18 21:07:57 +00001183 true);
Chris Lattner74391b42009-03-22 21:03:39 +00001184}
1185
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001186void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1187 assert(!D->getInit() && "Cannot emit definite definitions here!");
1188
Douglas Gregor7520bd12009-04-21 19:28:58 +00001189 if (MayDeferGeneration(D)) {
1190 // If we have not seen a reference to this variable yet, place it
1191 // into the deferred declarations table to be emitted if needed
1192 // later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001193 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001194 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001195 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001196 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001197 }
1198 }
1199
1200 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001201 EmitGlobalVarDefinition(D);
1202}
1203
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001204void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1205 if (DefinitionRequired)
1206 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1207}
1208
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001209llvm::GlobalVariable::LinkageTypes
Anders Carlsson046c2942010-04-17 20:15:18 +00001210CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Eli Friedmancb5d2d02011-06-10 21:53:06 +00001211 if (RD->getLinkage() != ExternalLinkage)
Douglas Gregordffb8012010-01-06 22:00:56 +00001212 return llvm::GlobalVariable::InternalLinkage;
1213
1214 if (const CXXMethodDecl *KeyFunction
1215 = RD->getASTContext().getKeyFunction(RD)) {
1216 // If this class has a key function, use that to determine the linkage of
1217 // the vtable.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001218 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001219 if (KeyFunction->hasBody(Def))
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001220 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregordffb8012010-01-06 22:00:56 +00001221
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001222 switch (KeyFunction->getTemplateSpecializationKind()) {
1223 case TSK_Undeclared:
1224 case TSK_ExplicitSpecialization:
Anders Carlsson6d7f8472011-01-30 20:45:54 +00001225 // When compiling with optimizations turned on, we emit all vtables,
1226 // even if the key function is not defined in the current translation
1227 // unit. If this is the case, use available_externally linkage.
1228 if (!Def && CodeGenOpts.OptimizationLevel)
1229 return llvm::GlobalVariable::AvailableExternallyLinkage;
1230
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001231 if (KeyFunction->isInlined())
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001232 return !Context.getLangOptions().AppleKext ?
1233 llvm::GlobalVariable::LinkOnceODRLinkage :
1234 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001235
1236 return llvm::GlobalVariable::ExternalLinkage;
1237
1238 case TSK_ImplicitInstantiation:
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001239 return !Context.getLangOptions().AppleKext ?
1240 llvm::GlobalVariable::LinkOnceODRLinkage :
1241 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001242
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001243 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001244 return !Context.getLangOptions().AppleKext ?
1245 llvm::GlobalVariable::WeakODRLinkage :
1246 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001247
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001248 case TSK_ExplicitInstantiationDeclaration:
1249 // FIXME: Use available_externally linkage. However, this currently
1250 // breaks LLVM's build due to undefined symbols.
1251 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001252 return !Context.getLangOptions().AppleKext ?
1253 llvm::GlobalVariable::LinkOnceODRLinkage :
1254 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001255 }
Douglas Gregordffb8012010-01-06 22:00:56 +00001256 }
1257
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001258 if (Context.getLangOptions().AppleKext)
1259 return llvm::Function::InternalLinkage;
1260
Douglas Gregordffb8012010-01-06 22:00:56 +00001261 switch (RD->getTemplateSpecializationKind()) {
1262 case TSK_Undeclared:
1263 case TSK_ExplicitSpecialization:
1264 case TSK_ImplicitInstantiation:
Douglas Gregordffb8012010-01-06 22:00:56 +00001265 // FIXME: Use available_externally linkage. However, this currently
1266 // breaks LLVM's build due to undefined symbols.
1267 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001268 case TSK_ExplicitInstantiationDeclaration:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001269 return llvm::GlobalVariable::LinkOnceODRLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001270
1271 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001272 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001273 }
1274
1275 // Silence GCC warning.
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001276 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001277}
1278
Chris Lattner2acc6e32011-07-18 04:24:23 +00001279CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck06f486e2011-01-18 02:01:14 +00001280 return Context.toCharUnitsFromBits(
1281 TheTargetData.getTypeStoreSizeInBits(Ty));
Ken Dyck687cc4a2010-01-26 13:48:07 +00001282}
1283
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001284void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +00001285 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +00001286 QualType ASTTy = D->getType();
Eli Friedman6c6bda32010-01-08 00:50:11 +00001287 bool NonConstInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Sebastian Redl31310a22010-02-01 20:16:42 +00001289 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlsson3bb92692010-01-26 17:43:42 +00001290
1291 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001292 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001293 // implicitly initialized with { 0 }.
1294 //
1295 // Note that tentative definitions are only emitted at the end of
1296 // a translation unit, so they should never have incomplete
1297 // type. In addition, EmitTentativeDefinition makes sure that we
1298 // never attempt to emit a tentative definition if a real one
1299 // exists. A use may still exists, however, so we still may need
1300 // to do a RAUW.
1301 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00001302 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00001303 } else {
Douglas Gregorc446d182010-05-05 20:15:55 +00001304 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman6e656f42009-02-20 01:18:21 +00001305 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00001306 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00001307 if (D->getType()->isReferenceType())
1308 T = D->getType();
1309
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001310 if (getLangOptions().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001311 Init = EmitNullConstant(T);
Eli Friedman6c6bda32010-01-08 00:50:11 +00001312 NonConstInit = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001313 } else {
1314 ErrorUnsupported(D, "static initializer");
1315 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1316 }
John McCallbf40cb52010-07-15 23:40:35 +00001317 } else {
1318 // We don't need an initializer, so remove the entry for the delayed
1319 // initializer position (just in case this entry was delayed).
1320 if (getLangOptions().CPlusPlus)
1321 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00001322 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001323 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001324
Chris Lattner2acc6e32011-07-18 04:24:23 +00001325 llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00001326 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00001327
Chris Lattner570585c2009-03-21 09:16:30 +00001328 // Strip off a bitcast if we got one back.
1329 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001330 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1331 // all zero index gep.
1332 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00001333 Entry = CE->getOperand(0);
1334 }
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Chris Lattner570585c2009-03-21 09:16:30 +00001336 // Entry is now either a Function or GlobalVariable.
1337 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Chris Lattner570585c2009-03-21 09:16:30 +00001339 // We have a definition after a declaration with the wrong type.
1340 // We must make a new GlobalVariable* and update everything that used OldGV
1341 // (a declaration or tentative definition) with the new GlobalVariable*
1342 // (which will be a definition).
1343 //
1344 // This happens if there is a prototype for a global (e.g.
1345 // "extern int x[];") and then a definition of a different type (e.g.
1346 // "int x[10];"). This also happens when an initializer has a different type
1347 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +00001348 if (GV == 0 ||
1349 GV->getType()->getElementType() != InitType ||
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001350 GV->getType()->getAddressSpace() !=
1351 getContext().getTargetAddressSpace(ASTTy)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001352
John McCallf746aa62010-03-19 23:29:14 +00001353 // Move the old entry aside so that we'll create a new one.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001354 Entry->setName(StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00001355
Chris Lattner570585c2009-03-21 09:16:30 +00001356 // Make a new global with the correct type, this is now guaranteed to work.
1357 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00001358
Eli Friedman77ba7082008-05-30 19:50:47 +00001359 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00001360 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001361 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00001362 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00001363
1364 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00001365 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00001366 }
Devang Patel8e53e722007-10-26 16:31:40 +00001367
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001368 if (D->hasAttr<AnnotateAttr>())
1369 AddGlobalAnnotations(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001370
Chris Lattner88a69ad2007-07-13 05:13:43 +00001371 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001372
1373 // If it is safe to mark the global 'constant', do so now.
1374 GV->setConstant(false);
Douglas Gregorda550742011-05-07 22:06:45 +00001375 if (!NonConstInit && DeclIsConstantGlobal(Context, D, true))
Chris Lattnere78b86f2009-08-05 05:20:29 +00001376 GV->setConstant(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Ken Dyck8b752f12010-01-27 17:10:57 +00001378 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001379
Chris Lattner88a69ad2007-07-13 05:13:43 +00001380 // Set the llvm linkage type as appropriate.
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001381 llvm::GlobalValue::LinkageTypes Linkage =
1382 GetLLVMLinkageVarDefinition(D, GV);
1383 GV->setLinkage(Linkage);
1384 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00001385 // common vars aren't constant even if declared const.
1386 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00001387
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001388 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00001389
John McCall3030eb82010-11-06 09:44:32 +00001390 // Emit the initializer function if necessary.
1391 if (NonConstInit)
1392 EmitCXXGlobalVarDeclInitFunc(D, GV);
1393
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001394 // Emit global variable debug information.
Eric Christopher73fb3502011-10-13 21:45:18 +00001395 if (CGDebugInfo *DI = getModuleDebugInfo())
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001396 DI->EmitGlobalVariable(GV, D);
Chris Lattner88a69ad2007-07-13 05:13:43 +00001397}
Reid Spencer5f016e22007-07-11 17:01:13 +00001398
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001399llvm::GlobalValue::LinkageTypes
1400CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1401 llvm::GlobalVariable *GV) {
1402 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1403 if (Linkage == GVA_Internal)
1404 return llvm::Function::InternalLinkage;
1405 else if (D->hasAttr<DLLImportAttr>())
1406 return llvm::Function::DLLImportLinkage;
1407 else if (D->hasAttr<DLLExportAttr>())
1408 return llvm::Function::DLLExportLinkage;
1409 else if (D->hasAttr<WeakAttr>()) {
1410 if (GV->isConstant())
1411 return llvm::GlobalVariable::WeakODRLinkage;
1412 else
1413 return llvm::GlobalVariable::WeakAnyLinkage;
1414 } else if (Linkage == GVA_TemplateInstantiation ||
1415 Linkage == GVA_ExplicitTemplateInstantiation)
John McCall99ace162011-04-12 01:46:54 +00001416 return llvm::GlobalVariable::WeakODRLinkage;
Eric Christophera6cf1e72010-12-02 02:45:55 +00001417 else if (!getLangOptions().CPlusPlus &&
1418 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1419 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001420 !D->hasExternalStorage() && !D->getInit() &&
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00001421 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1422 !D->getAttr<WeakImportAttr>()) {
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001423 // Thread local vars aren't considered common linkage.
1424 return llvm::GlobalVariable::CommonLinkage;
1425 }
1426 return llvm::GlobalVariable::ExternalLinkage;
1427}
1428
Chris Lattnerbdb01322009-05-05 06:16:31 +00001429/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1430/// implement a function with no prototype, e.g. "int foo() {}". If there are
1431/// existing call uses of the old function in the module, this adjusts them to
1432/// call the new function directly.
1433///
1434/// This is not just a cleanup: the always_inline pass requires direct calls to
1435/// functions to be able to inline them. If there is a bitcast in the way, it
1436/// won't inline them. Instcombine normally deletes these calls, but it isn't
1437/// run at -O0.
1438static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1439 llvm::Function *NewFn) {
1440 // If we're redefining a global as a function, don't transform it.
1441 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1442 if (OldFn == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Chris Lattner2acc6e32011-07-18 04:24:23 +00001444 llvm::Type *NewRetTy = NewFn->getReturnType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001445 SmallVector<llvm::Value*, 4> ArgList;
Chris Lattnerbdb01322009-05-05 06:16:31 +00001446
1447 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001448 UI != E; ) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001449 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001450 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1451 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif8670cd32010-07-28 09:19:33 +00001452 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
Gabor Greif35db3b92010-04-10 03:45:50 +00001453 llvm::CallSite CS(CI);
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001454 if (!CI || !CS.isCallee(I)) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Chris Lattnerbdb01322009-05-05 06:16:31 +00001456 // If the return types don't match exactly, and if the call isn't dead, then
1457 // we can't transform this call.
1458 if (CI->getType() != NewRetTy && !CI->use_empty())
1459 continue;
1460
John McCall40f9c302011-08-03 00:43:55 +00001461 // Get the attribute list.
1462 llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
1463 llvm::AttrListPtr AttrList = CI->getAttributes();
1464
1465 // Get any return attributes.
1466 llvm::Attributes RAttrs = AttrList.getRetAttributes();
1467
1468 // Add the return attributes.
1469 if (RAttrs)
1470 AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
1471
Chris Lattnerbdb01322009-05-05 06:16:31 +00001472 // If the function was passed too few arguments, don't transform. If extra
1473 // arguments were passed, we silently drop them. If any of the types
1474 // mismatch, we don't transform.
1475 unsigned ArgNo = 0;
1476 bool DontTransform = false;
1477 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1478 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greif35db3b92010-04-10 03:45:50 +00001479 if (CS.arg_size() == ArgNo ||
1480 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001481 DontTransform = true;
1482 break;
1483 }
John McCall40f9c302011-08-03 00:43:55 +00001484
1485 // Add any parameter attributes.
1486 if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
1487 AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
Chris Lattnerbdb01322009-05-05 06:16:31 +00001488 }
1489 if (DontTransform)
1490 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001491
John McCall40f9c302011-08-03 00:43:55 +00001492 if (llvm::Attributes FnAttrs = AttrList.getFnAttributes())
1493 AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
1494
Chris Lattnerbdb01322009-05-05 06:16:31 +00001495 // Okay, we can transform this. Create the new call instruction and copy
1496 // over the required information.
Gabor Greif6ba728d2010-04-10 02:56:12 +00001497 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001498 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001499 ArgList.clear();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001500 if (!NewCall->getType()->isVoidTy())
Chris Lattnerbdb01322009-05-05 06:16:31 +00001501 NewCall->takeName(CI);
John McCall40f9c302011-08-03 00:43:55 +00001502 NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(),
1503 AttrVec.end()));
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001504 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001505
1506 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner00549fc2009-10-14 05:49:21 +00001507 if (!CI->use_empty())
1508 CI->replaceAllUsesWith(NewCall);
Devang Patel3b122bc2009-10-13 17:02:04 +00001509
Chris Lattnerc6034632010-04-01 06:31:43 +00001510 // Copy debug location attached to CI.
1511 if (!CI->getDebugLoc().isUnknown())
1512 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001513 CI->eraseFromParent();
1514 }
1515}
1516
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001517
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001518void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001519 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalld26bc762011-03-09 04:27:21 +00001520
John McCall1f6f9612011-03-09 08:12:35 +00001521 // Compute the function info and LLVM type.
John McCalld26bc762011-03-09 04:27:21 +00001522 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
John McCall1f6f9612011-03-09 08:12:35 +00001523 bool variadic = false;
1524 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
1525 variadic = fpt->isVariadic();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001526 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic);
John McCalld26bc762011-03-09 04:27:21 +00001527
Chris Lattner9fa959d2009-05-12 20:58:15 +00001528 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001529 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Chris Lattner0558e792009-03-21 09:25:43 +00001531 // Strip off a bitcast if we got one back.
1532 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1533 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1534 Entry = CE->getOperand(0);
1535 }
Mike Stump1eb44332009-09-09 15:08:12 +00001536
1537
Chris Lattner0558e792009-03-21 09:25:43 +00001538 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001539 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Daniel Dunbar42745812009-03-09 23:53:08 +00001541 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001542 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +00001543 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00001544
Chris Lattner62b33ea2009-03-21 08:38:50 +00001545 // F is the Function* for the one with the wrong type, we must make a new
1546 // Function* and update everything that used F (a declaration) with the new
1547 // Function* (which will be a definition).
1548 //
1549 // This happens if there is a prototype for a function
1550 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00001551 // (e.g. "int f(int x)"). Move the old function aside so that it
1552 // doesn't interfere with GetAddrOfFunction.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001553 OldFn->setName(StringRef());
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001554 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Chris Lattnerbdb01322009-05-05 06:16:31 +00001556 // If this is an implementation of a function without a prototype, try to
1557 // replace any existing uses of the function (which may be calls) with uses
1558 // of the new function
Chris Lattner9fa959d2009-05-12 20:58:15 +00001559 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001560 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001561 OldFn->removeDeadConstantUsers();
1562 }
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Chris Lattner62b33ea2009-03-21 08:38:50 +00001564 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001565 if (!Entry->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001566 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001567 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001568 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1569 }
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Chris Lattner62b33ea2009-03-21 08:38:50 +00001571 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001572 OldFn->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Chris Lattner0558e792009-03-21 09:25:43 +00001574 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001575 }
Mike Stump1eb44332009-09-09 15:08:12 +00001576
John McCall112c9672010-11-02 21:04:24 +00001577 // We need to set linkage and visibility on the function before
1578 // generating code for it because various parts of IR generation
1579 // want to propagate this information down (e.g. to local static
1580 // declarations).
Chris Lattner0558e792009-03-21 09:25:43 +00001581 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall8b242332010-05-25 04:30:21 +00001582 setFunctionLinkage(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001583
John McCall112c9672010-11-02 21:04:24 +00001584 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlsson0ffeaad2011-01-29 19:39:23 +00001585 setGlobalVisibility(Fn, D);
John McCall112c9672010-11-02 21:04:24 +00001586
John McCalld26bc762011-03-09 04:27:21 +00001587 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00001588
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001589 SetFunctionDefinitionAttributes(D, Fn);
1590 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001592 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001593 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001594 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001595 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001596 if (D->hasAttr<AnnotateAttr>())
1597 AddGlobalAnnotations(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001598}
1599
John McCallf746aa62010-03-19 23:29:14 +00001600void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1601 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001602 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00001603 assert(AA && "Not an alias?");
1604
Chris Lattner5f9e2722011-07-23 10:55:15 +00001605 StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
John McCallf746aa62010-03-19 23:29:14 +00001607 // If there is a definition in the module, then it wins over the alias.
1608 // This is dubious, but allow it to be safe. Just ignore the alias.
1609 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1610 if (Entry && !Entry->isDeclaration())
1611 return;
1612
Chris Lattner2acc6e32011-07-18 04:24:23 +00001613 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00001614
1615 // Create a reference to the named value. This ensures that it is emitted
1616 // if a deferred decl.
1617 llvm::Constant *Aliasee;
1618 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001619 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1620 /*ForVTable=*/false);
Chris Lattnerbd532712009-03-22 21:47:11 +00001621 else
John McCallf746aa62010-03-19 23:29:14 +00001622 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson96e0fc72009-07-29 22:16:19 +00001623 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattnerbd532712009-03-22 21:47:11 +00001624
1625 // Create the new alias itself, but don't set a name yet.
Mike Stump1eb44332009-09-09 15:08:12 +00001626 llvm::GlobalValue *GA =
Chris Lattnerbd532712009-03-22 21:47:11 +00001627 new llvm::GlobalAlias(Aliasee->getType(),
1628 llvm::Function::ExternalLinkage,
1629 "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Chris Lattnerbd532712009-03-22 21:47:11 +00001631 if (Entry) {
John McCallf746aa62010-03-19 23:29:14 +00001632 assert(Entry->isDeclaration());
1633
Chris Lattnerbd532712009-03-22 21:47:11 +00001634 // If there is a declaration in the module, then we had an extern followed
1635 // by the alias, as in:
1636 // extern int test6();
1637 // ...
1638 // int test6() __attribute__((alias("test7")));
1639 //
1640 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00001641 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Owen Anderson3c4972d2009-07-29 18:54:39 +00001643 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00001644 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00001645 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00001646 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00001647 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00001648 }
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001650 // Set attributes which are particular to an alias; this is a
1651 // specialization of the attributes which may be set on a global
1652 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001653 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001654 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1655 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001656 if (FD->hasBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001657 GA->setLinkage(llvm::Function::DLLExportLinkage);
1658 } else {
1659 GA->setLinkage(llvm::Function::DLLExportLinkage);
1660 }
Mike Stump1eb44332009-09-09 15:08:12 +00001661 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindola11e8ce72010-02-23 22:00:30 +00001662 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001663 D->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001664 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1665 }
1666
1667 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00001668}
1669
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00001670llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00001671 ArrayRef<llvm::Type*> Tys) {
Jay Foaddf983a82011-07-12 14:06:48 +00001672 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00001673 Tys);
Chris Lattner7acda7c2007-12-18 00:25:38 +00001674}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001675
Daniel Dunbar1d552912009-07-23 22:52:48 +00001676static llvm::StringMapEntry<llvm::Constant*> &
1677GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1678 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001679 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00001680 bool &IsUTF16,
1681 unsigned &StringLength) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001682 StringRef String = Literal->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001683 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001684
Daniel Dunbarf015b032009-09-22 10:03:52 +00001685 // Check for simple case.
1686 if (!Literal->containsNonAsciiOrNull()) {
1687 StringLength = NumBytes;
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001688 return Map.GetOrCreateValue(String);
Daniel Dunbarf015b032009-09-22 10:03:52 +00001689 }
1690
Daniel Dunbar1d552912009-07-23 22:52:48 +00001691 // Otherwise, convert the UTF8 literals into a byte string.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001692 SmallVector<UTF16, 128> ToBuf(NumBytes);
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001693 const UTF8 *FromPtr = (UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001694 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00001696 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1697 &ToPtr, ToPtr + NumBytes,
1698 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001700 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00001701 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001702
1703 // Render the UTF-16 string into a byte array and convert to the target byte
1704 // order.
1705 //
1706 // FIXME: This isn't something we should need to do here.
1707 llvm::SmallString<128> AsBytes;
1708 AsBytes.reserve(StringLength * 2);
1709 for (unsigned i = 0; i != StringLength; ++i) {
1710 unsigned short Val = ToBuf[i];
1711 if (TargetIsLSB) {
1712 AsBytes.push_back(Val & 0xFF);
1713 AsBytes.push_back(Val >> 8);
1714 } else {
1715 AsBytes.push_back(Val >> 8);
1716 AsBytes.push_back(Val & 0xFF);
1717 }
1718 }
Daniel Dunbar434da482009-08-03 21:47:08 +00001719 // Append one extra null character, the second is automatically added by our
1720 // caller.
1721 AsBytes.push_back(0);
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001722
Daniel Dunbar1d552912009-07-23 22:52:48 +00001723 IsUTF16 = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001724 return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar1d552912009-07-23 22:52:48 +00001725}
1726
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001727static llvm::StringMapEntry<llvm::Constant*> &
1728GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1729 const StringLiteral *Literal,
1730 unsigned &StringLength)
1731{
Chris Lattner5f9e2722011-07-23 10:55:15 +00001732 StringRef String = Literal->getString();
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001733 StringLength = String.size();
1734 return Map.GetOrCreateValue(String);
1735}
1736
Daniel Dunbar1d552912009-07-23 22:52:48 +00001737llvm::Constant *
1738CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1739 unsigned StringLength = 0;
1740 bool isUTF16 = false;
1741 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00001742 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001743 getTargetData().isLittleEndian(),
1744 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Daniel Dunbar1d552912009-07-23 22:52:48 +00001746 if (llvm::Constant *C = Entry.getValue())
1747 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Owen Anderson0032b272009-08-13 21:57:51 +00001749 llvm::Constant *Zero =
1750 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001751 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001753 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00001754 if (!CFConstantStringClassRef) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001755 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001756 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001757 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001758 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001759 // Decay array -> ptr
1760 CFConstantStringClassRef =
Jay Foada5c04342011-07-21 14:31:17 +00001761 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001762 }
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Anders Carlssone3daa762008-11-15 18:54:24 +00001764 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001765
Chris Lattner2acc6e32011-07-18 04:24:23 +00001766 llvm::StructType *STy =
Anders Carlssone3daa762008-11-15 18:54:24 +00001767 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1768
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001769 llvm::Constant *Fields[4];
Douglas Gregor44b43212008-12-11 16:49:14 +00001770
Anders Carlssonc9e20912007-08-21 00:21:21 +00001771 // Class pointer.
Anders Carlsson5add6832009-08-16 05:55:31 +00001772 Fields[0] = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Anders Carlssonc9e20912007-08-21 00:21:21 +00001774 // Flags.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001775 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001776 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00001777 llvm::ConstantInt::get(Ty, 0x07C8);
1778
Anders Carlssonc9e20912007-08-21 00:21:21 +00001779 // String pointer.
Owen Anderson0032b272009-08-13 21:57:51 +00001780 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001781
Chris Lattner95b851e2009-07-16 05:03:48 +00001782 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001783 bool isConstant;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001784 if (isUTF16) {
Chris Lattner278b9f02009-10-14 05:55:45 +00001785 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner95b851e2009-07-16 05:03:48 +00001786 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001787 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1788 // does make plain ascii ones writable.
Daniel Dunbara9668e02009-04-03 00:57:44 +00001789 isConstant = true;
Chris Lattner278b9f02009-10-14 05:55:45 +00001790 } else {
Rafael Espindola584acf22011-03-14 17:55:00 +00001791 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1792 // when using private linkage. It is not clear if this is a bug in ld
1793 // or a reasonable new restriction.
Rafael Espindoladc0f1372011-03-14 21:08:19 +00001794 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001795 isConstant = !Features.WritableStrings;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001796 }
Chris Lattner278b9f02009-10-14 05:55:45 +00001797
Mike Stump1eb44332009-09-09 15:08:12 +00001798 llvm::GlobalVariable *GV =
Chris Lattner278b9f02009-10-14 05:55:45 +00001799 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1800 ".str");
Rafael Espindolab266a1f2011-01-17 16:31:00 +00001801 GV->setUnnamedAddr(true);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001802 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00001803 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1804 GV->setAlignment(Align.getQuantity());
Daniel Dunbarf7e903d2011-04-12 23:30:52 +00001805 } else {
1806 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1807 GV->setAlignment(Align.getQuantity());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001808 }
Jay Foada5c04342011-07-21 14:31:17 +00001809 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson5add6832009-08-16 05:55:31 +00001810
Anders Carlssonc9e20912007-08-21 00:21:21 +00001811 // String length.
1812 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00001813 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Anders Carlssonc9e20912007-08-21 00:21:21 +00001815 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00001816 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00001817 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1818 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00001819 "_unnamed_cfstring_");
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001820 if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001821 GV->setSection(Sect);
Daniel Dunbar1d552912009-07-23 22:52:48 +00001822 Entry.setValue(GV);
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Anders Carlsson0c678292007-11-01 00:41:52 +00001824 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001825}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001826
Douglas Gregor45c4ea72011-08-09 15:54:21 +00001827static RecordDecl *
1828CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
1829 DeclContext *DC, IdentifierInfo *Id) {
1830 SourceLocation Loc;
1831 if (Ctx.getLangOptions().CPlusPlus)
1832 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
1833 else
1834 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
1835}
1836
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001837llvm::Constant *
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001838CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001839 unsigned StringLength = 0;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001840 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001841 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001842
1843 if (llvm::Constant *C = Entry.getValue())
1844 return C;
1845
1846 llvm::Constant *Zero =
1847 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1848 llvm::Constant *Zeros[] = { Zero, Zero };
1849
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001850 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001851 if (!ConstantStringClassRef) {
1852 std::string StringClass(getLangOptions().ObjCConstantStringClass);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001853 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001854 llvm::Constant *GV;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00001855 if (Features.ObjCNonFragileABI) {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00001856 std::string str =
1857 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
1858 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00001859 GV = getObjCRuntime().GetClassGlobal(str);
1860 // Make sure the result is of the correct type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001861 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00001862 ConstantStringClassRef =
1863 llvm::ConstantExpr::getBitCast(GV, PTy);
1864 } else {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00001865 std::string str =
1866 StringClass.empty() ? "_NSConstantStringClassReference"
1867 : "_" + StringClass + "ClassReference";
Chris Lattner2acc6e32011-07-18 04:24:23 +00001868 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00001869 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00001870 // Decay array -> ptr
1871 ConstantStringClassRef =
Jay Foada5c04342011-07-21 14:31:17 +00001872 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001873 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001874 }
Douglas Gregor45c4ea72011-08-09 15:54:21 +00001875
1876 if (!NSConstantStringType) {
1877 // Construct the type for a constant NSString.
1878 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
1879 Context.getTranslationUnitDecl(),
1880 &Context.Idents.get("__builtin_NSString"));
1881 D->startDefinition();
1882
1883 QualType FieldTypes[3];
1884
1885 // const int *isa;
1886 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
1887 // const char *str;
1888 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
1889 // unsigned int length;
1890 FieldTypes[2] = Context.UnsignedIntTy;
1891
1892 // Create fields
1893 for (unsigned i = 0; i < 3; ++i) {
1894 FieldDecl *Field = FieldDecl::Create(Context, D,
1895 SourceLocation(),
1896 SourceLocation(), 0,
1897 FieldTypes[i], /*TInfo=*/0,
1898 /*BitWidth=*/0,
1899 /*Mutable=*/false,
1900 /*HasInit=*/false);
1901 Field->setAccess(AS_public);
1902 D->addDecl(Field);
1903 }
1904
1905 D->completeDefinition();
1906 QualType NSTy = Context.getTagDeclType(D);
1907 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1908 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001909
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001910 llvm::Constant *Fields[3];
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001911
1912 // Class pointer.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001913 Fields[0] = ConstantStringClassRef;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001914
1915 // String pointer.
1916 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1917
1918 llvm::GlobalValue::LinkageTypes Linkage;
1919 bool isConstant;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001920 Linkage = llvm::GlobalValue::PrivateLinkage;
1921 isConstant = !Features.WritableStrings;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001922
1923 llvm::GlobalVariable *GV =
1924 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1925 ".str");
Rafael Espindola803d3072011-01-17 22:11:21 +00001926 GV->setUnnamedAddr(true);
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00001927 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1928 GV->setAlignment(Align.getQuantity());
Jay Foada5c04342011-07-21 14:31:17 +00001929 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001930
1931 // String length.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001932 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001933 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1934
1935 // The struct.
Douglas Gregor45c4ea72011-08-09 15:54:21 +00001936 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001937 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1938 llvm::GlobalVariable::PrivateLinkage, C,
1939 "_unnamed_nsstring_");
1940 // FIXME. Fix section.
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001941 if (const char *Sect =
1942 Features.ObjCNonFragileABI
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001943 ? getContext().getTargetInfo().getNSStringNonFragileABISection()
1944 : getContext().getTargetInfo().getNSStringSection())
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001945 GV->setSection(Sect);
1946 Entry.setValue(GV);
1947
1948 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001949}
1950
Douglas Gregor0815b572011-08-09 17:23:49 +00001951QualType CodeGenModule::getObjCFastEnumerationStateType() {
1952 if (ObjCFastEnumerationStateType.isNull()) {
1953 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
1954 Context.getTranslationUnitDecl(),
1955 &Context.Idents.get("__objcFastEnumerationState"));
1956 D->startDefinition();
1957
1958 QualType FieldTypes[] = {
1959 Context.UnsignedLongTy,
1960 Context.getPointerType(Context.getObjCIdType()),
1961 Context.getPointerType(Context.UnsignedLongTy),
1962 Context.getConstantArrayType(Context.UnsignedLongTy,
1963 llvm::APInt(32, 5), ArrayType::Normal, 0)
1964 };
1965
1966 for (size_t i = 0; i < 4; ++i) {
1967 FieldDecl *Field = FieldDecl::Create(Context,
1968 D,
1969 SourceLocation(),
1970 SourceLocation(), 0,
1971 FieldTypes[i], /*TInfo=*/0,
1972 /*BitWidth=*/0,
1973 /*Mutable=*/false,
1974 /*HasInit=*/false);
1975 Field->setAccess(AS_public);
1976 D->addDecl(Field);
1977 }
1978
1979 D->completeDefinition();
1980 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
1981 }
1982
1983 return ObjCFastEnumerationStateType;
1984}
1985
Daniel Dunbar61432932008-08-13 23:20:05 +00001986/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001987/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001988std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Ken Dyck3b8037a2011-01-29 17:53:12 +00001989 const ASTContext &Context = getContext();
Daniel Dunbar1e049762008-08-10 20:25:57 +00001990 const ConstantArrayType *CAT =
Ken Dyck3b8037a2011-01-29 17:53:12 +00001991 Context.getAsConstantArrayType(E->getType());
Daniel Dunbar1e049762008-08-10 20:25:57 +00001992 assert(CAT && "String isn't pointer or array!");
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001994 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001995 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Douglas Gregor5cee1192011-07-27 05:40:30 +00001997 switch (E->getKind()) {
1998 case StringLiteral::Ascii:
1999 case StringLiteral::UTF8:
2000 break;
2001 case StringLiteral::Wide:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002002 RealLen *= Context.getTargetInfo().getWCharWidth() / Context.getCharWidth();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002003 break;
2004 case StringLiteral::UTF16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002005 RealLen *= Context.getTargetInfo().getChar16Width() / Context.getCharWidth();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002006 break;
2007 case StringLiteral::UTF32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002008 RealLen *= Context.getTargetInfo().getChar32Width() / Context.getCharWidth();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002009 break;
2010 }
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002012 std::string Str = E->getString().str();
Daniel Dunbar1e049762008-08-10 20:25:57 +00002013 Str.resize(RealLen, '\0');
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Daniel Dunbar1e049762008-08-10 20:25:57 +00002015 return Str;
2016}
2017
Daniel Dunbar61432932008-08-13 23:20:05 +00002018/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2019/// constant array for the given string literal.
2020llvm::Constant *
2021CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2022 // FIXME: This can be more efficient.
Eli Friedman7eb79c12009-11-16 05:55:46 +00002023 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
John McCalla5e19c62011-08-04 01:03:22 +00002024 CharUnits Align = getContext().getTypeAlignInChars(S->getType());
2025 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S),
2026 /* GlobalName */ 0,
2027 Align.getQuantity());
Douglas Gregor5cee1192011-07-27 05:40:30 +00002028 if (S->isWide() || S->isUTF16() || S->isUTF32()) {
Eli Friedman7eb79c12009-11-16 05:55:46 +00002029 llvm::Type *DestTy =
2030 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
2031 C = llvm::ConstantExpr::getBitCast(C, DestTy);
2032 }
2033 return C;
Daniel Dunbar61432932008-08-13 23:20:05 +00002034}
2035
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002036/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2037/// array for the given ObjCEncodeExpr node.
2038llvm::Constant *
2039CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2040 std::string Str;
2041 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00002042
2043 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002044}
2045
2046
Chris Lattnera7ad98f2008-02-11 00:02:17 +00002047/// GenerateWritableString -- Creates storage for a string literal.
John McCalla5e19c62011-08-04 01:03:22 +00002048static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002049 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00002050 CodeGenModule &CGM,
John McCalla5e19c62011-08-04 01:03:22 +00002051 const char *GlobalName,
2052 unsigned Alignment) {
Daniel Dunbar61432932008-08-13 23:20:05 +00002053 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson0032b272009-08-13 21:57:51 +00002054 llvm::Constant *C =
2055 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002057 // Create a global variable for this string
Rafael Espindola1257bc62011-01-10 22:34:03 +00002058 llvm::GlobalVariable *GV =
2059 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2060 llvm::GlobalValue::PrivateLinkage,
2061 C, GlobalName);
John McCalla5e19c62011-08-04 01:03:22 +00002062 GV->setAlignment(Alignment);
Rafael Espindola1257bc62011-01-10 22:34:03 +00002063 GV->setUnnamedAddr(true);
2064 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002065}
2066
Daniel Dunbar61432932008-08-13 23:20:05 +00002067/// GetAddrOfConstantString - Returns a pointer to a character array
2068/// containing the literal. This contents are exactly that of the
2069/// given string, i.e. it will not be null terminated automatically;
2070/// see GetAddrOfConstantCString. Note that whether the result is
2071/// actually a pointer to an LLVM constant depends on
2072/// Feature.WriteableStrings.
2073///
2074/// The result has pointer to array type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002075llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
John McCalla5e19c62011-08-04 01:03:22 +00002076 const char *GlobalName,
2077 unsigned Alignment) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002078 bool IsConstant = !Features.WritableStrings;
2079
2080 // Get the default prefix if a name wasn't specified.
2081 if (!GlobalName)
Chris Lattner95b851e2009-07-16 05:03:48 +00002082 GlobalName = ".str";
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002083
2084 // Don't share any string literals if strings aren't constant.
2085 if (!IsConstant)
John McCalla5e19c62011-08-04 01:03:22 +00002086 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002087
John McCalla5e19c62011-08-04 01:03:22 +00002088 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
Benjamin Kramer9de43422011-03-05 13:45:23 +00002089 ConstantStringMap.GetOrCreateValue(Str);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002090
John McCalla5e19c62011-08-04 01:03:22 +00002091 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2092 if (Alignment > GV->getAlignment()) {
2093 GV->setAlignment(Alignment);
2094 }
2095 return GV;
2096 }
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002097
2098 // Create a global variable for this.
John McCalla5e19c62011-08-04 01:03:22 +00002099 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, Alignment);
2100 Entry.setValue(GV);
2101 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002102}
Daniel Dunbar61432932008-08-13 23:20:05 +00002103
2104/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer9de43422011-03-05 13:45:23 +00002105/// array containing the literal and a terminating '\0'
Daniel Dunbar61432932008-08-13 23:20:05 +00002106/// character. The result has pointer to array type.
Benjamin Kramer9de43422011-03-05 13:45:23 +00002107llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
John McCalla5e19c62011-08-04 01:03:22 +00002108 const char *GlobalName,
2109 unsigned Alignment) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002110 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCalla5e19c62011-08-04 01:03:22 +00002111 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
Daniel Dunbar61432932008-08-13 23:20:05 +00002112}
Daniel Dunbar41071de2008-08-15 23:26:23 +00002113
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002114/// EmitObjCPropertyImplementations - Emit information for synthesized
2115/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00002116void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002117 ObjCImplementationDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00002118 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002119 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002120 ObjCPropertyImplDecl *PID = *i;
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002122 // Dynamic is just for type-checking.
2123 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2124 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2125
2126 // Determine which methods need to be implemented, some may have
2127 // been overridden. Note that ::isSynthesized is not the method
2128 // we want, that just indicates if the decl came from a
2129 // property. What we want to know is if the method is defined in
2130 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002131 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00002132 CodeGenFunction(*this).GenerateObjCGetter(
2133 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002134 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002135 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00002136 CodeGenFunction(*this).GenerateObjCSetter(
2137 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002138 }
2139 }
2140}
2141
John McCalle81ac692011-03-22 07:05:39 +00002142static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002143 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2144 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00002145 ivar; ivar = ivar->getNextIvar())
2146 if (ivar->getType().isDestructedType())
2147 return true;
2148
2149 return false;
2150}
2151
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002152/// EmitObjCIvarInitializations - Emit information for ivar initialization
2153/// for an implementation.
2154void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCalle81ac692011-03-22 07:05:39 +00002155 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2156 if (needsDestructMethod(D)) {
2157 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2158 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2159 ObjCMethodDecl *DTORMethod =
2160 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002161 cxxSelector, getContext().VoidTy, 0, D,
2162 /*isInstance=*/true, /*isVariadic=*/false,
2163 /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
2164 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCalle81ac692011-03-22 07:05:39 +00002165 D->addInstanceMethod(DTORMethod);
2166 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCallf85e1932011-06-15 23:02:42 +00002167 D->setHasCXXStructors(true);
John McCalle81ac692011-03-22 07:05:39 +00002168 }
2169
2170 // If the implementation doesn't have any ivar initializers, we don't need
2171 // a .cxx_construct.
David Chisnall827bbcc2011-03-17 14:19:08 +00002172 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002173 return;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002174
John McCalle81ac692011-03-22 07:05:39 +00002175 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2176 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002177 // The constructor returns 'self'.
2178 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2179 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00002180 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00002181 cxxSelector,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002182 getContext().getObjCIdType(), 0,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002183 D, /*isInstance=*/true,
2184 /*isVariadic=*/false,
2185 /*isSynthesized=*/true,
2186 /*isImplicitlyDeclared=*/true,
2187 /*isDefined=*/false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002188 ObjCMethodDecl::Required);
2189 D->addInstanceMethod(CTORMethod);
2190 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCallf85e1932011-06-15 23:02:42 +00002191 D->setHasCXXStructors(true);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002192}
2193
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002194/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00002195void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002196 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00002197 I != E; ++I)
2198 EmitTopLevelDecl(*I);
2199}
2200
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002201// EmitLinkageSpec - Emit all declarations in a linkage spec.
2202void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00002203 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2204 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002205 ErrorUnsupported(LSD, "linkage spec");
2206 return;
2207 }
2208
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002209 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002210 I != E; ++I)
2211 EmitTopLevelDecl(*I);
2212}
2213
Daniel Dunbar41071de2008-08-15 23:26:23 +00002214/// EmitTopLevelDecl - Emit code for a single top level declaration.
2215void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2216 // If an error has occurred, stop code generation, but continue
2217 // parsing and semantic analysis (to ensure all warnings and errors
2218 // are emitted).
2219 if (Diags.hasErrorOccurred())
2220 return;
2221
Douglas Gregor16e8be22009-06-29 17:30:29 +00002222 // Ignore dependent declarations.
2223 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2224 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Daniel Dunbar41071de2008-08-15 23:26:23 +00002226 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00002227 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00002228 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002229 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00002230 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002231 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2232 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor16e8be22009-06-29 17:30:29 +00002233 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002235 EmitGlobal(cast<FunctionDecl>(D));
2236 break;
2237
Daniel Dunbar41071de2008-08-15 23:26:23 +00002238 case Decl::Var:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002239 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002240 break;
2241
John McCall26fbc722011-04-12 01:01:22 +00002242 // Indirect fields from global anonymous structs and unions can be
2243 // ignored; only the actual variable requires IR gen support.
2244 case Decl::IndirectField:
2245 break;
2246
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002247 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00002248 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00002249 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002250 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002251 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00002252 case Decl::UsingShadow:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002253 case Decl::Using:
Douglas Gregordd9967a2009-09-02 23:49:23 +00002254 case Decl::UsingDirective:
Douglas Gregor127102b2009-06-29 20:59:39 +00002255 case Decl::ClassTemplate:
2256 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002257 case Decl::TypeAliasTemplate:
Anders Carlsson018837b2009-09-23 19:19:16 +00002258 case Decl::NamespaceAlias:
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002259 case Decl::Block:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002260 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002261 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002262 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002263 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2264 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002265 return;
2266
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002267 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2268 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002269 case Decl::CXXDestructor:
Francois Pichet8387e2a2011-04-22 22:18:13 +00002270 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2271 return;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002272 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2273 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00002274
2275 case Decl::StaticAssert:
2276 // Nothing to do.
2277 break;
2278
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002279 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00002281 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002282 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002283 case Decl::ObjCForwardProtocol:
Chris Lattner285d0db2009-04-01 02:36:43 +00002284 case Decl::ObjCInterface:
Chris Lattner285d0db2009-04-01 02:36:43 +00002285 break;
Fariborz Jahanian000835d2010-08-23 18:51:39 +00002286
Chris Lattnerbaf101d2011-04-09 07:11:53 +00002287 case Decl::ObjCCategory: {
2288 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2289 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2290 Context.ResetObjCLayout(CD->getClassInterface());
2291 break;
2292 }
Chris Lattner285d0db2009-04-01 02:36:43 +00002293
Daniel Dunbar41071de2008-08-15 23:26:23 +00002294 case Decl::ObjCProtocol:
Peter Collingbournee9265232011-07-27 20:29:46 +00002295 ObjCRuntime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002296 break;
2297
2298 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002299 // Categories have properties but don't support synthesize so we
2300 // can ignore them here.
Peter Collingbournee9265232011-07-27 20:29:46 +00002301 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002302 break;
2303
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002304 case Decl::ObjCImplementation: {
2305 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
Fariborz Jahanian000835d2010-08-23 18:51:39 +00002306 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2307 Context.ResetObjCLayout(OMD->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002308 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002309 EmitObjCIvarInitializations(OMD);
Peter Collingbournee9265232011-07-27 20:29:46 +00002310 ObjCRuntime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00002311 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002312 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00002313 case Decl::ObjCMethod: {
2314 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2315 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002316 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00002317 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2318 break;
2319 }
Mike Stump1eb44332009-09-09 15:08:12 +00002320 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00002321 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002322 break;
2323
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002324 case Decl::LinkageSpec:
2325 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002326 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00002327
2328 case Decl::FileScopeAsm: {
2329 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002330 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Daniel Dunbar41071de2008-08-15 23:26:23 +00002332 const std::string &S = getModule().getModuleInlineAsm();
2333 if (S.empty())
2334 getModule().setModuleInlineAsm(AsmString);
Chris Lattner9f5bff02011-07-23 20:04:25 +00002335 else if (*--S.end() == '\n')
2336 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002337 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00002338 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002339 break;
2340 }
Mike Stump1eb44332009-09-09 15:08:12 +00002341
2342 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00002343 // Make sure we handled everything we should, every other kind is a
2344 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2345 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002346 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2347 }
2348}
John McCall744016d2010-07-06 23:57:41 +00002349
2350/// Turns the given pointer into a constant.
2351static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2352 const void *Ptr) {
2353 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002354 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall744016d2010-07-06 23:57:41 +00002355 return llvm::ConstantInt::get(i64, PtrInt);
2356}
2357
2358static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2359 llvm::NamedMDNode *&GlobalMetadata,
2360 GlobalDecl D,
2361 llvm::GlobalValue *Addr) {
2362 if (!GlobalMetadata)
2363 GlobalMetadata =
2364 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2365
2366 // TODO: should we report variant information for ctors/dtors?
2367 llvm::Value *Ops[] = {
2368 Addr,
2369 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2370 };
Jay Foad6f141652011-04-21 19:59:12 +00002371 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall744016d2010-07-06 23:57:41 +00002372}
2373
2374/// Emits metadata nodes associating all the global values in the
2375/// current module with the Decls they came from. This is useful for
2376/// projects using IR gen as a subroutine.
2377///
2378/// Since there's currently no way to associate an MDNode directly
2379/// with an llvm::GlobalValue, we create a global named metadata
2380/// with the name 'clang.global.decl.ptrs'.
2381void CodeGenModule::EmitDeclMetadata() {
2382 llvm::NamedMDNode *GlobalMetadata = 0;
2383
2384 // StaticLocalDeclMap
Chris Lattner5f9e2722011-07-23 10:55:15 +00002385 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
John McCall744016d2010-07-06 23:57:41 +00002386 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2387 I != E; ++I) {
2388 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2389 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2390 }
2391}
2392
2393/// Emits metadata nodes for all the local variables in the current
2394/// function.
2395void CodeGenFunction::EmitDeclMetadata() {
2396 if (LocalDeclMap.empty()) return;
2397
2398 llvm::LLVMContext &Context = getLLVMContext();
2399
2400 // Find the unique metadata ID for this name.
2401 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2402
2403 llvm::NamedMDNode *GlobalMetadata = 0;
2404
2405 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2406 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2407 const Decl *D = I->first;
2408 llvm::Value *Addr = I->second;
2409
2410 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2411 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foad6f141652011-04-21 19:59:12 +00002412 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall744016d2010-07-06 23:57:41 +00002413 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2414 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2415 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2416 }
2417 }
2418}
Daniel Dunbar673431a2010-07-16 00:00:15 +00002419
Nick Lewycky3dc05412011-05-05 00:08:20 +00002420void CodeGenModule::EmitCoverageFile() {
2421 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002422 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2423 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2424 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky3dc05412011-05-05 00:08:20 +00002425 llvm::MDString *CoverageFile =
2426 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002427 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2428 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky3dc05412011-05-05 00:08:20 +00002429 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002430 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2431 GCov->addOperand(N);
2432 }
2433 }
2434 }
2435}