blob: 49c0b35df9af1b01687ca4ad421d08a9f8d9fec6 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Chris Lattner984fac52009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000016#include "CodeGenFunction.h"
Dan Gohman947c9af2010-10-14 23:06:10 +000017#include "CodeGenTBAA.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CGCall.h"
John McCall5d865c322010-08-31 07:33:07 +000019#include "CGCXXABI.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000021#include "TargetInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000022#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000023#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000024#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000026#include "clang/AST/DeclCXX.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000027#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000029#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000031#include "clang/Basic/Diagnostic.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000032#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000033#include "clang/Basic/TargetInfo.h"
Steve Naroff29cae662009-04-01 15:50:34 +000034#include "clang/Basic/ConvertUTF.h"
Nate Begemanaca747a2008-03-09 03:09:36 +000035#include "llvm/CallingConv.h"
Chris Lattner1eec6602007-08-31 04:31:45 +000036#include "llvm/Module.h"
Chris Lattner09153c02007-06-22 18:48:09 +000037#include "llvm/Intrinsics.h"
Chris Lattner5e124bf2009-12-28 21:44:41 +000038#include "llvm/LLVMContext.h"
John McCallbeec5a02010-03-06 00:35:14 +000039#include "llvm/ADT/Triple.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000040#include "llvm/Target/TargetData.h"
Gabor Greifd0ef1342010-04-10 02:56:12 +000041#include "llvm/Support/CallSite.h"
Chris Lattner15275e52009-11-07 09:22:46 +000042#include "llvm/Support/ErrorHandling.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000043using namespace clang;
44using namespace CodeGen;
45
John McCall614dbdc2010-08-22 21:01:12 +000046static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
47 switch (CGM.getContext().Target.getCXXABI()) {
48 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
49 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
50 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
51 }
52
53 llvm_unreachable("invalid C++ ABI kind");
54 return *CreateItaniumCXXABI(CGM);
55}
56
Chris Lattnerbed31442007-05-28 01:07:47 +000057
Chandler Carruthbc55fe22009-11-12 17:24:48 +000058CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall731be662010-03-04 04:29:44 +000059 llvm::Module &M, const llvm::TargetData &TD,
60 Diagnostic &diags)
Chris Lattner984fac52009-03-26 05:00:52 +000061 : BlockModule(C, M, TD, Types, *this), Context(C),
Chandler Carruthbc55fe22009-11-12 17:24:48 +000062 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall731be662010-03-04 04:29:44 +000063 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCall614dbdc2010-08-22 21:01:12 +000064 ABI(createCXXABI(*this)),
65 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
Dan Gohman947c9af2010-10-14 23:06:10 +000066 TBAA(0),
John McCall614dbdc2010-08-22 21:01:12 +000067 VTables(*this), Runtime(0),
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000068 CFConstantStringClassRef(0), ConstantStringClassRef(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000069 VMContext(M.getContext()),
Daniel Dunbar3348e2d2010-07-16 00:00:19 +000070 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000071 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
Daniel Dunbar3348e2d2010-07-16 00:00:19 +000072 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000073 BlockObjectAssign(0), BlockObjectDispose(0){
Daniel Dunbar8d480592008-08-11 18:12:00 +000074
Chris Lattner36376522009-03-21 07:12:05 +000075 if (!Features.ObjC1)
76 Runtime = 0;
77 else if (!Features.NeXTRuntime)
78 Runtime = CreateGNUObjCRuntime(*this);
79 else if (Features.ObjCNonFragileABI)
80 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
81 else
82 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000083
Dan Gohman947c9af2010-10-14 23:06:10 +000084 // Enable TBAA unless it's suppressed.
85 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
Dan Gohman2e29eb52010-10-15 20:23:12 +000086 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
87 ABI.getMangleContext());
Dan Gohman947c9af2010-10-14 23:06:10 +000088
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000089 // If debug info generation is enabled, create the CGDebugInfo object.
Anders Carlsson3efc6e62009-12-06 18:00:51 +000090 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
Chris Lattnera087ff92008-03-01 08:45:05 +000091}
92
93CodeGenModule::~CodeGenModule() {
Ted Kremenek2c674f62008-08-05 18:50:11 +000094 delete Runtime;
John McCall614dbdc2010-08-22 21:01:12 +000095 delete &ABI;
Dan Gohmand19ee8a2010-10-15 18:04:46 +000096 delete TBAA;
Ted Kremenek2c674f62008-08-05 18:50:11 +000097 delete DebugInfo;
98}
99
David Chisnall481e3a82010-01-23 02:40:42 +0000100void CodeGenModule::createObjCRuntime() {
101 if (!Features.NeXTRuntime)
102 Runtime = CreateGNUObjCRuntime(*this);
103 else if (Features.ObjCNonFragileABI)
104 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
105 else
106 Runtime = CreateMacObjCRuntime(*this);
107}
108
Ted Kremenek2c674f62008-08-05 18:50:11 +0000109void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000110 EmitDeferred();
Eli Friedman5866fe32010-01-08 00:50:11 +0000111 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000112 EmitCXXGlobalDtorFunc();
Daniel Dunbar8d480592008-08-11 18:12:00 +0000113 if (Runtime)
114 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
115 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000116 EmitCtorList(GlobalCtors, "llvm.global_ctors");
117 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman7fab5782008-04-18 23:43:57 +0000118 EmitAnnotations();
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000119 EmitLLVMUsed();
John McCall09ae0322010-07-06 23:57:41 +0000120
John McCall0bdb1fd2010-09-16 06:16:50 +0000121 SimplifyPersonality();
122
John McCall09ae0322010-07-06 23:57:41 +0000123 if (getCodeGenOpts().EmitDeclMetadata)
124 EmitDeclMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000125}
126
Dan Gohman947c9af2010-10-14 23:06:10 +0000127llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
128 if (!TBAA)
129 return 0;
130 return TBAA->getTBAAInfo(QTy);
131}
132
133void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
134 llvm::MDNode *TBAAInfo) {
135 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
136}
137
John McCallbeec5a02010-03-06 00:35:14 +0000138bool CodeGenModule::isTargetDarwin() const {
139 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
140}
141
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000142/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000143/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000144void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
145 bool OmitOnError) {
146 if (OmitOnError && getDiags().hasErrorOccurred())
147 return;
Mike Stump11289f42009-09-09 15:08:12 +0000148 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000149 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000150 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000151 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
152 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000153}
Chris Lattner41af8182007-12-02 06:27:33 +0000154
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000155/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000156/// specified decl yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000157void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
158 bool OmitOnError) {
159 if (OmitOnError && getDiags().hasErrorOccurred())
160 return;
Mike Stump11289f42009-09-09 15:08:12 +0000161 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000162 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000163 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000164 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000165}
166
John McCall37bb6c92010-10-29 22:22:43 +0000167static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
168 switch (V) {
169 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
170 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
171 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
172 }
173 llvm_unreachable("unknown visibility!");
174 return llvm::GlobalValue::DefaultVisibility;
175}
176
177
Mike Stump11289f42009-09-09 15:08:12 +0000178void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000179 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000180 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000181 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000182 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000183 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000184 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000185
John McCallc273f242010-10-30 11:50:40 +0000186 // Set visibility for definitions.
187 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Anders Carlssonc6a47892011-01-29 19:39:23 +0000188 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
John McCallc273f242010-10-30 11:50:40 +0000189 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000190}
191
John McCalle16adc22010-08-04 08:34:44 +0000192/// Set the symbol visibility of type information (vtable and RTTI)
193/// associated with the given type.
194void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
195 const CXXRecordDecl *RD,
Anders Carlssonfd483402011-01-29 05:26:32 +0000196 bool IsForRTTI) const {
Anders Carlssonc6a47892011-01-29 19:39:23 +0000197 setGlobalVisibility(GV, RD);
John McCalle16adc22010-08-04 08:34:44 +0000198
John McCallb3732bb2010-08-12 23:36:15 +0000199 if (!CodeGenOpts.HiddenWeakVTables)
200 return;
201
John McCalle16adc22010-08-04 08:34:44 +0000202 // We want to drop the visibility to hidden for weak type symbols.
203 // This isn't possible if there might be unresolved references
204 // elsewhere that rely on this symbol being visible.
205
John McCall5513fce92010-08-05 20:39:18 +0000206 // This should be kept roughly in sync with setThunkVisibility
207 // in CGVTables.cpp.
208
John McCalle16adc22010-08-04 08:34:44 +0000209 // Preconditions.
Anders Carlsson571e2ad2011-01-24 00:46:19 +0000210 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCalle16adc22010-08-04 08:34:44 +0000211 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
212 return;
213
214 // Don't override an explicit visibility attribute.
215 if (RD->hasAttr<VisibilityAttr>())
216 return;
217
218 switch (RD->getTemplateSpecializationKind()) {
219 // We have to disable the optimization if this is an EI definition
220 // because there might be EI declarations in other shared objects.
221 case TSK_ExplicitInstantiationDefinition:
222 case TSK_ExplicitInstantiationDeclaration:
223 return;
224
John McCall5513fce92010-08-05 20:39:18 +0000225 // Every use of a non-template class's type information has to emit it.
John McCalle16adc22010-08-04 08:34:44 +0000226 case TSK_Undeclared:
227 break;
228
John McCall5513fce92010-08-05 20:39:18 +0000229 // In theory, implicit instantiations can ignore the possibility of
230 // an explicit instantiation declaration because there necessarily
231 // must be an EI definition somewhere with default visibility. In
232 // practice, it's possible to have an explicit instantiation for
233 // an arbitrary template class, and linkers aren't necessarily able
234 // to deal with mixed-visibility symbols.
235 case TSK_ExplicitSpecialization:
John McCalle16adc22010-08-04 08:34:44 +0000236 case TSK_ImplicitInstantiation:
John McCallb3732bb2010-08-12 23:36:15 +0000237 if (!CodeGenOpts.HiddenWeakTemplateVTables)
John McCall5513fce92010-08-05 20:39:18 +0000238 return;
John McCalle16adc22010-08-04 08:34:44 +0000239 break;
240 }
241
242 // If there's a key function, there may be translation units
243 // that don't have the key function's definition. But ignore
244 // this if we're emitting RTTI under -fno-rtti.
245 if (!IsForRTTI || Features.RTTI)
246 if (Context.getKeyFunction(RD))
247 return;
248
249 // Otherwise, drop the visibility to hidden.
250 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1e879c2011-01-11 21:44:37 +0000251 GV->setUnnamedAddr(true);
John McCalle16adc22010-08-04 08:34:44 +0000252}
253
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000254llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
255 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
256
257 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
258 if (!Str.empty())
259 return Str;
260
John McCall5d865c322010-08-31 07:33:07 +0000261 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000262 IdentifierInfo *II = ND->getIdentifier();
263 assert(II && "Attempt to mangle unnamed decl.");
264
265 Str = II->getName();
266 return Str;
267 }
268
269 llvm::SmallString<256> Buffer;
270 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
John McCall5d865c322010-08-31 07:33:07 +0000271 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000272 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
John McCall5d865c322010-08-31 07:33:07 +0000273 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000274 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000275 getCXXABI().getMangleContext().mangleBlock(BD, Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000276 else
John McCall5d865c322010-08-31 07:33:07 +0000277 getCXXABI().getMangleContext().mangleName(ND, Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000278
279 // Allocate space for the mangled name.
280 size_t Length = Buffer.size();
281 char *Name = MangledNamesAllocator.Allocate<char>(Length);
282 std::copy(Buffer.begin(), Buffer.end(), Name);
283
284 Str = llvm::StringRef(Name, Length);
285
286 return Str;
287}
288
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000289void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
290 const BlockDecl *BD) {
291 MangleContext &MangleCtx = getCXXABI().getMangleContext();
292 const Decl *D = GD.getDecl();
293 if (D == 0)
294 MangleCtx.mangleGlobalBlock(BD, Buffer.getBuffer());
295 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
296 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Buffer.getBuffer());
297 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
298 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Buffer.getBuffer());
299 else
300 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Buffer.getBuffer());
Anders Carlsson635186a2010-06-09 02:36:32 +0000301}
302
John McCall7ec50432010-03-19 23:29:14 +0000303llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
304 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000305}
306
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000307/// AddGlobalCtor - Add a function to the list that will be called before
308/// main() runs.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000309void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000310 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000311 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000312}
313
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000314/// AddGlobalDtor - Add a function to the list that will be called
315/// when the module is unloaded.
316void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000317 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000318 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
319}
320
321void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
322 // Ctor function type is void()*.
323 llvm::FunctionType* CtorFTy =
Benjamin Kramer1e188892011-01-22 12:15:57 +0000324 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000325 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000326
327 // Get the type of a ctor entry, { i32, void ()* }.
Mike Stump11289f42009-09-09 15:08:12 +0000328 llvm::StructType* CtorStructTy =
329 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
Owen Anderson9793f0e2009-07-29 22:16:19 +0000330 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000331
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000332 // Construct the constructor and destructor arrays.
333 std::vector<llvm::Constant*> Ctors;
334 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
335 std::vector<llvm::Constant*> S;
Mike Stump11289f42009-09-09 15:08:12 +0000336 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson41a75022009-08-13 21:57:51 +0000337 I->second, false));
Owen Andersonade90fd2009-07-29 18:54:39 +0000338 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson0e0189d2009-07-27 22:29:56 +0000339 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000340 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000341
342 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000343 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000344 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000345 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000346 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000347 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000348 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000349}
350
Nate Begeman7fab5782008-04-18 23:43:57 +0000351void CodeGenModule::EmitAnnotations() {
352 if (Annotations.empty())
353 return;
354
355 // Create a new global variable for the ConstantStruct in the Module.
356 llvm::Constant *Array =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000357 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
Nate Begeman7fab5782008-04-18 23:43:57 +0000358 Annotations.size()),
359 Annotations);
Mike Stump11289f42009-09-09 15:08:12 +0000360 llvm::GlobalValue *gv =
361 new llvm::GlobalVariable(TheModule, Array->getType(), false,
362 llvm::GlobalValue::AppendingLinkage, Array,
Owen Andersonc10c8d32009-07-08 19:05:04 +0000363 "llvm.global.annotations");
Nate Begeman7fab5782008-04-18 23:43:57 +0000364 gv->setSection("llvm.metadata");
365}
366
John McCalld4324142010-02-19 01:32:20 +0000367llvm::GlobalValue::LinkageTypes
368CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000369 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000370
Chris Lattner749b8ed2010-06-30 16:58:07 +0000371 if (Linkage == GVA_Internal)
John McCalld4324142010-02-19 01:32:20 +0000372 return llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000373
374 if (D->hasAttr<DLLExportAttr>())
John McCalld4324142010-02-19 01:32:20 +0000375 return llvm::Function::DLLExportLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000376
377 if (D->hasAttr<WeakAttr>())
John McCalld4324142010-02-19 01:32:20 +0000378 return llvm::Function::WeakAnyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000379
380 // In C99 mode, 'inline' functions are guaranteed to have a strong
381 // definition somewhere else, so we can use available_externally linkage.
382 if (Linkage == GVA_C99Inline)
John McCalld4324142010-02-19 01:32:20 +0000383 return llvm::Function::AvailableExternallyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000384
385 // In C++, the compiler has to emit a definition in every translation unit
386 // that references the function. We should use linkonce_odr because
387 // a) if all references in this translation unit are optimized away, we
388 // don't need to codegen it. b) if the function persists, it needs to be
389 // merged with other definitions. c) C++ has the ODR, so we know the
390 // definition is dependable.
391 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
John McCalld4324142010-02-19 01:32:20 +0000392 return llvm::Function::LinkOnceODRLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000393
394 // An explicit instantiation of a template has weak linkage, since
395 // explicit instantiations can occur in multiple translation units
396 // and must all be equivalent. However, we are not allowed to
397 // throw away these explicit instantiations.
398 if (Linkage == GVA_ExplicitTemplateInstantiation)
Douglas Gregorb14d1232010-03-13 18:23:07 +0000399 return llvm::Function::WeakODRLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000400
401 // Otherwise, we have strong external linkage.
402 assert(Linkage == GVA_StrongExternal);
403 return llvm::Function::ExternalLinkage;
John McCalld4324142010-02-19 01:32:20 +0000404}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000405
John McCalld4324142010-02-19 01:32:20 +0000406
407/// SetFunctionDefinitionAttributes - Set attributes for a global.
408///
409/// FIXME: This is currently only done for aliases and functions, but not for
410/// variables (these details are set in EmitGlobalVarDefinition for variables).
411void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
412 llvm::GlobalValue *GV) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000413 SetCommonAttributes(D, GV);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000414}
415
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000416void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000417 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000418 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000419 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000420 AttributeListType AttributeList;
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000421 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel322300d2008-09-25 21:02:23 +0000422 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000423 AttributeList.size()));
424 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000425}
426
Daniel Dunbar38932572009-04-14 08:05:55 +0000427void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
428 llvm::Function *F) {
Daniel Dunbar0f3403c2009-03-02 04:58:03 +0000429 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Mike Stump11289f42009-09-09 15:08:12 +0000430 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000431
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000432 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbar03a38442008-10-28 00:17:57 +0000433 F->addFnAttr(llvm::Attribute::AlwaysInline);
Mike Stump11289f42009-09-09 15:08:12 +0000434
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000435 if (D->hasAttr<NakedAttr>())
436 F->addFnAttr(llvm::Attribute::Naked);
437
Mike Stump3722f582009-08-26 22:31:08 +0000438 if (D->hasAttr<NoInlineAttr>())
Anders Carlssonf96954c2009-02-19 19:22:11 +0000439 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpc5e153c2009-10-05 21:58:44 +0000440
Rafael Espindola0ee986c1f2011-01-11 00:26:26 +0000441 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
442 F->setUnnamedAddr(true);
443
Anders Carlsson0d82fa62009-11-16 16:56:03 +0000444 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
445 F->addFnAttr(llvm::Attribute::StackProtect);
446 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
447 F->addFnAttr(llvm::Attribute::StackProtectReq);
448
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000449 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
450 if (alignment)
451 F->setAlignment(alignment);
452
Mike Stump3472ae52009-10-05 22:49:20 +0000453 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000454 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
455 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000456}
457
Mike Stump11289f42009-09-09 15:08:12 +0000458void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000459 llvm::GlobalValue *GV) {
John McCall457a04e2010-10-22 21:05:15 +0000460 if (isa<NamedDecl>(D))
Anders Carlssonc6a47892011-01-29 19:39:23 +0000461 setGlobalVisibility(GV, cast<NamedDecl>(D));
John McCall457a04e2010-10-22 21:05:15 +0000462 else
463 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +0000464
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000465 if (D->hasAttr<UsedAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000466 AddUsedGlobal(GV);
467
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000468 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000469 GV->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000470
471 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000472}
473
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000474void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
475 llvm::Function *F,
476 const CGFunctionInfo &FI) {
477 SetLLVMFunctionAttributes(D, FI, F);
478 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000479
480 F->setLinkage(llvm::Function::InternalLinkage);
481
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000482 SetCommonAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000483}
484
Anders Carlsson6710c532010-02-06 02:44:09 +0000485void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000486 llvm::Function *F,
487 bool IsIncompleteFunction) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000488 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
489
Eli Friedman895771a2009-05-26 01:22:57 +0000490 if (!IsIncompleteFunction)
Anders Carlsson6710c532010-02-06 02:44:09 +0000491 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000492
Daniel Dunbar38932572009-04-14 08:05:55 +0000493 // Only a few attributes are set on declarations; these may later be
494 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000495
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000496 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000497 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump11289f42009-09-09 15:08:12 +0000498 } else if (FD->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000499 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000500 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump11289f42009-09-09 15:08:12 +0000501 // separate linkage types for this.
Daniel Dunbar38932572009-04-14 08:05:55 +0000502 F->setLinkage(llvm::Function::ExternalWeakLinkage);
503 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000504 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallc273f242010-10-30 11:50:40 +0000505
506 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
507 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
508 F->setVisibility(GetLLVMVisibility(LV.visibility()));
509 }
Daniel Dunbar38932572009-04-14 08:05:55 +0000510 }
511
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000512 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000513 F->setSection(SA->getName());
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000514}
515
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000516void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000517 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000518 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000519 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000520}
521
522void CodeGenModule::EmitLLVMUsed() {
523 // Don't create llvm.used if there is no need.
Chris Lattnerf56501c2009-07-17 23:57:13 +0000524 if (LLVMUsed.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000525 return;
526
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000527 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000529 // Convert LLVMUsed to what ConstantArray needs.
530 std::vector<llvm::Constant*> UsedArray;
531 UsedArray.resize(LLVMUsed.size());
532 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000533 UsedArray[i] =
534 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Anderson170229f2009-07-14 23:10:40 +0000535 i8PTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000538 if (UsedArray.empty())
539 return;
Owen Anderson9793f0e2009-07-29 22:16:19 +0000540 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000541
542 llvm::GlobalVariable *GV =
543 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000544 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000545 llvm::ConstantArray::get(ATy, UsedArray),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000546 "llvm.used");
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000547
548 GV->setSection("llvm.metadata");
549}
550
551void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +0000552 // Emit code for any potentially referenced deferred decls. Since a
553 // previously unused static decl may become used during the generation of code
554 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000555
Anders Carlsson11e51402010-04-17 20:15:18 +0000556 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
557 if (!DeferredVTables.empty()) {
558 const CXXRecordDecl *RD = DeferredVTables.back();
559 DeferredVTables.pop_back();
560 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000561 continue;
562 }
563
Anders Carlssondae1abc2009-05-05 04:44:02 +0000564 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner45470942009-03-21 09:44:56 +0000565 DeferredDeclsToEmit.pop_back();
566
John McCallc2af9392010-05-27 01:45:30 +0000567 // Check to see if we've already emitted this. This is necessary
568 // for a couple of reasons: first, decls can end up in the
569 // deferred-decls queue multiple times, and second, decls can end
570 // up with definitions in unusual ways (e.g. by an extern inline
571 // function acquiring a strong function redefinition). Just
572 // ignore these cases.
573 //
574 // TODO: That said, looking this up multiple times is very wasteful.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000575 llvm::StringRef Name = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +0000576 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner45470942009-03-21 09:44:56 +0000577 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump11289f42009-09-09 15:08:12 +0000578
Chris Lattner45470942009-03-21 09:44:56 +0000579 if (!CGRef->isDeclaration())
580 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000581
John McCallc2af9392010-05-27 01:45:30 +0000582 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
583 // purposes an alias counts as a definition.
584 if (isa<llvm::GlobalAlias>(CGRef))
585 continue;
586
Chris Lattner45470942009-03-21 09:44:56 +0000587 // Otherwise, emit the definition and move on to the next one.
588 EmitGlobalDefinition(D);
589 }
Chris Lattnerbed31442007-05-28 01:07:47 +0000590}
Chris Lattner09153c02007-06-22 18:48:09 +0000591
Mike Stump11289f42009-09-09 15:08:12 +0000592/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
Nate Begemanfaae0812008-04-19 04:17:09 +0000593/// annotation information for a given GlobalValue. The annotation struct is
Mike Stump11289f42009-09-09 15:08:12 +0000594/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
595/// GlobalValue being annotated. The second field is the constant string
596/// created from the AnnotateAttr's annotation. The third field is a constant
Nate Begemanfaae0812008-04-19 04:17:09 +0000597/// string containing the name of the translation unit. The fourth field is
598/// the line number in the file of the annotated value declaration.
599///
600/// FIXME: this does not unique the annotation string constants, as llvm-gcc
601/// appears to.
602///
Mike Stump11289f42009-09-09 15:08:12 +0000603llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +0000604 const AnnotateAttr *AA,
605 unsigned LineNo) {
606 llvm::Module *M = &getModule();
607
608 // get [N x i8] constants for the annotation string, and the filename string
609 // which are the 2nd and 3rd elements of the global annotation structure.
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000610 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000611 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000612 AA->getAnnotation(), true);
613 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
614 M->getModuleIdentifier(),
Nate Begemanfaae0812008-04-19 04:17:09 +0000615 true);
616
617 // Get the two global values corresponding to the ConstantArrays we just
618 // created to hold the bytes of the strings.
Mike Stump11289f42009-09-09 15:08:12 +0000619 llvm::GlobalValue *annoGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000620 new llvm::GlobalVariable(*M, anno->getType(), false,
621 llvm::GlobalValue::PrivateLinkage, anno,
622 GV->getName());
Nate Begemanfaae0812008-04-19 04:17:09 +0000623 // translation unit name string, emitted into the llvm.metadata section.
624 llvm::GlobalValue *unitGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000625 new llvm::GlobalVariable(*M, unit->getType(), false,
Mike Stump11289f42009-09-09 15:08:12 +0000626 llvm::GlobalValue::PrivateLinkage, unit,
Chris Lattner3afa3e12009-07-16 05:03:48 +0000627 ".str");
Rafael Espindola2e217d62011-01-17 22:22:52 +0000628 unitGV->setUnnamedAddr(true);
Nate Begemanfaae0812008-04-19 04:17:09 +0000629
Daniel Dunbar346892a2009-04-14 22:41:13 +0000630 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +0000631 llvm::Constant *Fields[4] = {
Owen Andersonade90fd2009-07-29 18:54:39 +0000632 llvm::ConstantExpr::getBitCast(GV, SBP),
633 llvm::ConstantExpr::getBitCast(annoGV, SBP),
634 llvm::ConstantExpr::getBitCast(unitGV, SBP),
Owen Anderson41a75022009-08-13 21:57:51 +0000635 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
Nate Begemanfaae0812008-04-19 04:17:09 +0000636 };
Owen Anderson758428f2009-08-05 23:18:46 +0000637 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
Nate Begemanfaae0812008-04-19 04:17:09 +0000638}
639
Argyrios Kyrtzidisc0279a92010-07-27 22:37:14 +0000640bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000641 // Never defer when EmitAllDecls is specified.
642 if (Features.EmitAllDecls)
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000643 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000644
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +0000645 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000646}
647
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000648llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
649 const AliasAttr *AA = VD->getAttr<AliasAttr>();
650 assert(AA && "No alias?");
651
652 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
653
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000654 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +0000655 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000656
657 llvm::Constant *Aliasee;
658 if (isa<llvm::FunctionType>(DeclTy))
John McCall7ec50432010-03-19 23:29:14 +0000659 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000660 else
John McCall7ec50432010-03-19 23:29:14 +0000661 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000662 llvm::PointerType::getUnqual(DeclTy), 0);
663 if (!Entry) {
664 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
665 F->setLinkage(llvm::Function::ExternalWeakLinkage);
666 WeakRefReferences.insert(F);
667 }
668
669 return Aliasee;
670}
671
Chris Lattnere0be0df2009-05-12 21:21:08 +0000672void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000673 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000674
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000675 // Weak references don't produce any output by themselves.
676 if (Global->hasAttr<WeakRefAttr>())
677 return;
678
Chris Lattner54041692009-03-22 21:47:11 +0000679 // If this is an alias definition (which otherwise looks like a declaration)
680 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000681 if (Global->hasAttr<AliasAttr>())
John McCall7ec50432010-03-19 23:29:14 +0000682 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000683
Chris Lattner45470942009-03-21 09:44:56 +0000684 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar4e004ed2009-03-19 08:27:24 +0000685 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar3348e2d2010-07-16 00:00:19 +0000686 if (FD->getIdentifier()) {
687 llvm::StringRef Name = FD->getName();
688 if (Name == "_Block_object_assign") {
689 BlockObjectAssignDecl = FD;
690 } else if (Name == "_Block_object_dispose") {
691 BlockObjectDisposeDecl = FD;
692 }
693 }
694
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000695 // Forward declarations are emitted lazily on first use.
696 if (!FD->isThisDeclarationADefinition())
697 return;
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000698 } else {
699 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000700 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
701
Daniel Dunbar3348e2d2010-07-16 00:00:19 +0000702 if (VD->getIdentifier()) {
703 llvm::StringRef Name = VD->getName();
704 if (Name == "_NSConcreteGlobalBlock") {
705 NSConcreteGlobalBlockDecl = VD;
706 } else if (Name == "_NSConcreteStackBlock") {
707 NSConcreteStackBlockDecl = VD;
708 }
709 }
710
711
Douglas Gregor61f6db52010-02-06 05:15:45 +0000712 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +0000713 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +0000714 }
715
Chris Lattner45470942009-03-21 09:44:56 +0000716 // Defer code generation when possible if this is a static definition, inline
717 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000718 if (!MayDeferGeneration(Global)) {
719 // Emit the definition if it can't be deferred.
720 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000721 return;
722 }
John McCall70013b62010-07-15 23:40:35 +0000723
724 // If we're deferring emission of a C++ variable with an
725 // initializer, remember the order in which it appeared in the file.
726 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
727 cast<VarDecl>(Global)->hasInit()) {
728 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
729 CXXGlobalInits.push_back(0);
730 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000731
732 // If the value has already been used, add it directly to the
733 // DeferredDeclsToEmit list.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000734 llvm::StringRef MangledName = getMangledName(GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000735 if (GetGlobalValue(MangledName))
736 DeferredDeclsToEmit.push_back(GD);
737 else {
738 // Otherwise, remember that we saw a deferred decl with this name. The
739 // first use of the mangled name will cause it to move into
740 // DeferredDeclsToEmit.
741 DeferredDecls[MangledName] = GD;
742 }
Nate Begeman8e8d4982008-04-20 06:29:50 +0000743}
744
Chris Lattnere0be0df2009-05-12 21:21:08 +0000745void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000746 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000747
Dan Gohman145f3f12010-04-19 16:39:44 +0000748 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +0000749 Context.getSourceManager(),
750 "Generating code for declaration");
751
Douglas Gregora700f682010-07-13 06:02:28 +0000752 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
753 // At -O0, don't generate IR for functions with available_externally
754 // linkage.
Douglas Gregor89976902010-07-15 22:58:18 +0000755 if (CodeGenOpts.OptimizationLevel == 0 &&
756 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregora700f682010-07-13 06:02:28 +0000757 getFunctionLinkage(Function)
758 == llvm::Function::AvailableExternallyLinkage)
759 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +0000760
Douglas Gregora700f682010-07-13 06:02:28 +0000761 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
762 if (Method->isVirtual())
763 getVTables().EmitThunks(GD);
764
765 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
766 return EmitCXXConstructor(CD, GD.getCtorType());
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000767
Douglas Gregora700f682010-07-13 06:02:28 +0000768 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
769 return EmitCXXDestructor(DD, GD.getDtorType());
770 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000771
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000772 return EmitGlobalFunctionDefinition(GD);
Douglas Gregora700f682010-07-13 06:02:28 +0000773 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000774
775 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
776 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000777
778 assert(0 && "Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +0000779}
780
Chris Lattnerd4808922009-03-22 21:03:39 +0000781/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
782/// module, create and return an llvm Function with the specified type. If there
783/// is something in the module with the specified name, return it potentially
784/// bitcasted to the right type.
785///
786/// If D is non-null, it specifies a decl that correspond to this. This is used
787/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000788llvm::Constant *
789CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
790 const llvm::Type *Ty,
791 GlobalDecl D) {
Chris Lattnera85d68e2009-03-21 09:25:43 +0000792 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000793 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000794 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000795 if (WeakRefReferences.count(Entry)) {
796 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
797 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +0000798 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000799
800 WeakRefReferences.erase(Entry);
801 }
802
Chris Lattnera85d68e2009-03-21 09:25:43 +0000803 if (Entry->getType()->getElementType() == Ty)
804 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000805
Chris Lattnera85d68e2009-03-21 09:25:43 +0000806 // Make sure the result is of the correct type.
Owen Anderson9793f0e2009-07-29 22:16:19 +0000807 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Owen Andersonade90fd2009-07-29 18:54:39 +0000808 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000809 }
Mike Stump11289f42009-09-09 15:08:12 +0000810
Eli Friedmancc522d92009-11-09 05:07:37 +0000811 // This function doesn't have a complete type (for example, the return
812 // type is an incomplete struct). Use a fake type instead, and make
813 // sure not to try to set attributes.
814 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +0000815
816 const llvm::FunctionType *FTy;
817 if (isa<llvm::FunctionType>(Ty)) {
818 FTy = cast<llvm::FunctionType>(Ty);
819 } else {
Benjamin Kramer1e188892011-01-22 12:15:57 +0000820 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
Eli Friedmancc522d92009-11-09 05:07:37 +0000821 IsIncompleteFunction = true;
822 }
Chris Lattner5c740f12010-06-30 19:14:05 +0000823
John McCalld06fb862010-04-28 00:00:30 +0000824 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +0000825 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +0000826 MangledName, &getModule());
827 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedmancc522d92009-11-09 05:07:37 +0000828 if (D.getDecl())
Anders Carlsson6710c532010-02-06 02:44:09 +0000829 SetFunctionAttributes(D, F, IsIncompleteFunction);
Eli Friedmancc522d92009-11-09 05:07:37 +0000830
Chris Lattner45470942009-03-21 09:44:56 +0000831 // This is the first use or definition of a mangled name. If there is a
832 // deferred decl with this name, remember that we need to emit it at the end
833 // of the file.
John McCall7ec50432010-03-19 23:29:14 +0000834 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +0000835 if (DDI != DeferredDecls.end()) {
836 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
837 // list, and remove it from DeferredDecls (since we don't need it anymore).
838 DeferredDeclsToEmit.push_back(DDI->second);
839 DeferredDecls.erase(DDI);
John McCall357d0f32010-12-15 04:00:32 +0000840
841 // Otherwise, there are cases we have to worry about where we're
842 // using a declaration for which we must emit a definition but where
843 // we might not find a top-level definition:
844 // - member functions defined inline in their classes
845 // - friend functions defined inline in some class
846 // - special member functions with implicit definitions
847 // If we ever change our AST traversal to walk into class methods,
848 // this will be unnecessary.
849 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
850 // Look for a declaration that's lexically in a record.
851 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
852 do {
853 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
854 if (FD->isImplicit()) {
855 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
856 DeferredDeclsToEmit.push_back(D);
857 break;
858 } else if (FD->isThisDeclarationADefinition()) {
859 DeferredDeclsToEmit.push_back(D);
860 break;
861 }
Rafael Espindola70e040d2010-03-02 21:28:26 +0000862 }
John McCall357d0f32010-12-15 04:00:32 +0000863 FD = FD->getPreviousDeclaration();
864 } while (FD);
Chris Lattner45470942009-03-21 09:44:56 +0000865 }
Mike Stump11289f42009-09-09 15:08:12 +0000866
John McCalld06fb862010-04-28 00:00:30 +0000867 // Make sure the result is of the requested type.
868 if (!IsIncompleteFunction) {
869 assert(F->getType()->getElementType() == Ty);
870 return F;
871 }
872
873 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
874 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000875}
876
Chris Lattnerd4808922009-03-22 21:03:39 +0000877/// GetAddrOfFunction - Return the address of the given function. If Ty is
878/// non-null, then this function will use the specified type if it has to
879/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +0000880llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattnerd4808922009-03-22 21:03:39 +0000881 const llvm::Type *Ty) {
882 // If there was no specific requested type, just convert it now.
883 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +0000884 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +0000885
Anders Carlssonea836bc2010-06-22 16:16:50 +0000886 llvm::StringRef MangledName = getMangledName(GD);
John McCall7ec50432010-03-19 23:29:14 +0000887 return GetOrCreateLLVMFunction(MangledName, Ty, GD);
Chris Lattnerd4808922009-03-22 21:03:39 +0000888}
Eli Friedmanc18d9d52008-05-30 19:50:47 +0000889
Chris Lattnerd4808922009-03-22 21:03:39 +0000890/// CreateRuntimeFunction - Create a new runtime function with the specified
891/// type and name.
892llvm::Constant *
893CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
John McCall7ec50432010-03-19 23:29:14 +0000894 llvm::StringRef Name) {
Chris Lattnere0be0df2009-05-12 21:21:08 +0000895 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
Chris Lattnerd4808922009-03-22 21:03:39 +0000896}
Daniel Dunbar9c426522008-07-29 23:18:29 +0000897
Eli Friedmanb095e152009-12-11 21:23:03 +0000898static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
John McCall340aafa2010-02-08 21:46:50 +0000899 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +0000900 return false;
901 if (Context.getLangOptions().CPlusPlus &&
902 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
903 // FIXME: We should do something fancier here!
904 return false;
905 }
906 return true;
907}
908
Chris Lattnerd4808922009-03-22 21:03:39 +0000909/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
910/// create and return an llvm GlobalVariable with the specified type. If there
911/// is something in the module with the specified name, return it potentially
912/// bitcasted to the right type.
913///
914/// If D is non-null, it specifies a decl that correspond to this. This is used
915/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000916llvm::Constant *
917CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
918 const llvm::PointerType *Ty,
Rafael Espindolad661a852011-01-18 21:07:57 +0000919 const VarDecl *D,
920 bool UnnamedAddr) {
Daniel Dunbar829e9882008-08-05 23:31:02 +0000921 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000922 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +0000923 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000924 if (WeakRefReferences.count(Entry)) {
925 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +0000926 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000927
928 WeakRefReferences.erase(Entry);
929 }
930
Rafael Espindolad661a852011-01-18 21:07:57 +0000931 if (UnnamedAddr)
932 Entry->setUnnamedAddr(true);
933
Chris Lattnerd4808922009-03-22 21:03:39 +0000934 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +0000935 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000936
Chris Lattner3bfce182009-03-21 08:03:33 +0000937 // Make sure the result is of the correct type.
Owen Andersonade90fd2009-07-29 18:54:39 +0000938 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +0000939 }
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattner45470942009-03-21 09:44:56 +0000941 // This is the first use or definition of a mangled name. If there is a
942 // deferred decl with this name, remember that we need to emit it at the end
943 // of the file.
John McCall7ec50432010-03-19 23:29:14 +0000944 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +0000945 if (DDI != DeferredDecls.end()) {
946 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
947 // list, and remove it from DeferredDecls (since we don't need it anymore).
948 DeferredDeclsToEmit.push_back(DDI->second);
949 DeferredDecls.erase(DDI);
950 }
Mike Stump11289f42009-09-09 15:08:12 +0000951
952 llvm::GlobalVariable *GV =
953 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner3bfce182009-03-21 08:03:33 +0000954 llvm::GlobalValue::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +0000955 0, MangledName, 0,
Eli Friedman4f856742009-04-19 21:05:03 +0000956 false, Ty->getAddressSpace());
Chris Lattner3bfce182009-03-21 08:03:33 +0000957
958 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +0000959 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +0000960 // FIXME: This code is overly simple and should be merged with other global
961 // handling.
Eli Friedmanb095e152009-12-11 21:23:03 +0000962 GV->setConstant(DeclIsConstantGlobal(Context, D));
Chris Lattner3bfce182009-03-21 08:03:33 +0000963
John McCall37bb6c92010-10-29 22:22:43 +0000964 // Set linkage and visibility in case we never see a definition.
John McCallc273f242010-10-30 11:50:40 +0000965 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
966 if (LV.linkage() != ExternalLinkage) {
John McCall37bb6c92010-10-29 22:22:43 +0000967 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
968 } else {
969 if (D->hasAttr<DLLImportAttr>())
970 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
971 else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
972 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner3bfce182009-03-21 08:03:33 +0000973
John McCallc273f242010-10-30 11:50:40 +0000974 // Set visibility on a declaration only if it's explicit.
975 if (LV.visibilityExplicit())
976 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall37bb6c92010-10-29 22:22:43 +0000977 }
Eli Friedman4f856742009-04-19 21:05:03 +0000978
979 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattnerd4808922009-03-22 21:03:39 +0000980 }
Mike Stump11289f42009-09-09 15:08:12 +0000981
John McCall7ec50432010-03-19 23:29:14 +0000982 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000983}
984
Chris Lattnerd4808922009-03-22 21:03:39 +0000985
Anders Carlssonda80af32011-01-29 18:20:20 +0000986llvm::GlobalVariable *
987CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
988 const llvm::Type *Ty,
989 llvm::GlobalValue::LinkageTypes Linkage) {
990 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
991 llvm::GlobalVariable *OldGV = 0;
992
993
994 if (GV) {
995 // Check if the variable has the right type.
996 if (GV->getType()->getElementType() == Ty)
997 return GV;
998
999 // Because C++ name mangling, the only way we can end up with an already
1000 // existing global with the same name is if it has been declared extern "C".
Anders Carlsson93be9a92011-01-29 18:25:07 +00001001 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00001002 OldGV = GV;
1003 }
1004
1005 // Create a new variable.
1006 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1007 Linkage, 0, Name);
1008
1009 if (OldGV) {
1010 // Replace occurrences of the old variable if needed.
1011 GV->takeName(OldGV);
1012
1013 if (!OldGV->use_empty()) {
1014 llvm::Constant *NewPtrForOldDecl =
1015 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1016 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1017 }
1018
1019 OldGV->eraseFromParent();
1020 }
1021
1022 return GV;
1023}
1024
Chris Lattnerd4808922009-03-22 21:03:39 +00001025/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1026/// given global variable. If Ty is non-null and if the global doesn't exist,
1027/// then it will be greated with the specified type instead of whatever the
1028/// normal requested type would be.
1029llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1030 const llvm::Type *Ty) {
1031 assert(D->hasGlobalStorage() && "Not a global variable");
1032 QualType ASTTy = D->getType();
1033 if (Ty == 0)
1034 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001035
1036 const llvm::PointerType *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001037 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
John McCall7ec50432010-03-19 23:29:14 +00001038
Anders Carlssonea836bc2010-06-22 16:16:50 +00001039 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001040 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001041}
1042
1043/// CreateRuntimeVariable - Create a new runtime global variable with the
1044/// specified type and name.
1045llvm::Constant *
1046CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
John McCall7ec50432010-03-19 23:29:14 +00001047 llvm::StringRef Name) {
Rafael Espindolad661a852011-01-18 21:07:57 +00001048 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1049 true);
Chris Lattnerd4808922009-03-22 21:03:39 +00001050}
1051
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001052void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1053 assert(!D->getInit() && "Cannot emit definite definitions here!");
1054
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001055 if (MayDeferGeneration(D)) {
1056 // If we have not seen a reference to this variable yet, place it
1057 // into the deferred declarations table to be emitted if needed
1058 // later.
Anders Carlssonea836bc2010-06-22 16:16:50 +00001059 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001060 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001061 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001062 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001063 }
1064 }
1065
1066 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001067 EmitGlobalVarDefinition(D);
1068}
1069
Douglas Gregor88d292c2010-05-13 16:44:06 +00001070void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1071 if (DefinitionRequired)
1072 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1073}
1074
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001075llvm::GlobalVariable::LinkageTypes
Anders Carlsson11e51402010-04-17 20:15:18 +00001076CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Douglas Gregor2a34df32010-01-06 22:00:56 +00001077 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1078 return llvm::GlobalVariable::InternalLinkage;
1079
1080 if (const CXXMethodDecl *KeyFunction
1081 = RD->getASTContext().getKeyFunction(RD)) {
1082 // If this class has a key function, use that to determine the linkage of
1083 // the vtable.
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001084 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001085 if (KeyFunction->hasBody(Def))
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001086 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregor2a34df32010-01-06 22:00:56 +00001087
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001088 switch (KeyFunction->getTemplateSpecializationKind()) {
1089 case TSK_Undeclared:
1090 case TSK_ExplicitSpecialization:
1091 if (KeyFunction->isInlined())
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001092 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001093
1094 return llvm::GlobalVariable::ExternalLinkage;
1095
1096 case TSK_ImplicitInstantiation:
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001097 return llvm::GlobalVariable::LinkOnceODRLinkage;
1098
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001099 case TSK_ExplicitInstantiationDefinition:
1100 return llvm::GlobalVariable::WeakODRLinkage;
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001101
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001102 case TSK_ExplicitInstantiationDeclaration:
1103 // FIXME: Use available_externally linkage. However, this currently
1104 // breaks LLVM's build due to undefined symbols.
1105 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001106 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001107 }
Douglas Gregor2a34df32010-01-06 22:00:56 +00001108 }
1109
1110 switch (RD->getTemplateSpecializationKind()) {
1111 case TSK_Undeclared:
1112 case TSK_ExplicitSpecialization:
1113 case TSK_ImplicitInstantiation:
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001114 return llvm::GlobalVariable::LinkOnceODRLinkage;
1115
Douglas Gregor2a34df32010-01-06 22:00:56 +00001116 case TSK_ExplicitInstantiationDefinition:
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001117 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor2a34df32010-01-06 22:00:56 +00001118
1119 case TSK_ExplicitInstantiationDeclaration:
1120 // FIXME: Use available_externally linkage. However, this currently
1121 // breaks LLVM's build due to undefined symbols.
1122 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001123 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001124 }
1125
1126 // Silence GCC warning.
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001127 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001128}
1129
Ken Dyck98ca7942010-01-26 13:48:07 +00001130CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
Ken Dyck9a648692011-01-18 02:01:14 +00001131 return Context.toCharUnitsFromBits(
1132 TheTargetData.getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00001133}
1134
Daniel Dunbar9c426522008-07-29 23:18:29 +00001135void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001136 llvm::Constant *Init = 0;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001137 QualType ASTTy = D->getType();
Eli Friedman5866fe32010-01-08 00:50:11 +00001138 bool NonConstInit = false;
Mike Stump11289f42009-09-09 15:08:12 +00001139
Sebastian Redl5ca79842010-02-01 20:16:42 +00001140 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlssonca4a5452010-01-26 17:43:42 +00001141
1142 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001143 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001144 // implicitly initialized with { 0 }.
1145 //
1146 // Note that tentative definitions are only emitted at the end of
1147 // a translation unit, so they should never have incomplete
1148 // type. In addition, EmitTentativeDefinition makes sure that we
1149 // never attempt to emit a tentative definition if a real one
1150 // exists. A use may still exists, however, so we still may need
1151 // to do a RAUW.
1152 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001153 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001154 } else {
Douglas Gregord450f062010-05-05 20:15:55 +00001155 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman719ed1a2009-02-20 01:18:21 +00001156 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001157 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001158 if (D->getType()->isReferenceType())
1159 T = D->getType();
1160
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001161 if (getLangOptions().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001162 Init = EmitNullConstant(T);
Eli Friedman5866fe32010-01-08 00:50:11 +00001163 NonConstInit = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001164 } else {
1165 ErrorUnsupported(D, "static initializer");
1166 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1167 }
John McCall70013b62010-07-15 23:40:35 +00001168 } else {
1169 // We don't need an initializer, so remove the entry for the delayed
1170 // initializer position (just in case this entry was delayed).
1171 if (getLangOptions().CPlusPlus)
1172 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001173 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001174 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001175
Chris Lattner64c55932009-03-21 08:13:05 +00001176 const llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001177 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001178
Chris Lattner149927c2009-03-21 09:16:30 +00001179 // Strip off a bitcast if we got one back.
1180 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001181 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1182 // all zero index gep.
1183 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001184 Entry = CE->getOperand(0);
1185 }
Mike Stump11289f42009-09-09 15:08:12 +00001186
Chris Lattner149927c2009-03-21 09:16:30 +00001187 // Entry is now either a Function or GlobalVariable.
1188 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001189
Chris Lattner149927c2009-03-21 09:16:30 +00001190 // We have a definition after a declaration with the wrong type.
1191 // We must make a new GlobalVariable* and update everything that used OldGV
1192 // (a declaration or tentative definition) with the new GlobalVariable*
1193 // (which will be a definition).
1194 //
1195 // This happens if there is a prototype for a global (e.g.
1196 // "extern int x[];") and then a definition of a different type (e.g.
1197 // "int x[10];"). This also happens when an initializer has a different type
1198 // from the type of the global (this happens with unions).
Chris Lattner149927c2009-03-21 09:16:30 +00001199 if (GV == 0 ||
1200 GV->getType()->getElementType() != InitType ||
1201 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
Mike Stump11289f42009-09-09 15:08:12 +00001202
John McCall7ec50432010-03-19 23:29:14 +00001203 // Move the old entry aside so that we'll create a new one.
1204 Entry->setName(llvm::StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001205
Chris Lattner149927c2009-03-21 09:16:30 +00001206 // Make a new global with the correct type, this is now guaranteed to work.
1207 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001208
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001209 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001210 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001211 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001212 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001213
1214 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001215 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001216 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001217
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001218 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begemanfaae0812008-04-19 04:17:09 +00001219 SourceManager &SM = Context.getSourceManager();
1220 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner8a425862009-01-16 07:36:28 +00001221 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begemanfaae0812008-04-19 04:17:09 +00001222 }
1223
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001224 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001225
1226 // If it is safe to mark the global 'constant', do so now.
1227 GV->setConstant(false);
Eli Friedman5866fe32010-01-08 00:50:11 +00001228 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
Chris Lattnerf49573d2009-08-05 05:20:29 +00001229 GV->setConstant(true);
Mike Stump11289f42009-09-09 15:08:12 +00001230
Ken Dyck160146e2010-01-27 17:10:57 +00001231 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001232
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001233 // Set the llvm linkage type as appropriate.
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001234 llvm::GlobalValue::LinkageTypes Linkage =
1235 GetLLVMLinkageVarDefinition(D, GV);
1236 GV->setLinkage(Linkage);
1237 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnerf49573d2009-08-05 05:20:29 +00001238 // common vars aren't constant even if declared const.
1239 GV->setConstant(false);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001240
Daniel Dunbar38932572009-04-14 08:05:55 +00001241 SetCommonAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001242
John McCallcdf7ef52010-11-06 09:44:32 +00001243 // Emit the initializer function if necessary.
1244 if (NonConstInit)
1245 EmitCXXGlobalVarDeclInitFunc(D, GV);
1246
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001247 // Emit global variable debug information.
Chris Lattner64c55932009-03-21 08:13:05 +00001248 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +00001249 DI->setLocation(D->getLocation());
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001250 DI->EmitGlobalVariable(GV, D);
1251 }
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001252}
Chris Lattner09153c02007-06-22 18:48:09 +00001253
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001254llvm::GlobalValue::LinkageTypes
1255CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1256 llvm::GlobalVariable *GV) {
1257 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1258 if (Linkage == GVA_Internal)
1259 return llvm::Function::InternalLinkage;
1260 else if (D->hasAttr<DLLImportAttr>())
1261 return llvm::Function::DLLImportLinkage;
1262 else if (D->hasAttr<DLLExportAttr>())
1263 return llvm::Function::DLLExportLinkage;
1264 else if (D->hasAttr<WeakAttr>()) {
1265 if (GV->isConstant())
1266 return llvm::GlobalVariable::WeakODRLinkage;
1267 else
1268 return llvm::GlobalVariable::WeakAnyLinkage;
1269 } else if (Linkage == GVA_TemplateInstantiation ||
1270 Linkage == GVA_ExplicitTemplateInstantiation)
1271 // FIXME: It seems like we can provide more specific linkage here
1272 // (LinkOnceODR, WeakODR).
1273 return llvm::GlobalVariable::WeakAnyLinkage;
Eric Christopher8a2ee392010-12-02 02:45:55 +00001274 else if (!getLangOptions().CPlusPlus &&
1275 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1276 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001277 !D->hasExternalStorage() && !D->getInit() &&
1278 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1279 // Thread local vars aren't considered common linkage.
1280 return llvm::GlobalVariable::CommonLinkage;
1281 }
1282 return llvm::GlobalVariable::ExternalLinkage;
1283}
1284
Chris Lattner36797ab2009-05-05 06:16:31 +00001285/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1286/// implement a function with no prototype, e.g. "int foo() {}". If there are
1287/// existing call uses of the old function in the module, this adjusts them to
1288/// call the new function directly.
1289///
1290/// This is not just a cleanup: the always_inline pass requires direct calls to
1291/// functions to be able to inline them. If there is a bitcast in the way, it
1292/// won't inline them. Instcombine normally deletes these calls, but it isn't
1293/// run at -O0.
1294static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1295 llvm::Function *NewFn) {
1296 // If we're redefining a global as a function, don't transform it.
1297 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1298 if (OldFn == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +00001299
Chris Lattner36797ab2009-05-05 06:16:31 +00001300 const llvm::Type *NewRetTy = NewFn->getReturnType();
1301 llvm::SmallVector<llvm::Value*, 4> ArgList;
1302
1303 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001304 UI != E; ) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001305 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001306 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1307 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif79ac9ed2010-07-28 09:19:33 +00001308 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
Gabor Greifd394aec2010-04-10 03:45:50 +00001309 llvm::CallSite CS(CI);
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001310 if (!CI || !CS.isCallee(I)) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001311
Chris Lattner36797ab2009-05-05 06:16:31 +00001312 // If the return types don't match exactly, and if the call isn't dead, then
1313 // we can't transform this call.
1314 if (CI->getType() != NewRetTy && !CI->use_empty())
1315 continue;
1316
1317 // If the function was passed too few arguments, don't transform. If extra
1318 // arguments were passed, we silently drop them. If any of the types
1319 // mismatch, we don't transform.
1320 unsigned ArgNo = 0;
1321 bool DontTransform = false;
1322 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1323 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greifd394aec2010-04-10 03:45:50 +00001324 if (CS.arg_size() == ArgNo ||
1325 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001326 DontTransform = true;
1327 break;
1328 }
1329 }
1330 if (DontTransform)
1331 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001332
Chris Lattner36797ab2009-05-05 06:16:31 +00001333 // Okay, we can transform this. Create the new call instruction and copy
1334 // over the required information.
Gabor Greifd0ef1342010-04-10 02:56:12 +00001335 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Chris Lattner36797ab2009-05-05 06:16:31 +00001336 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1337 ArgList.end(), "", CI);
1338 ArgList.clear();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00001339 if (!NewCall->getType()->isVoidTy())
Chris Lattner36797ab2009-05-05 06:16:31 +00001340 NewCall->takeName(CI);
Chris Lattner36797ab2009-05-05 06:16:31 +00001341 NewCall->setAttributes(CI->getAttributes());
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001342 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattner36797ab2009-05-05 06:16:31 +00001343
1344 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner734351d2009-10-14 05:49:21 +00001345 if (!CI->use_empty())
1346 CI->replaceAllUsesWith(NewCall);
Devang Patel74684892009-10-13 17:02:04 +00001347
Chris Lattnere675d0f2010-04-01 06:31:43 +00001348 // Copy debug location attached to CI.
1349 if (!CI->getDebugLoc().isUnknown())
1350 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattner36797ab2009-05-05 06:16:31 +00001351 CI->eraseFromParent();
1352 }
1353}
1354
Daniel Dunbar9c426522008-07-29 23:18:29 +00001355
Chris Lattnere0be0df2009-05-12 21:21:08 +00001356void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00001357 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCallf8ff7b92010-02-23 00:48:20 +00001358 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
Chris Lattnereb7466d2009-05-12 20:58:15 +00001359 // Get or create the prototype for the function.
Chris Lattnere0be0df2009-05-12 21:21:08 +00001360 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001361
Chris Lattnera85d68e2009-03-21 09:25:43 +00001362 // Strip off a bitcast if we got one back.
1363 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1364 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1365 Entry = CE->getOperand(0);
1366 }
Mike Stump11289f42009-09-09 15:08:12 +00001367
1368
Chris Lattnera85d68e2009-03-21 09:25:43 +00001369 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001370 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001371
Daniel Dunbar99d28352009-03-09 23:53:08 +00001372 // If the types mismatch then we have to rewrite the definition.
Chris Lattner36797ab2009-05-05 06:16:31 +00001373 assert(OldFn->isDeclaration() &&
Chris Lattnera85d68e2009-03-21 09:25:43 +00001374 "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00001375
Chris Lattner5eaee562009-03-21 08:38:50 +00001376 // F is the Function* for the one with the wrong type, we must make a new
1377 // Function* and update everything that used F (a declaration) with the new
1378 // Function* (which will be a definition).
1379 //
1380 // This happens if there is a prototype for a function
1381 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00001382 // (e.g. "int f(int x)"). Move the old function aside so that it
1383 // doesn't interfere with GetAddrOfFunction.
1384 OldFn->setName(llvm::StringRef());
Chris Lattnere0be0df2009-05-12 21:21:08 +00001385 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00001386
Chris Lattner36797ab2009-05-05 06:16:31 +00001387 // If this is an implementation of a function without a prototype, try to
1388 // replace any existing uses of the function (which may be calls) with uses
1389 // of the new function
Chris Lattnereb7466d2009-05-12 20:58:15 +00001390 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001391 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattnereb7466d2009-05-12 20:58:15 +00001392 OldFn->removeDeadConstantUsers();
1393 }
Mike Stump11289f42009-09-09 15:08:12 +00001394
Chris Lattner5eaee562009-03-21 08:38:50 +00001395 // Replace uses of F with the Function we will endow with a body.
Chris Lattner36797ab2009-05-05 06:16:31 +00001396 if (!Entry->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00001397 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001398 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattner36797ab2009-05-05 06:16:31 +00001399 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1400 }
Mike Stump11289f42009-09-09 15:08:12 +00001401
Chris Lattner5eaee562009-03-21 08:38:50 +00001402 // Ok, delete the old function now, which is dead.
Chris Lattner36797ab2009-05-05 06:16:31 +00001403 OldFn->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00001404
Chris Lattnera85d68e2009-03-21 09:25:43 +00001405 Entry = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001406 }
Mike Stump11289f42009-09-09 15:08:12 +00001407
John McCall8e7cb6d2010-11-02 21:04:24 +00001408 // We need to set linkage and visibility on the function before
1409 // generating code for it because various parts of IR generation
1410 // want to propagate this information down (e.g. to local static
1411 // declarations).
Chris Lattnera85d68e2009-03-21 09:25:43 +00001412 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall7cb02202010-05-25 04:30:21 +00001413 setFunctionLinkage(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001414
John McCall8e7cb6d2010-11-02 21:04:24 +00001415 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00001416 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00001417
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001418 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001419
Daniel Dunbar38932572009-04-14 08:05:55 +00001420 SetFunctionDefinitionAttributes(D, Fn);
1421 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00001422
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001423 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001424 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001425 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001426 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar9c426522008-07-29 23:18:29 +00001427}
1428
John McCall7ec50432010-03-19 23:29:14 +00001429void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1430 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001431 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00001432 assert(AA && "Not an alias?");
1433
Anders Carlssonea836bc2010-06-22 16:16:50 +00001434 llvm::StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00001435
John McCall7ec50432010-03-19 23:29:14 +00001436 // If there is a definition in the module, then it wins over the alias.
1437 // This is dubious, but allow it to be safe. Just ignore the alias.
1438 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1439 if (Entry && !Entry->isDeclaration())
1440 return;
1441
1442 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00001443
1444 // Create a reference to the named value. This ensures that it is emitted
1445 // if a deferred decl.
1446 llvm::Constant *Aliasee;
1447 if (isa<llvm::FunctionType>(DeclTy))
John McCall7ec50432010-03-19 23:29:14 +00001448 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Chris Lattner54041692009-03-22 21:47:11 +00001449 else
John McCall7ec50432010-03-19 23:29:14 +00001450 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson9793f0e2009-07-29 22:16:19 +00001451 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattner54041692009-03-22 21:47:11 +00001452
1453 // Create the new alias itself, but don't set a name yet.
Mike Stump11289f42009-09-09 15:08:12 +00001454 llvm::GlobalValue *GA =
Chris Lattner54041692009-03-22 21:47:11 +00001455 new llvm::GlobalAlias(Aliasee->getType(),
1456 llvm::Function::ExternalLinkage,
1457 "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00001458
Chris Lattner54041692009-03-22 21:47:11 +00001459 if (Entry) {
John McCall7ec50432010-03-19 23:29:14 +00001460 assert(Entry->isDeclaration());
1461
Chris Lattner54041692009-03-22 21:47:11 +00001462 // If there is a declaration in the module, then we had an extern followed
1463 // by the alias, as in:
1464 // extern int test6();
1465 // ...
1466 // int test6() __attribute__((alias("test7")));
1467 //
1468 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00001469 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001470
Owen Andersonade90fd2009-07-29 18:54:39 +00001471 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00001472 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00001473 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00001474 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00001475 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00001476 }
Mike Stump11289f42009-09-09 15:08:12 +00001477
Daniel Dunbar38932572009-04-14 08:05:55 +00001478 // Set attributes which are particular to an alias; this is a
1479 // specialization of the attributes which may be set on a global
1480 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001481 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001482 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1483 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001484 if (FD->hasBody())
Daniel Dunbar38932572009-04-14 08:05:55 +00001485 GA->setLinkage(llvm::Function::DLLExportLinkage);
1486 } else {
1487 GA->setLinkage(llvm::Function::DLLExportLinkage);
1488 }
Mike Stump11289f42009-09-09 15:08:12 +00001489 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00001490 D->hasAttr<WeakRefAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001491 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001492 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1493 }
1494
1495 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00001496}
1497
Chris Lattnere64911a2009-03-22 21:56:56 +00001498/// getBuiltinLibFunction - Given a builtin id for a function like
1499/// "__builtin_fabsf", return a Function* for "fabsf".
Daniel Dunbarff0553e2009-09-14 04:33:21 +00001500llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1501 unsigned BuiltinID) {
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001502 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
Mike Stump11289f42009-09-09 15:08:12 +00001503 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001504 "isn't a lib fn");
Mike Stump11289f42009-09-09 15:08:12 +00001505
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001506 // Get the name, skip over the __builtin_ prefix (if necessary).
1507 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1508 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1509 Name += 10;
Mike Stump11289f42009-09-09 15:08:12 +00001510
Mike Stump11289f42009-09-09 15:08:12 +00001511 const llvm::FunctionType *Ty =
Eli Friedman4f678f32009-12-09 03:05:59 +00001512 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
Chris Lattner1eec6602007-08-31 04:31:45 +00001513
Daniel Dunbarff0553e2009-09-14 04:33:21 +00001514 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
Chris Lattner1eec6602007-08-31 04:31:45 +00001515}
1516
Chris Lattnerb8be97e2007-12-18 00:25:38 +00001517llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1518 unsigned NumTys) {
1519 return llvm::Intrinsic::getDeclaration(&getModule(),
1520 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1521}
Chris Lattner1eec6602007-08-31 04:31:45 +00001522
Daniel Dunbar64509b22009-07-23 22:52:48 +00001523static llvm::StringMapEntry<llvm::Constant*> &
1524GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1525 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001526 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00001527 bool &IsUTF16,
1528 unsigned &StringLength) {
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001529 llvm::StringRef String = Literal->getString();
1530 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001531
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001532 // Check for simple case.
1533 if (!Literal->containsNonAsciiOrNull()) {
1534 StringLength = NumBytes;
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001535 return Map.GetOrCreateValue(String);
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001536 }
1537
Daniel Dunbar64509b22009-07-23 22:52:48 +00001538 // Otherwise, convert the UTF8 literals into a byte string.
1539 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001540 const UTF8 *FromPtr = (UTF8 *)String.data();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001541 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00001542
Fariborz Jahanian535618b2010-09-07 19:57:04 +00001543 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1544 &ToPtr, ToPtr + NumBytes,
1545 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00001546
Daniel Dunbar91ade142009-07-23 23:41:22 +00001547 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00001548 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00001549
1550 // Render the UTF-16 string into a byte array and convert to the target byte
1551 // order.
1552 //
1553 // FIXME: This isn't something we should need to do here.
1554 llvm::SmallString<128> AsBytes;
1555 AsBytes.reserve(StringLength * 2);
1556 for (unsigned i = 0; i != StringLength; ++i) {
1557 unsigned short Val = ToBuf[i];
1558 if (TargetIsLSB) {
1559 AsBytes.push_back(Val & 0xFF);
1560 AsBytes.push_back(Val >> 8);
1561 } else {
1562 AsBytes.push_back(Val >> 8);
1563 AsBytes.push_back(Val & 0xFF);
1564 }
1565 }
Daniel Dunbar4d93a4f2009-08-03 21:47:08 +00001566 // Append one extra null character, the second is automatically added by our
1567 // caller.
1568 AsBytes.push_back(0);
Daniel Dunbar91ade142009-07-23 23:41:22 +00001569
Daniel Dunbar64509b22009-07-23 22:52:48 +00001570 IsUTF16 = true;
Daniel Dunbar91ade142009-07-23 23:41:22 +00001571 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar64509b22009-07-23 22:52:48 +00001572}
1573
1574llvm::Constant *
1575CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1576 unsigned StringLength = 0;
1577 bool isUTF16 = false;
1578 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00001579 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001580 getTargetData().isLittleEndian(),
1581 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001582
Daniel Dunbar64509b22009-07-23 22:52:48 +00001583 if (llvm::Constant *C = Entry.getValue())
1584 return C;
Mike Stump11289f42009-09-09 15:08:12 +00001585
Owen Anderson41a75022009-08-13 21:57:51 +00001586 llvm::Constant *Zero =
1587 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbard644ad62008-08-23 18:37:06 +00001588 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump11289f42009-09-09 15:08:12 +00001589
Chris Lattneraa64ca22009-07-16 16:48:25 +00001590 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00001591 if (!CFConstantStringClassRef) {
1592 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001593 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001594 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00001595 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00001596 // Decay array -> ptr
1597 CFConstantStringClassRef =
Owen Andersonade90fd2009-07-29 18:54:39 +00001598 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonb04ea612007-08-21 00:21:21 +00001599 }
Mike Stump11289f42009-09-09 15:08:12 +00001600
Anders Carlssonc2480a52008-11-15 18:54:24 +00001601 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00001602
Mike Stump11289f42009-09-09 15:08:12 +00001603 const llvm::StructType *STy =
Anders Carlssonc2480a52008-11-15 18:54:24 +00001604 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1605
Anders Carlsson157c3212009-08-16 05:55:31 +00001606 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor91f84212008-12-11 16:49:14 +00001607
Anders Carlssonb04ea612007-08-21 00:21:21 +00001608 // Class pointer.
Anders Carlsson157c3212009-08-16 05:55:31 +00001609 Fields[0] = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00001610
Anders Carlssonb04ea612007-08-21 00:21:21 +00001611 // Flags.
Daniel Dunbard644ad62008-08-23 18:37:06 +00001612 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001613 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00001614 llvm::ConstantInt::get(Ty, 0x07C8);
1615
Anders Carlssonb04ea612007-08-21 00:21:21 +00001616 // String pointer.
Owen Anderson41a75022009-08-13 21:57:51 +00001617 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001618
Chris Lattner3afa3e12009-07-16 05:03:48 +00001619 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001620 bool isConstant;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001621 if (isUTF16) {
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001622 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner3afa3e12009-07-16 05:03:48 +00001623 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001624 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1625 // does make plain ascii ones writable.
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001626 isConstant = true;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001627 } else {
1628 Linkage = llvm::GlobalValue::PrivateLinkage;
1629 isConstant = !Features.WritableStrings;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001630 }
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001631
Mike Stump11289f42009-09-09 15:08:12 +00001632 llvm::GlobalVariable *GV =
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001633 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1634 ".str");
Rafael Espindolae79d43da2011-01-17 16:31:00 +00001635 GV->setUnnamedAddr(true);
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001636 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00001637 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1638 GV->setAlignment(Align.getQuantity());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001639 }
Anders Carlsson157c3212009-08-16 05:55:31 +00001640 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1641
Anders Carlssonb04ea612007-08-21 00:21:21 +00001642 // String length.
1643 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00001644 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001645
Anders Carlssonb04ea612007-08-21 00:21:21 +00001646 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00001647 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00001648 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1649 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00001650 "_unnamed_cfstring_");
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001651 if (const char *Sect = getContext().Target.getCFStringSection())
1652 GV->setSection(Sect);
Daniel Dunbar64509b22009-07-23 22:52:48 +00001653 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00001654
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00001655 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00001656}
Chris Lattnerfb300092007-11-28 05:34:05 +00001657
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001658llvm::Constant *
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001659CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001660 unsigned StringLength = 0;
1661 bool isUTF16 = false;
1662 llvm::StringMapEntry<llvm::Constant*> &Entry =
1663 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1664 getTargetData().isLittleEndian(),
1665 isUTF16, StringLength);
1666
1667 if (llvm::Constant *C = Entry.getValue())
1668 return C;
1669
1670 llvm::Constant *Zero =
1671 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1672 llvm::Constant *Zeros[] = { Zero, Zero };
1673
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001674 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001675 if (!ConstantStringClassRef) {
1676 std::string StringClass(getLangOptions().ObjCConstantStringClass);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001677 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1678 Ty = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001679 llvm::Constant *GV;
1680 if (StringClass.empty())
1681 GV = CreateRuntimeVariable(Ty,
1682 Features.ObjCNonFragileABI ?
1683 "OBJC_CLASS_$_NSConstantString" :
1684 "_NSConstantStringClassReference");
1685 else {
1686 std::string str;
1687 if (Features.ObjCNonFragileABI)
1688 str = "OBJC_CLASS_$_" + StringClass;
1689 else
1690 str = "_" + StringClass + "ClassReference";
1691 GV = CreateRuntimeVariable(Ty, str);
1692 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001693 // Decay array -> ptr
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001694 ConstantStringClassRef =
1695 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001696 }
1697
1698 QualType NSTy = getContext().getNSConstantStringType();
1699
1700 const llvm::StructType *STy =
1701 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1702
1703 std::vector<llvm::Constant*> Fields(3);
1704
1705 // Class pointer.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001706 Fields[0] = ConstantStringClassRef;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001707
1708 // String pointer.
1709 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1710
1711 llvm::GlobalValue::LinkageTypes Linkage;
1712 bool isConstant;
1713 if (isUTF16) {
1714 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1715 Linkage = llvm::GlobalValue::InternalLinkage;
1716 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1717 // does make plain ascii ones writable.
1718 isConstant = true;
1719 } else {
1720 Linkage = llvm::GlobalValue::PrivateLinkage;
1721 isConstant = !Features.WritableStrings;
1722 }
1723
1724 llvm::GlobalVariable *GV =
1725 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1726 ".str");
Rafael Espindolade089d42011-01-17 22:11:21 +00001727 GV->setUnnamedAddr(true);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001728 if (isUTF16) {
1729 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1730 GV->setAlignment(Align.getQuantity());
1731 }
1732 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1733
1734 // String length.
1735 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1736 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1737
1738 // The struct.
1739 C = llvm::ConstantStruct::get(STy, Fields);
1740 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1741 llvm::GlobalVariable::PrivateLinkage, C,
1742 "_unnamed_nsstring_");
1743 // FIXME. Fix section.
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001744 if (const char *Sect =
1745 Features.ObjCNonFragileABI
1746 ? getContext().Target.getNSStringNonFragileABISection()
1747 : getContext().Target.getNSStringSection())
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001748 GV->setSection(Sect);
1749 Entry.setValue(GV);
1750
1751 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001752}
1753
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001754/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001755/// string literal, properly padded to match the literal type.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001756std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Ken Dycka45a70c2011-01-29 17:53:12 +00001757 const ASTContext &Context = getContext();
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001758 const ConstantArrayType *CAT =
Ken Dycka45a70c2011-01-29 17:53:12 +00001759 Context.getAsConstantArrayType(E->getType());
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001760 assert(CAT && "String isn't pointer or array!");
Mike Stump11289f42009-09-09 15:08:12 +00001761
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001762 // Resize the string to the right size.
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001763 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001764
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001765 if (E->isWide())
Ken Dycka45a70c2011-01-29 17:53:12 +00001766 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001767
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001768 std::string Str = E->getString().str();
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001769 Str.resize(RealLen, '\0');
Mike Stump11289f42009-09-09 15:08:12 +00001770
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001771 return Str;
1772}
1773
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001774/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1775/// constant array for the given string literal.
1776llvm::Constant *
1777CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1778 // FIXME: This can be more efficient.
Eli Friedman49ddc5f2009-11-16 05:55:46 +00001779 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1780 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1781 if (S->isWide()) {
1782 llvm::Type *DestTy =
1783 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1784 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1785 }
1786 return C;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001787}
1788
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001789/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1790/// array for the given ObjCEncodeExpr node.
1791llvm::Constant *
1792CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1793 std::string Str;
1794 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00001795
1796 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001797}
1798
1799
Chris Lattner36fc8792008-02-11 00:02:17 +00001800/// GenerateWritableString -- Creates storage for a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001801static llvm::Constant *GenerateStringLiteral(const std::string &str,
Chris Lattnerfb300092007-11-28 05:34:05 +00001802 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001803 CodeGenModule &CGM,
1804 const char *GlobalName) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001805 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00001806 llvm::Constant *C =
1807 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00001808
Chris Lattnerfb300092007-11-28 05:34:05 +00001809 // Create a global variable for this string
Rafael Espindolab7f60e32011-01-10 22:34:03 +00001810 llvm::GlobalVariable *GV =
1811 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1812 llvm::GlobalValue::PrivateLinkage,
1813 C, GlobalName);
1814 GV->setUnnamedAddr(true);
1815 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00001816}
1817
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001818/// GetAddrOfConstantString - Returns a pointer to a character array
1819/// containing the literal. This contents are exactly that of the
1820/// given string, i.e. it will not be null terminated automatically;
1821/// see GetAddrOfConstantCString. Note that whether the result is
1822/// actually a pointer to an LLVM constant depends on
1823/// Feature.WriteableStrings.
1824///
1825/// The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001826llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1827 const char *GlobalName) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001828 bool IsConstant = !Features.WritableStrings;
1829
1830 // Get the default prefix if a name wasn't specified.
1831 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00001832 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001833
1834 // Don't share any string literals if strings aren't constant.
1835 if (!IsConstant)
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001836 return GenerateStringLiteral(str, false, *this, GlobalName);
Mike Stump11289f42009-09-09 15:08:12 +00001837
1838 llvm::StringMapEntry<llvm::Constant *> &Entry =
Chris Lattner3afa3e12009-07-16 05:03:48 +00001839 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
Chris Lattnerfb300092007-11-28 05:34:05 +00001840
1841 if (Entry.getValue())
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001842 return Entry.getValue();
Chris Lattnerfb300092007-11-28 05:34:05 +00001843
1844 // Create a global variable for this.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001845 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerfb300092007-11-28 05:34:05 +00001846 Entry.setValue(C);
1847 return C;
1848}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001849
1850/// GetAddrOfConstantCString - Returns a pointer to a character
1851/// array containing the literal and a terminating '\-'
1852/// character. The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001853llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1854 const char *GlobalName){
Chris Lattner2e41b0e2008-12-09 19:10:54 +00001855 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001856}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001857
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001858/// EmitObjCPropertyImplementations - Emit information for synthesized
1859/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00001860void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001861 ObjCImplementationDecl *D) {
Mike Stump11289f42009-09-09 15:08:12 +00001862 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001863 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001864 ObjCPropertyImplDecl *PID = *i;
Mike Stump11289f42009-09-09 15:08:12 +00001865
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001866 // Dynamic is just for type-checking.
1867 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1868 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1869
1870 // Determine which methods need to be implemented, some may have
1871 // been overridden. Note that ::isSynthesized is not the method
1872 // we want, that just indicates if the decl came from a
1873 // property. What we want to know is if the method is defined in
1874 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001875 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001876 CodeGenFunction(*this).GenerateObjCGetter(
1877 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001878 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001879 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001880 CodeGenFunction(*this).GenerateObjCSetter(
1881 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001882 }
1883 }
1884}
1885
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001886/// EmitObjCIvarInitializations - Emit information for ivar initialization
1887/// for an implementation.
1888void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1889 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1890 return;
1891 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1892 assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1893 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1894 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1895 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1896 D->getLocation(),
1897 D->getLocation(), cxxSelector,
1898 getContext().VoidTy, 0,
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001899 DC, true, false, true, false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001900 ObjCMethodDecl::Required);
1901 D->addInstanceMethod(DTORMethod);
1902 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1903
1904 II = &getContext().Idents.get(".cxx_construct");
1905 cxxSelector = getContext().Selectors.getSelector(0, &II);
1906 // The constructor returns 'self'.
1907 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1908 D->getLocation(),
1909 D->getLocation(), cxxSelector,
1910 getContext().getObjCIdType(), 0,
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001911 DC, true, false, true, false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001912 ObjCMethodDecl::Required);
1913 D->addInstanceMethod(CTORMethod);
1914 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1915
1916
1917}
1918
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001919/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00001920void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001921 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson237f3492009-04-01 00:58:25 +00001922 I != E; ++I)
1923 EmitTopLevelDecl(*I);
1924}
1925
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001926// EmitLinkageSpec - Emit all declarations in a linkage spec.
1927void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00001928 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1929 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001930 ErrorUnsupported(LSD, "linkage spec");
1931 return;
1932 }
1933
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001934 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001935 I != E; ++I)
1936 EmitTopLevelDecl(*I);
1937}
1938
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001939/// EmitTopLevelDecl - Emit code for a single top level declaration.
1940void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1941 // If an error has occurred, stop code generation, but continue
1942 // parsing and semantic analysis (to ensure all warnings and errors
1943 // are emitted).
1944 if (Diags.hasErrorOccurred())
1945 return;
1946
Douglas Gregor70d83e22009-06-29 17:30:29 +00001947 // Ignore dependent declarations.
1948 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1949 return;
Mike Stump11289f42009-09-09 15:08:12 +00001950
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001951 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00001952 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00001953 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001954 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00001955 // Skip function templates
1956 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1957 return;
Mike Stump11289f42009-09-09 15:08:12 +00001958
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001959 EmitGlobal(cast<FunctionDecl>(D));
1960 break;
1961
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001962 case Decl::Var:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001963 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001964 break;
1965
Anders Carlssonf7475242009-04-15 15:55:24 +00001966 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001967 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00001968 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001969 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00001970 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00001971 case Decl::UsingShadow:
Douglas Gregorfec52632009-06-20 00:51:54 +00001972 case Decl::Using:
Douglas Gregore5feb512009-09-02 23:49:23 +00001973 case Decl::UsingDirective:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001974 case Decl::ClassTemplate:
1975 case Decl::FunctionTemplate:
Anders Carlsson649a17e2009-09-23 19:19:16 +00001976 case Decl::NamespaceAlias:
Douglas Gregorfec52632009-06-20 00:51:54 +00001977 break;
Anders Carlssonf7475242009-04-15 15:55:24 +00001978 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00001979 // Skip function templates
1980 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1981 return;
1982
Anders Carlssonf7475242009-04-15 15:55:24 +00001983 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1984 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00001985 case Decl::CXXDestructor:
1986 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1987 break;
Anders Carlsson87835432009-06-11 21:22:55 +00001988
1989 case Decl::StaticAssert:
1990 // Nothing to do.
1991 break;
1992
Anders Carlssonf7475242009-04-15 15:55:24 +00001993 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00001994
Fariborz Jahanian3654e652009-03-18 22:33:24 +00001995 // Forward declarations, no (immediate) code generation.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001996 case Decl::ObjCClass:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001997 case Decl::ObjCForwardProtocol:
Chris Lattnerd18136a2009-04-01 02:36:43 +00001998 case Decl::ObjCInterface:
Chris Lattnerd18136a2009-04-01 02:36:43 +00001999 break;
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00002000
2001 case Decl::ObjCCategory: {
2002 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2003 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2004 Context.ResetObjCLayout(CD->getClassInterface());
2005 break;
2006 }
2007
Chris Lattnerd18136a2009-04-01 02:36:43 +00002008
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002009 case Decl::ObjCProtocol:
Fariborz Jahanian629aed92009-03-21 18:06:45 +00002010 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002011 break;
2012
2013 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002014 // Categories have properties but don't support synthesize so we
2015 // can ignore them here.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002016 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2017 break;
2018
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002019 case Decl::ObjCImplementation: {
2020 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00002021 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2022 Context.ResetObjCLayout(OMD->getClassInterface());
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002023 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002024 EmitObjCIvarInitializations(OMD);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002025 Runtime->GenerateClass(OMD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002026 break;
Mike Stump11289f42009-09-09 15:08:12 +00002027 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002028 case Decl::ObjCMethod: {
2029 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2030 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002031 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002032 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2033 break;
2034 }
Mike Stump11289f42009-09-09 15:08:12 +00002035 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian17290c32009-01-08 01:10:55 +00002036 // compatibility-alias is a directive and has no code gen.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002037 break;
2038
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002039 case Decl::LinkageSpec:
2040 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002041 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002042
2043 case Decl::FileScopeAsm: {
2044 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002045 llvm::StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00002046
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002047 const std::string &S = getModule().getModuleInlineAsm();
2048 if (S.empty())
2049 getModule().setModuleInlineAsm(AsmString);
2050 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002051 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002052 break;
2053 }
Mike Stump11289f42009-09-09 15:08:12 +00002054
2055 default:
Mike Stump18bb9282009-05-16 07:57:57 +00002056 // Make sure we handled everything we should, every other kind is a
2057 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2058 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002059 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2060 }
2061}
John McCall09ae0322010-07-06 23:57:41 +00002062
2063/// Turns the given pointer into a constant.
2064static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2065 const void *Ptr) {
2066 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2067 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2068 return llvm::ConstantInt::get(i64, PtrInt);
2069}
2070
2071static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2072 llvm::NamedMDNode *&GlobalMetadata,
2073 GlobalDecl D,
2074 llvm::GlobalValue *Addr) {
2075 if (!GlobalMetadata)
2076 GlobalMetadata =
2077 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2078
2079 // TODO: should we report variant information for ctors/dtors?
2080 llvm::Value *Ops[] = {
2081 Addr,
2082 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2083 };
2084 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2085}
2086
2087/// Emits metadata nodes associating all the global values in the
2088/// current module with the Decls they came from. This is useful for
2089/// projects using IR gen as a subroutine.
2090///
2091/// Since there's currently no way to associate an MDNode directly
2092/// with an llvm::GlobalValue, we create a global named metadata
2093/// with the name 'clang.global.decl.ptrs'.
2094void CodeGenModule::EmitDeclMetadata() {
2095 llvm::NamedMDNode *GlobalMetadata = 0;
2096
2097 // StaticLocalDeclMap
2098 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2099 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2100 I != E; ++I) {
2101 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2102 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2103 }
2104}
2105
2106/// Emits metadata nodes for all the local variables in the current
2107/// function.
2108void CodeGenFunction::EmitDeclMetadata() {
2109 if (LocalDeclMap.empty()) return;
2110
2111 llvm::LLVMContext &Context = getLLVMContext();
2112
2113 // Find the unique metadata ID for this name.
2114 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2115
2116 llvm::NamedMDNode *GlobalMetadata = 0;
2117
2118 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2119 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2120 const Decl *D = I->first;
2121 llvm::Value *Addr = I->second;
2122
2123 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2124 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2125 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2126 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2127 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2128 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2129 }
2130 }
2131}
Daniel Dunbar900546d2010-07-16 00:00:15 +00002132
2133///@name Custom Runtime Function Interfaces
2134///@{
2135//
2136// FIXME: These can be eliminated once we can have clients just get the required
2137// AST nodes from the builtin tables.
2138
2139llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2140 if (BlockObjectDispose)
2141 return BlockObjectDispose;
2142
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002143 // If we saw an explicit decl, use that.
2144 if (BlockObjectDisposeDecl) {
2145 return BlockObjectDispose = GetAddrOfFunction(
2146 BlockObjectDisposeDecl,
2147 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2148 }
2149
2150 // Otherwise construct the function by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002151 const llvm::FunctionType *FTy;
2152 std::vector<const llvm::Type*> ArgTys;
2153 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2154 ArgTys.push_back(PtrToInt8Ty);
2155 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2156 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2157 return BlockObjectDispose =
2158 CreateRuntimeFunction(FTy, "_Block_object_dispose");
2159}
2160
2161llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2162 if (BlockObjectAssign)
2163 return BlockObjectAssign;
2164
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002165 // If we saw an explicit decl, use that.
2166 if (BlockObjectAssignDecl) {
2167 return BlockObjectAssign = GetAddrOfFunction(
2168 BlockObjectAssignDecl,
2169 getTypes().GetFunctionType(BlockObjectAssignDecl));
2170 }
2171
2172 // Otherwise construct the function by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002173 const llvm::FunctionType *FTy;
2174 std::vector<const llvm::Type*> ArgTys;
2175 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2176 ArgTys.push_back(PtrToInt8Ty);
2177 ArgTys.push_back(PtrToInt8Ty);
2178 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2179 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2180 return BlockObjectAssign =
2181 CreateRuntimeFunction(FTy, "_Block_object_assign");
2182}
2183
2184llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2185 if (NSConcreteGlobalBlock)
2186 return NSConcreteGlobalBlock;
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002187
2188 // If we saw an explicit decl, use that.
2189 if (NSConcreteGlobalBlockDecl) {
2190 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2191 NSConcreteGlobalBlockDecl,
2192 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2193 }
2194
2195 // Otherwise construct the variable by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002196 return NSConcreteGlobalBlock = CreateRuntimeVariable(
2197 PtrToInt8Ty, "_NSConcreteGlobalBlock");
2198}
2199
2200llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2201 if (NSConcreteStackBlock)
2202 return NSConcreteStackBlock;
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002203
2204 // If we saw an explicit decl, use that.
2205 if (NSConcreteStackBlockDecl) {
2206 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2207 NSConcreteStackBlockDecl,
2208 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2209 }
2210
2211 // Otherwise construct the variable by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002212 return NSConcreteStackBlock = CreateRuntimeVariable(
2213 PtrToInt8Ty, "_NSConcreteStackBlock");
2214}
2215
2216///@}