blob: e0309e1654bd68f7bd44d224f5582222e438a9a2 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattnerdb6be562007-11-28 05:34:05 +000021#include "clang/Basic/LangOptions.h"
Nate Begeman8a704172008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000024#include "llvm/CallingConv.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "llvm/Constants.h"
26#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000027#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000029#include "llvm/Target/TargetData.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000030#include "llvm/Analysis/Verifier.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000031#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000032using namespace clang;
33using namespace CodeGen;
34
35
Chris Lattnerdb6be562007-11-28 05:34:05 +000036CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000037 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000038 Diagnostic &diags, bool GenerateDebugInfo,
39 bool UseMacObjCRuntime)
Chris Lattner22595b82007-12-02 01:40:18 +000040 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Eli Friedman8f08a252008-05-26 12:59:39 +000041 Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
42 CFConstantStringClassRef(0) {
Chris Lattnercbfb5512008-03-01 08:45:05 +000043 //TODO: Make this selectable at runtime
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000044 if (UseMacObjCRuntime) {
45 Runtime = CreateMacObjCRuntime(*this);
46 } else {
47 Runtime = CreateGNUObjCRuntime(*this);
48 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000049
50 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000051 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000052}
53
54CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000055 delete Runtime;
56 delete DebugInfo;
57}
58
59void CodeGenModule::Release() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000060 EmitStatics();
Chris Lattnerb326b172008-03-30 23:03:07 +000061 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000062 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000063 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000064 EmitCtorList(GlobalCtors, "llvm.global_ctors");
65 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000066 EmitAnnotations();
Chris Lattnerb033c4a2008-04-30 16:05:42 +000067 // Run the verifier to check that the generated code is consistent.
68 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000069}
Chris Lattner4b009652007-07-25 00:24:17 +000070
Chris Lattnercf9c9d02007-12-02 07:19:18 +000071/// WarnUnsupported - Print out a warning that codegen doesn't support the
72/// specified stmt yet.
73void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
74 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
75 "cannot codegen this %0 yet");
76 SourceRange Range = S->getSourceRange();
77 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000078 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000079 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000080}
Chris Lattner0e4755d2007-12-02 06:27:33 +000081
Chris Lattner806a5f52008-01-12 07:05:38 +000082/// WarnUnsupported - Print out a warning that codegen doesn't support the
83/// specified decl yet.
84void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
85 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
86 "cannot codegen this %0 yet");
87 std::string Msg = Type;
88 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
89 &Msg, 1);
90}
91
Dan Gohman4751a3a2008-05-22 00:50:06 +000092/// setVisibility - Set the visibility for the given LLVM GlobalValue
93/// according to the given clang AST visibility value.
94void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
95 VisibilityAttr::VisibilityTypes Vis) {
96 switch (Vis) {
97 default: assert(0 && "Unknown visibility!");
98 case VisibilityAttr::DefaultVisibility:
99 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
100 break;
101 case VisibilityAttr::HiddenVisibility:
102 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
103 break;
104 case VisibilityAttr::ProtectedVisibility:
105 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
106 break;
107 }
108}
109
Chris Lattner753d2592008-03-14 17:18:18 +0000110/// AddGlobalCtor - Add a function to the list that will be called before
111/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000112void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000113 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000114 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000115}
116
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000117/// AddGlobalDtor - Add a function to the list that will be called
118/// when the module is unloaded.
119void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
120 // TODO: Type coercion of void()* types.
121 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
122}
123
124void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
125 // Ctor function type is void()*.
126 llvm::FunctionType* CtorFTy =
127 llvm::FunctionType::get(llvm::Type::VoidTy,
128 std::vector<const llvm::Type*>(),
129 false);
130 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
131
132 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000133 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000134 llvm::StructType::get(llvm::Type::Int32Ty,
135 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000136
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000137 // Construct the constructor and destructor arrays.
138 std::vector<llvm::Constant*> Ctors;
139 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
140 std::vector<llvm::Constant*> S;
141 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
142 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
143 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000144 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000145
146 if (!Ctors.empty()) {
147 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
148 new llvm::GlobalVariable(AT, false,
149 llvm::GlobalValue::AppendingLinkage,
150 llvm::ConstantArray::get(AT, Ctors),
151 GlobalName,
152 &TheModule);
153 }
Chris Lattner753d2592008-03-14 17:18:18 +0000154}
155
Nate Begeman52da5c72008-04-18 23:43:57 +0000156void CodeGenModule::EmitAnnotations() {
157 if (Annotations.empty())
158 return;
159
160 // Create a new global variable for the ConstantStruct in the Module.
161 llvm::Constant *Array =
162 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
163 Annotations.size()),
164 Annotations);
165 llvm::GlobalValue *gv =
166 new llvm::GlobalVariable(Array->getType(), false,
167 llvm::GlobalValue::AppendingLinkage, Array,
168 "llvm.global.annotations", &TheModule);
169 gv->setSection("llvm.metadata");
170}
171
Eli Friedman9be42212008-06-01 15:54:49 +0000172bool hasAggregateLLVMType(QualType T) {
173 return !T->isRealType() && !T->isPointerLikeType() &&
174 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
175}
176
Nuno Lopes78534382008-06-08 15:45:52 +0000177void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
178 llvm::GlobalValue *GV) {
179 // TODO: Set up linkage and many other things. Note, this is a simple
180 // approximation of what we really want.
181 if (FD->getStorageClass() == FunctionDecl::Static)
182 GV->setLinkage(llvm::Function::InternalLinkage);
183 else if (FD->getAttr<DLLImportAttr>())
184 GV->setLinkage(llvm::Function::DLLImportLinkage);
185 else if (FD->getAttr<DLLExportAttr>())
186 GV->setLinkage(llvm::Function::DLLExportLinkage);
187 else if (FD->getAttr<WeakAttr>() || FD->isInline())
188 GV->setLinkage(llvm::Function::WeakLinkage);
189
190 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
191 CodeGenModule::setVisibility(GV, attr->getVisibility());
192 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000193
194 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
195 // Prefaced with special LLVM marker to indicate that the name
196 // should not be munged.
197 GV->setName("\01" + ALA->getLabel());
198 }
Nuno Lopes78534382008-06-08 15:45:52 +0000199}
200
Eli Friedman9be42212008-06-01 15:54:49 +0000201void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
202 llvm::Function *F,
203 const llvm::FunctionType *FTy) {
204 unsigned FuncAttrs = 0;
205 if (FD->getAttr<NoThrowAttr>())
206 FuncAttrs |= llvm::ParamAttr::NoUnwind;
207 if (FD->getAttr<NoReturnAttr>())
208 FuncAttrs |= llvm::ParamAttr::NoReturn;
209
210 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
211 if (FuncAttrs)
212 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
213 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
214 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
215 if (AggregateReturn)
216 ParamAttrList.push_back(
217 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
218 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000219 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
220 if (FTP) {
221 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
222 QualType ParamType = FTP->getArgType(i);
223 unsigned ParamAttrs = 0;
224 if (ParamType->isRecordType())
225 ParamAttrs |= llvm::ParamAttr::ByVal;
Chris Lattner578279d2008-06-26 05:08:00 +0000226 if (ParamType->isSignedIntegerType() &&
227 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000228 ParamAttrs |= llvm::ParamAttr::SExt;
Chris Lattner578279d2008-06-26 05:08:00 +0000229 if (ParamType->isUnsignedIntegerType() &&
230 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000231 ParamAttrs |= llvm::ParamAttr::ZExt;
232 if (ParamAttrs)
233 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
234 ParamAttrs));
235 }
Eli Friedman9be42212008-06-01 15:54:49 +0000236 }
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000237
Eli Friedman9be42212008-06-01 15:54:49 +0000238 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
239 ParamAttrList.size()));
240
241 // Set the appropriate calling convention for the Function.
242 if (FD->getAttr<FastCallAttr>())
243 F->setCallingConv(llvm::CallingConv::Fast);
244
Nuno Lopes78534382008-06-08 15:45:52 +0000245 SetGlobalValueAttributes(FD, F);
Eli Friedman9be42212008-06-01 15:54:49 +0000246}
247
Chris Lattnerb326b172008-03-30 23:03:07 +0000248void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
249 // If this is not a prototype, emit the body.
250 if (OMD->getBody())
251 CodeGenFunction(*this).GenerateObjCMethod(OMD);
252}
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000253void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
254 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner0be08822008-07-21 21:32:27 +0000255 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
256 E = PD->protocol_end(); PI != E; ++PI)
257 Protocols.push_back((*PI)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000258 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
259 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
260 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
Chris Lattner0be08822008-07-21 21:32:27 +0000261 E = PD->instmeth_end(); iter != E; iter++) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000262 std::string TypeStr;
Chris Lattner0be08822008-07-21 21:32:27 +0000263 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000264 InstanceMethodNames.push_back(
265 GetAddrOfConstantString((*iter)->getSelector().getName()));
266 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
267 }
268 // Collect information about class methods:
269 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
270 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
271 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
272 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
273 std::string TypeStr;
274 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
275 ClassMethodNames.push_back(
276 GetAddrOfConstantString((*iter)->getSelector().getName()));
277 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
278 }
279 Runtime->GenerateProtocol(PD->getName(), Protocols, InstanceMethodNames,
280 InstanceMethodTypes, ClassMethodNames, ClassMethodTypes);
281}
282
283void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
284
285 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000286 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000287 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
288 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
289 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000290 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000291 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000292 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000293 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
294 }
295
296 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000297 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000298 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
299 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
300 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000301 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000302 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000303 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000304 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
305 }
306
307 // Collect the names of referenced protocols
308 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000309 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
310 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
311 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
312 E = Protos.end(); I != E; ++I)
313 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000314
315 // Generate the category
316 Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
Chris Lattner578279d2008-06-26 05:08:00 +0000317 OCD->getName(), InstanceMethodSels, InstanceMethodTypes,
318 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000319}
320
321void CodeGenModule::EmitObjCClassImplementation(
322 const ObjCImplementationDecl *OID) {
323 // Get the superclass name.
324 const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
325 const char * SCName = NULL;
326 if (SCDecl) {
327 SCName = SCDecl->getName();
328 }
329
330 // Get the class name
331 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
332 const char * ClassName = ClassDecl->getName();
333
334 // Get the size of instances. For runtimes that support late-bound instances
335 // this should probably be something different (size just of instance
336 // varaibles in this class, not superclasses?).
337 int instanceSize = 0;
338 const llvm::Type *ObjTy;
339 if (!Runtime->LateBoundIVars()) {
340 ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
341 instanceSize = TheTargetData.getABITypeSize(ObjTy);
342 }
343
344 // Collect information about instance variables.
345 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
346 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
347 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
348 const llvm::StructLayout *Layout =
349 TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
350 ObjTy = llvm::PointerType::getUnqual(ObjTy);
351 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
352 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
353 // Store the name
354 IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
355 // Get the type encoding for this ivar
356 std::string TypeStr;
357 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
358 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
359 EncodingRecordTypes);
360 IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
361 // Get the offset
362 int offset =
363 (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
364 IvarOffsets.push_back(
365 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
366 }
367
368 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000369 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000370 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
371 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
372 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000373 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000374 std::string TypeStr;
375 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000376 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
377 }
378
379 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000380 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000381 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
382 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
383 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000384 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000385 std::string TypeStr;
386 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000387 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
388 }
389 // Collect the names of referenced protocols
390 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000391 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
392 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
393 E = Protos.end(); I != E; ++I)
394 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000395
396 // Generate the category
397 Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
Chris Lattner578279d2008-06-26 05:08:00 +0000398 IvarOffsets, InstanceMethodSels, InstanceMethodTypes,
399 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000400}
401
Nate Begemanad320b62008-04-20 06:29:50 +0000402void CodeGenModule::EmitStatics() {
403 // Emit code for each used static decl encountered. Since a previously unused
404 // static decl may become used during the generation of code for a static
405 // function, iterate until no changes are made.
406 bool Changed;
407 do {
408 Changed = false;
409 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000410 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000411
412 // Check if we have used a decl with the same name
413 // FIXME: The AST should have some sort of aggregate decls or
414 // global symbol map.
Daniel Dunbarced89142008-08-06 00:03:29 +0000415 if (!GlobalDeclMap.count(D->getName()))
416 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000417
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000418 // Emit the definition.
419 EmitGlobalDefinition(D);
420
Nate Begemanad320b62008-04-20 06:29:50 +0000421 // Erase the used decl from the list.
422 StaticDecls[i] = StaticDecls.back();
423 StaticDecls.pop_back();
424 --i;
425 --e;
426
427 // Remember that we made a change.
428 Changed = true;
429 }
430 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000431}
432
Nate Begeman8a704172008-04-19 04:17:09 +0000433/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
434/// annotation information for a given GlobalValue. The annotation struct is
435/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000436/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000437/// created from the AnnotateAttr's annotation. The third field is a constant
438/// string containing the name of the translation unit. The fourth field is
439/// the line number in the file of the annotated value declaration.
440///
441/// FIXME: this does not unique the annotation string constants, as llvm-gcc
442/// appears to.
443///
444llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
445 const AnnotateAttr *AA,
446 unsigned LineNo) {
447 llvm::Module *M = &getModule();
448
449 // get [N x i8] constants for the annotation string, and the filename string
450 // which are the 2nd and 3rd elements of the global annotation structure.
451 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
452 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
453 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
454 true);
455
456 // Get the two global values corresponding to the ConstantArrays we just
457 // created to hold the bytes of the strings.
458 llvm::GlobalValue *annoGV =
459 new llvm::GlobalVariable(anno->getType(), false,
460 llvm::GlobalValue::InternalLinkage, anno,
461 GV->getName() + ".str", M);
462 // translation unit name string, emitted into the llvm.metadata section.
463 llvm::GlobalValue *unitGV =
464 new llvm::GlobalVariable(unit->getType(), false,
465 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
466
467 // Create the ConstantStruct that is the global annotion.
468 llvm::Constant *Fields[4] = {
469 llvm::ConstantExpr::getBitCast(GV, SBP),
470 llvm::ConstantExpr::getBitCast(annoGV, SBP),
471 llvm::ConstantExpr::getBitCast(unitGV, SBP),
472 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
473 };
474 return llvm::ConstantStruct::get(Fields, 4, false);
475}
476
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000477void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
478 bool isDef, isStatic;
479
480 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
481 isDef = (FD->isThisDeclarationADefinition() ||
482 FD->getAttr<AliasAttr>());
483 isStatic = FD->getStorageClass() == FunctionDecl::Static;
484 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
485 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
486
487 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
488 isStatic = VD->getStorageClass() == VarDecl::Static;
489 } else {
490 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000491 return;
492 }
493
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000494 // Forward declarations are emitted lazily on first use.
495 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000496 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000497
498 // If the global is a static, defer code generation until later so
499 // we can easily omit unused statics.
500 if (isStatic) {
501 StaticDecls.push_back(Global);
502 return;
503 }
504
505 // Otherwise emit the definition.
506 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000507}
508
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000509void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
510 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
511 EmitGlobalFunctionDefinition(FD);
512 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
513 EmitGlobalVarDefinition(VD);
514 } else {
515 assert(0 && "Invalid argument to EmitGlobalDefinition()");
516 }
517}
518
Daniel Dunbar2188c532008-07-30 16:32:24 +0000519 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000520 assert(D->hasGlobalStorage() && "Not a global variable");
521
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000522 QualType ASTTy = D->getType();
523 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000524 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000525
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000526 // Lookup the entry, lazily creating it if necessary.
527 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
528 if (!Entry)
529 Entry = new llvm::GlobalVariable(Ty, false,
530 llvm::GlobalValue::ExternalLinkage,
531 0, D->getName(), &getModule(), 0,
532 ASTTy.getAddressSpace());
533
Daniel Dunbar2188c532008-07-30 16:32:24 +0000534 // Make sure the result is of the correct type.
535 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000536}
537
538void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000539 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000540 QualType ASTTy = D->getType();
541 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000542
Chris Lattner4b009652007-07-25 00:24:17 +0000543 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000544 // This is a tentative definition; tentative definitions are
545 // implicitly initialized with { 0 }
546 const llvm::Type* InitTy;
547 if (ASTTy->isIncompleteArrayType()) {
548 // An incomplete array is normally [ TYPE x 0 ], but we need
549 // to fix it to [ TYPE x 1 ].
550 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
551 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
552 } else {
553 InitTy = VarTy;
554 }
555 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000556 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000557 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000558 }
559 const llvm::Type* InitType = Init->getType();
560
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000561 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
562 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
563
Eli Friedman43a0ce82008-05-30 19:50:47 +0000564 if (!GV) {
565 GV = new llvm::GlobalVariable(InitType, false,
566 llvm::GlobalValue::ExternalLinkage,
567 0, D->getName(), &getModule(), 0,
568 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000569 } else if (GV->getType() !=
570 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000571 // We have a definition after a prototype with the wrong type.
572 // We must make a new GlobalVariable* and update everything that used OldGV
573 // (a declaration or tentative definition) with the new GlobalVariable*
574 // (which will be a definition).
575 //
576 // This happens if there is a prototype for a global (e.g. "extern int x[];")
577 // and then a definition of a different type (e.g. "int x[10];"). This also
578 // happens when an initializer has a different type from the type of the
579 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000580 //
581 // FIXME: This also ends up happening if there's a definition followed by
582 // a tentative definition! (Although Sema rejects that construct
583 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000584
585 // Save the old global
586 llvm::GlobalVariable *OldGV = GV;
587
588 // Make a new global with the correct type
589 GV = new llvm::GlobalVariable(InitType, false,
590 llvm::GlobalValue::ExternalLinkage,
591 0, D->getName(), &getModule(), 0,
592 ASTTy.getAddressSpace());
593 // Steal the name of the old global
594 GV->takeName(OldGV);
595
596 // Replace all uses of the old global with the new global
597 llvm::Constant *NewPtrForOldDecl =
598 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
599 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000600
601 // Erase the old global, since it is no longer used.
602 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000603 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000604
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000605 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000606
Nate Begeman8a704172008-04-19 04:17:09 +0000607 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
608 SourceManager &SM = Context.getSourceManager();
609 AddAnnotation(EmitAnnotateAttr(GV, AA,
610 SM.getLogicalLineNumber(D->getLocation())));
611 }
612
Chris Lattner4b009652007-07-25 00:24:17 +0000613 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000614
Eli Friedman7008e9a2008-05-30 20:39:54 +0000615 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
616 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000617 if (const IncompleteArrayType* IAT =
618 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000619 Align = Context.getTypeAlign(IAT->getElementType());
620 else
621 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000622 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
623 Align = std::max(Align, AA->getAlignment());
624 }
625 GV->setAlignment(Align / 8);
626
Chris Lattner402b3372008-03-03 03:28:21 +0000627 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000628 setVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000629 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000630
631 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
632 // Prefaced with special LLVM marker to indicate that the name
633 // should not be munged.
634 GV->setName("\01" + ALA->getLabel());
635 }
Chris Lattner4b009652007-07-25 00:24:17 +0000636
637 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000638 if (D->getStorageClass() == VarDecl::Static)
639 GV->setLinkage(llvm::Function::InternalLinkage);
640 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000641 GV->setLinkage(llvm::Function::DLLImportLinkage);
642 else if (D->getAttr<DLLExportAttr>())
643 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000644 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000645 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000646 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000647 // FIXME: This isn't right. This should handle common linkage and other
648 // stuff.
649 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000650 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000651 case VarDecl::Auto:
652 case VarDecl::Register:
653 assert(0 && "Can't have auto or register globals");
654 case VarDecl::None:
655 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000656 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000657 break;
658 case VarDecl::Extern:
659 case VarDecl::PrivateExtern:
660 // todo: common
661 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000662 }
Chris Lattner4b009652007-07-25 00:24:17 +0000663 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000664
665 // Emit global variable debug information.
666 CGDebugInfo *DI = getDebugInfo();
667 if(DI) {
668 if(D->getLocation().isValid())
669 DI->setLocation(D->getLocation());
670 DI->EmitGlobalVariable(GV, D);
671 }
Chris Lattner4b009652007-07-25 00:24:17 +0000672}
673
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000674llvm::GlobalValue *
675CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
676 // FIXME: param attributes for sext/zext etc.
677 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
678 assert(!D->getBody() && "Unexpected alias attr on function with body.");
679
680 const std::string& aliaseeName = AA->getAliasee();
681 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
682 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
683 llvm::Function::ExternalLinkage,
684 D->getName(),
685 aliasee,
686 &getModule());
687 SetGlobalValueAttributes(D, alias);
688 return alias;
689 } else {
690 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
691 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
692 llvm::Function *F = llvm::Function::Create(FTy,
693 llvm::Function::ExternalLinkage,
694 D->getName(), &getModule());
695
696 SetFunctionAttributes(D, F, FTy);
697 return F;
698 }
699}
700
701llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000702 QualType ASTTy = D->getType();
703 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
704 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000705
706 // Lookup the entry, lazily creating it if necessary.
707 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
708 if (!Entry)
709 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000710
Daniel Dunbar2188c532008-07-30 16:32:24 +0000711 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000712}
713
714void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000715 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
716 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000717 Entry = EmitForwardFunctionDefinition(D);
718 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000719 // If the types mismatch then we have to rewrite the definition.
720 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
721 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000722 // Otherwise, we have a definition after a prototype with the wrong type.
723 // F is the Function* for the one with the wrong type, we must make a new
724 // Function* and update everything that used F (a declaration) with the new
725 // Function* (which will be a definition).
726 //
727 // This happens if there is a prototype for a function (e.g. "int f()") and
728 // then a definition of a different type (e.g. "int f(int x)"). Start by
729 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000730 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
731 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000732
733 // Replace uses of F with the Function we will endow with a body.
734 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000735 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
736 Entry->replaceAllUsesWith(NewPtrForOldDecl);
737
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000738 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000739 // FIXME: Add GlobalValue->eraseFromParent().
740 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
741 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
742 F->eraseFromParent();
743 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
744 GA->eraseFromParent();
745 } else {
746 assert(0 && "Invalid global variable type.");
747 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000748
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000749 Entry = NewFn;
750 }
751 }
752
753 if (D->getAttr<AliasAttr>()) {
754 ;
755 } else {
756 llvm::Function *Fn = cast<llvm::Function>(Entry);
757 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000758
759 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
760 AddGlobalCtor(Fn, CA->getPriority());
761 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
762 AddGlobalDtor(Fn, DA->getPriority());
763 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000764 }
765}
766
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000767void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
768 // Make sure that this type is translated.
769 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000770}
771
772
Chris Lattnerab862cc2007-08-31 04:31:45 +0000773/// getBuiltinLibFunction
774llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000775 if (BuiltinID > BuiltinFunctions.size())
776 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000777
Chris Lattner9f2d6892007-12-13 00:38:03 +0000778 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
779 // a slot for it.
780 assert(BuiltinID && "Invalid Builtin ID");
781 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000782 if (FunctionSlot)
783 return FunctionSlot;
784
785 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
786
787 // Get the name, skip over the __builtin_ prefix.
788 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
789
790 // Get the type for the builtin.
791 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
792 const llvm::FunctionType *Ty =
793 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
794
795 // FIXME: This has a serious problem with code like this:
796 // void abs() {}
797 // ... __builtin_abs(x);
798 // The two versions of abs will collide. The fix is for the builtin to win,
799 // and for the existing one to be turned into a constantexpr cast of the
800 // builtin. In the case where the existing one is a static function, it
801 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000802 if (llvm::Function *Existing = getModule().getFunction(Name)) {
803 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
804 return FunctionSlot = Existing;
805 assert(Existing == 0 && "FIXME: Name collision");
806 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000807
808 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000809 return FunctionSlot =
810 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
811 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000812}
813
Chris Lattner4b23f942007-12-18 00:25:38 +0000814llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
815 unsigned NumTys) {
816 return llvm::Intrinsic::getDeclaration(&getModule(),
817 (llvm::Intrinsic::ID)IID, Tys, NumTys);
818}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000819
Chris Lattner4b009652007-07-25 00:24:17 +0000820llvm::Function *CodeGenModule::getMemCpyFn() {
821 if (MemCpyFn) return MemCpyFn;
822 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000823 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000824 default: assert(0 && "Unknown ptr width");
825 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
826 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
827 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000828 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000829}
Anders Carlsson36a04872007-08-21 00:21:21 +0000830
Eli Friedman8f08a252008-05-26 12:59:39 +0000831llvm::Function *CodeGenModule::getMemMoveFn() {
832 if (MemMoveFn) return MemMoveFn;
833 llvm::Intrinsic::ID IID;
834 switch (Context.Target.getPointerWidth(0)) {
835 default: assert(0 && "Unknown ptr width");
836 case 32: IID = llvm::Intrinsic::memmove_i32; break;
837 case 64: IID = llvm::Intrinsic::memmove_i64; break;
838 }
839 return MemMoveFn = getIntrinsic(IID);
840}
841
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000842llvm::Function *CodeGenModule::getMemSetFn() {
843 if (MemSetFn) return MemSetFn;
844 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000845 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000846 default: assert(0 && "Unknown ptr width");
847 case 32: IID = llvm::Intrinsic::memset_i32; break;
848 case 64: IID = llvm::Intrinsic::memset_i64; break;
849 }
850 return MemSetFn = getIntrinsic(IID);
851}
Chris Lattner4b23f942007-12-18 00:25:38 +0000852
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000853// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerab862cc2007-08-31 04:31:45 +0000854llvm::Constant *CodeGenModule::
855GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000856 llvm::StringMapEntry<llvm::Constant *> &Entry =
857 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
858
859 if (Entry.getValue())
860 return Entry.getValue();
861
862 std::vector<llvm::Constant*> Fields;
863
864 if (!CFConstantStringClassRef) {
865 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
866 Ty = llvm::ArrayType::get(Ty, 0);
867
868 CFConstantStringClassRef =
869 new llvm::GlobalVariable(Ty, false,
870 llvm::GlobalVariable::ExternalLinkage, 0,
871 "__CFConstantStringClassReference",
872 &getModule());
873 }
874
875 // Class pointer.
876 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
877 llvm::Constant *Zeros[] = { Zero, Zero };
878 llvm::Constant *C =
879 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
880 Fields.push_back(C);
881
882 // Flags.
883 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
884 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
885
886 // String pointer.
887 C = llvm::ConstantArray::get(str);
888 C = new llvm::GlobalVariable(C->getType(), true,
889 llvm::GlobalValue::InternalLinkage,
890 C, ".str", &getModule());
891
892 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
893 Fields.push_back(C);
894
895 // String length.
896 Ty = getTypes().ConvertType(getContext().LongTy);
897 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
898
899 // The struct.
900 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
901 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000902 llvm::GlobalVariable *GV =
903 new llvm::GlobalVariable(C->getType(), true,
904 llvm::GlobalVariable::InternalLinkage,
905 C, "", &getModule());
906 GV->setSection("__DATA,__cfstring");
907 Entry.setValue(GV);
908 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000909}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000910
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000911/// getStringForStringLiteral - Return the appropriate bytes for a
912/// string literal, properly padded to match the literal type.
913std::string CodeGenModule::getStringForStringLiteral(const StringLiteral *E) {
914 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
915 const char *StrData = E->getStrData();
916 unsigned Len = E->getByteLength();
917
918 const ConstantArrayType *CAT =
919 getContext().getAsConstantArrayType(E->getType());
920 assert(CAT && "String isn't pointer or array!");
921
922 // Resize the string to the right size
923 // FIXME: What about wchar_t strings?
924 std::string Str(StrData, StrData+Len);
925 uint64_t RealLen = CAT->getSize().getZExtValue();
926 Str.resize(RealLen, '\0');
927
928 return Str;
929}
930
Chris Lattnera6dcce32008-02-11 00:02:17 +0000931/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000932static llvm::Constant *GenerateStringLiteral(const std::string &str,
933 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000934 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000935 // Create Constant for this string literal
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000936 llvm::Constant *C = llvm::ConstantArray::get(str);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000937
938 // Create a global variable for this string
939 C = new llvm::GlobalVariable(C->getType(), constant,
940 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000941 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000942 return C;
943}
944
Chris Lattnera6dcce32008-02-11 00:02:17 +0000945/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
946/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000947llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
948 // Don't share any string literals if writable-strings is turned on.
949 if (Features.WritableStrings)
950 return GenerateStringLiteral(str, false, *this);
951
952 llvm::StringMapEntry<llvm::Constant *> &Entry =
953 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
954
955 if (Entry.getValue())
956 return Entry.getValue();
957
958 // Create a global variable for this.
959 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
960 Entry.setValue(C);
961 return C;
962}