blob: 4c12011c4be3870bf705d54dca99e89f03eed048 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000017#include "CGObjCRuntime.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000020#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000023#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000024#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000026#include "llvm/Target/TargetData.h"
Chris Lattnera1945fa2008-04-30 16:05:42 +000027#include "llvm/Analysis/Verifier.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29using namespace CodeGen;
30
31
Chris Lattner45e8cbd2007-11-28 05:34:05 +000032CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-12-02 01:40:18 +000033 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbarf77ac862008-08-11 21:35:06 +000034 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattnerfb97b032007-12-02 01:40:18 +000035 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000036 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Eli Friedman0c995092008-05-26 12:59:39 +000037 CFConstantStringClassRef(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000038
39 if (Features.ObjC1) {
Daniel Dunbarf77ac862008-08-11 21:35:06 +000040 if (Features.NeXTRuntime) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000041 Runtime = CreateMacObjCRuntime(*this);
42 } else {
43 Runtime = CreateGNUObjCRuntime(*this);
44 }
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000045 }
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000046
47 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek815c78f2008-08-05 18:50:11 +000048 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000049}
50
51CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000052 delete Runtime;
53 delete DebugInfo;
54}
55
56void CodeGenModule::Release() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000057 EmitStatics();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000058 if (Runtime)
59 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
60 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000061 EmitCtorList(GlobalCtors, "llvm.global_ctors");
62 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000063 EmitAnnotations();
Chris Lattnera1945fa2008-04-30 16:05:42 +000064 // Run the verifier to check that the generated code is consistent.
65 assert(!verifyModule(TheModule));
Chris Lattner2b94fe32008-03-01 08:45:05 +000066}
Reid Spencer5f016e22007-07-11 17:01:13 +000067
Daniel Dunbar488e9932008-08-16 00:56:44 +000068/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +000069/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000070void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
71 bool OmitOnError) {
72 if (OmitOnError && getDiags().hasErrorOccurred())
73 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000074 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner2c8569d2007-12-02 07:19:18 +000075 "cannot codegen this %0 yet");
76 SourceRange Range = S->getSourceRange();
77 std::string Msg = Type;
Ted Kremenek9c728dc2007-12-12 22:39:36 +000078 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000079 &Msg, 1, &Range, 1);
Chris Lattner2c8569d2007-12-02 07:19:18 +000080}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000081
Daniel Dunbar488e9932008-08-16 00:56:44 +000082/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +000083/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000084void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
85 bool OmitOnError) {
86 if (OmitOnError && getDiags().hasErrorOccurred())
87 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000088 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnerc6fdc342008-01-12 07:05:38 +000089 "cannot codegen this %0 yet");
90 std::string Msg = Type;
91 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
92 &Msg, 1);
93}
94
Daniel Dunbar41071de2008-08-15 23:26:23 +000095/// setGlobalVisibility - Set the visibility for the given LLVM
96/// GlobalValue according to the given clang AST visibility value.
97static void setGlobalVisibility(llvm::GlobalValue *GV,
98 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +000099 switch (Vis) {
100 default: assert(0 && "Unknown visibility!");
101 case VisibilityAttr::DefaultVisibility:
102 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
103 break;
104 case VisibilityAttr::HiddenVisibility:
105 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
106 break;
107 case VisibilityAttr::ProtectedVisibility:
108 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
109 break;
110 }
111}
112
Chris Lattner6d397602008-03-14 17:18:18 +0000113/// AddGlobalCtor - Add a function to the list that will be called before
114/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000115void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner6d397602008-03-14 17:18:18 +0000116 // TODO: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000117 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000118}
119
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000120/// AddGlobalDtor - Add a function to the list that will be called
121/// when the module is unloaded.
122void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
123 // TODO: Type coercion of void()* types.
124 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
125}
126
127void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
128 // Ctor function type is void()*.
129 llvm::FunctionType* CtorFTy =
130 llvm::FunctionType::get(llvm::Type::VoidTy,
131 std::vector<const llvm::Type*>(),
132 false);
133 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
134
135 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000136 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000137 llvm::StructType::get(llvm::Type::Int32Ty,
138 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000139
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000140 // Construct the constructor and destructor arrays.
141 std::vector<llvm::Constant*> Ctors;
142 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
143 std::vector<llvm::Constant*> S;
144 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
145 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
146 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000147 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000148
149 if (!Ctors.empty()) {
150 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
151 new llvm::GlobalVariable(AT, false,
152 llvm::GlobalValue::AppendingLinkage,
153 llvm::ConstantArray::get(AT, Ctors),
154 GlobalName,
155 &TheModule);
156 }
Chris Lattner6d397602008-03-14 17:18:18 +0000157}
158
Nate Begeman532485c2008-04-18 23:43:57 +0000159void CodeGenModule::EmitAnnotations() {
160 if (Annotations.empty())
161 return;
162
163 // Create a new global variable for the ConstantStruct in the Module.
164 llvm::Constant *Array =
165 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
166 Annotations.size()),
167 Annotations);
168 llvm::GlobalValue *gv =
169 new llvm::GlobalVariable(Array->getType(), false,
170 llvm::GlobalValue::AppendingLinkage, Array,
171 "llvm.global.annotations", &TheModule);
172 gv->setSection("llvm.metadata");
173}
174
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000175void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
176 llvm::GlobalValue *GV) {
177 // TODO: Set up linkage and many other things. Note, this is a simple
178 // approximation of what we really want.
179 if (FD->getStorageClass() == FunctionDecl::Static)
180 GV->setLinkage(llvm::Function::InternalLinkage);
181 else if (FD->getAttr<DLLImportAttr>())
182 GV->setLinkage(llvm::Function::DLLImportLinkage);
183 else if (FD->getAttr<DLLExportAttr>())
184 GV->setLinkage(llvm::Function::DLLExportLinkage);
185 else if (FD->getAttr<WeakAttr>() || FD->isInline())
186 GV->setLinkage(llvm::Function::WeakLinkage);
187
188 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000189 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000190 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000191
192 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
193 // Prefaced with special LLVM marker to indicate that the name
194 // should not be munged.
195 GV->setName("\01" + ALA->getLabel());
196 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000197}
198
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000199static void
200SetFunctionAttributesFromTypes(const Decl *FD,
201 llvm::Function *F,
202 const llvm::SmallVector<QualType, 16> &ArgTypes) {
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000203 unsigned FuncAttrs = 0;
204 if (FD->getAttr<NoThrowAttr>())
205 FuncAttrs |= llvm::ParamAttr::NoUnwind;
206 if (FD->getAttr<NoReturnAttr>())
207 FuncAttrs |= llvm::ParamAttr::NoReturn;
208
209 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
210 if (FuncAttrs)
211 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
212 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000213 bool AggregateReturn = CodeGenFunction::hasAggregateLLVMType(ArgTypes[0]);
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000214 if (AggregateReturn)
215 ParamAttrList.push_back(
216 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
217 unsigned increment = AggregateReturn ? 2 : 1;
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000218 for (llvm::SmallVector<QualType, 8>::const_iterator i = ArgTypes.begin() + 1,
219 e = ArgTypes.end(); i != e; ++i, ++increment) {
220 QualType ParamType = *i;
221 unsigned ParamAttrs = 0;
222 if (ParamType->isRecordType())
223 ParamAttrs |= llvm::ParamAttr::ByVal;
224 if (ParamType->isSignedIntegerType() &&
225 ParamType->isPromotableIntegerType())
226 ParamAttrs |= llvm::ParamAttr::SExt;
227 if (ParamType->isUnsignedIntegerType() &&
228 ParamType->isPromotableIntegerType())
229 ParamAttrs |= llvm::ParamAttr::ZExt;
230 if (ParamAttrs)
231 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(increment,
232 ParamAttrs));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000233 }
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000234
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000235 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
236 ParamAttrList.size()));
237
238 // Set the appropriate calling convention for the Function.
239 if (FD->getAttr<FastCallAttr>())
240 F->setCallingConv(llvm::CallingConv::Fast);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000241}
242
243/// SetFunctionAttributesForDefinition - Set function attributes
244/// specific to a function definition.
245void CodeGenModule::SetFunctionAttributesForDefinition(llvm::Function *F) {
246 if (!Features.Exceptions)
247 F->addParamAttr(0, llvm::ParamAttr::NoUnwind);
248}
249
250void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
251 llvm::Function *F) {
252 llvm::SmallVector<QualType, 16> ArgTypes;
253
254 ArgTypes.push_back(MD->getResultType());
255 ArgTypes.push_back(MD->getSelfDecl()->getType());
256 ArgTypes.push_back(Context.getObjCSelType());
257 for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(),
258 e = MD->param_end(); i != e; ++i)
259 ArgTypes.push_back((*i)->getType());
260
261 SetFunctionAttributesFromTypes(MD, F, ArgTypes);
262
263 SetFunctionAttributesForDefinition(F);
264
265 // FIXME: set visibility
266}
267
268void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
269 llvm::Function *F) {
270 llvm::SmallVector<QualType, 16> ArgTypes;
271 const FunctionType *FTy = FD->getType()->getAsFunctionType();
272 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FTy);
273
274 ArgTypes.push_back(FTy->getResultType());
275 if (FTP)
276 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
277 ArgTypes.push_back(FTP->getArgType(i));
278
279 SetFunctionAttributesFromTypes(FD, F, ArgTypes);
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000280
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000281 SetGlobalValueAttributes(FD, F);
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000282}
283
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000284void CodeGenModule::EmitStatics() {
285 // Emit code for each used static decl encountered. Since a previously unused
286 // static decl may become used during the generation of code for a static
287 // function, iterate until no changes are made.
288 bool Changed;
289 do {
290 Changed = false;
291 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000292 const ValueDecl *D = StaticDecls[i];
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000293
294 // Check if we have used a decl with the same name
295 // FIXME: The AST should have some sort of aggregate decls or
296 // global symbol map.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000297 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbara735ad82008-08-06 00:03:29 +0000298 continue;
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000299
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000300 // Emit the definition.
301 EmitGlobalDefinition(D);
302
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000303 // Erase the used decl from the list.
304 StaticDecls[i] = StaticDecls.back();
305 StaticDecls.pop_back();
306 --i;
307 --e;
308
309 // Remember that we made a change.
310 Changed = true;
311 }
312 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000313}
314
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000315/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
316/// annotation information for a given GlobalValue. The annotation struct is
317/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000318/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000319/// created from the AnnotateAttr's annotation. The third field is a constant
320/// string containing the name of the translation unit. The fourth field is
321/// the line number in the file of the annotated value declaration.
322///
323/// FIXME: this does not unique the annotation string constants, as llvm-gcc
324/// appears to.
325///
326llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
327 const AnnotateAttr *AA,
328 unsigned LineNo) {
329 llvm::Module *M = &getModule();
330
331 // get [N x i8] constants for the annotation string, and the filename string
332 // which are the 2nd and 3rd elements of the global annotation structure.
333 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
334 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
335 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
336 true);
337
338 // Get the two global values corresponding to the ConstantArrays we just
339 // created to hold the bytes of the strings.
340 llvm::GlobalValue *annoGV =
341 new llvm::GlobalVariable(anno->getType(), false,
342 llvm::GlobalValue::InternalLinkage, anno,
343 GV->getName() + ".str", M);
344 // translation unit name string, emitted into the llvm.metadata section.
345 llvm::GlobalValue *unitGV =
346 new llvm::GlobalVariable(unit->getType(), false,
347 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
348
349 // Create the ConstantStruct that is the global annotion.
350 llvm::Constant *Fields[4] = {
351 llvm::ConstantExpr::getBitCast(GV, SBP),
352 llvm::ConstantExpr::getBitCast(annoGV, SBP),
353 llvm::ConstantExpr::getBitCast(unitGV, SBP),
354 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
355 };
356 return llvm::ConstantStruct::get(Fields, 4, false);
357}
358
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000359void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
360 bool isDef, isStatic;
361
362 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
363 isDef = (FD->isThisDeclarationADefinition() ||
364 FD->getAttr<AliasAttr>());
365 isStatic = FD->getStorageClass() == FunctionDecl::Static;
366 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
367 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
368
369 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
370 isStatic = VD->getStorageClass() == VarDecl::Static;
371 } else {
372 assert(0 && "Invalid argument to EmitGlobal");
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000373 return;
374 }
375
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000376 // Forward declarations are emitted lazily on first use.
377 if (!isDef)
Chris Lattner88a69ad2007-07-13 05:13:43 +0000378 return;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000379
380 // If the global is a static, defer code generation until later so
381 // we can easily omit unused statics.
382 if (isStatic) {
383 StaticDecls.push_back(Global);
384 return;
385 }
386
387 // Otherwise emit the definition.
388 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000389}
390
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000391void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
392 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
393 EmitGlobalFunctionDefinition(FD);
394 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
395 EmitGlobalVarDefinition(VD);
396 } else {
397 assert(0 && "Invalid argument to EmitGlobalDefinition()");
398 }
399}
400
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000401 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000402 assert(D->hasGlobalStorage() && "Not a global variable");
403
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000404 QualType ASTTy = D->getType();
405 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000406 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000407
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000408 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000409 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000410 if (!Entry)
411 Entry = new llvm::GlobalVariable(Ty, false,
412 llvm::GlobalValue::ExternalLinkage,
413 0, D->getName(), &getModule(), 0,
414 ASTTy.getAddressSpace());
415
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000416 // Make sure the result is of the correct type.
417 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000418}
419
420void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000421 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000422 QualType ASTTy = D->getType();
423 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000424
Chris Lattner8f32f712007-07-14 00:23:28 +0000425 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000426 // This is a tentative definition; tentative definitions are
427 // implicitly initialized with { 0 }
428 const llvm::Type* InitTy;
429 if (ASTTy->isIncompleteArrayType()) {
430 // An incomplete array is normally [ TYPE x 0 ], but we need
431 // to fix it to [ TYPE x 1 ].
432 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
433 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
434 } else {
435 InitTy = VarTy;
436 }
437 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000438 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000439 Init = EmitConstantExpr(D->getInit());
Eli Friedman77ba7082008-05-30 19:50:47 +0000440 }
441 const llvm::Type* InitType = Init->getType();
442
Daniel Dunbar90db8822008-08-25 06:18:57 +0000443 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000444 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
445
Eli Friedman77ba7082008-05-30 19:50:47 +0000446 if (!GV) {
447 GV = new llvm::GlobalVariable(InitType, false,
448 llvm::GlobalValue::ExternalLinkage,
449 0, D->getName(), &getModule(), 0,
450 ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000451 } else if (GV->getType() !=
452 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000453 // We have a definition after a prototype with the wrong type.
454 // We must make a new GlobalVariable* and update everything that used OldGV
455 // (a declaration or tentative definition) with the new GlobalVariable*
456 // (which will be a definition).
457 //
458 // This happens if there is a prototype for a global (e.g. "extern int x[];")
459 // and then a definition of a different type (e.g. "int x[10];"). This also
460 // happens when an initializer has a different type from the type of the
461 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000462 //
463 // FIXME: This also ends up happening if there's a definition followed by
464 // a tentative definition! (Although Sema rejects that construct
465 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000466
467 // Save the old global
468 llvm::GlobalVariable *OldGV = GV;
469
470 // Make a new global with the correct type
471 GV = new llvm::GlobalVariable(InitType, false,
472 llvm::GlobalValue::ExternalLinkage,
473 0, D->getName(), &getModule(), 0,
474 ASTTy.getAddressSpace());
475 // Steal the name of the old global
476 GV->takeName(OldGV);
477
478 // Replace all uses of the old global with the new global
479 llvm::Constant *NewPtrForOldDecl =
480 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
481 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000482
483 // Erase the old global, since it is no longer used.
484 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000485 }
Devang Patel8e53e722007-10-26 16:31:40 +0000486
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000487 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000488
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000489 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
490 SourceManager &SM = Context.getSourceManager();
491 AddAnnotation(EmitAnnotateAttr(GV, AA,
492 SM.getLogicalLineNumber(D->getLocation())));
493 }
494
Chris Lattner88a69ad2007-07-13 05:13:43 +0000495 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000496 GV->setConstant(D->getType().isConstant(Context));
Chris Lattnerddee4232008-03-03 03:28:21 +0000497
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000498 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
499 unsigned Align;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000500 if (const IncompleteArrayType* IAT =
501 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000502 Align = Context.getTypeAlign(IAT->getElementType());
503 else
504 Align = Context.getTypeAlign(D->getType());
Eli Friedman08d78022008-05-29 11:10:27 +0000505 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
506 Align = std::max(Align, AA->getAlignment());
507 }
508 GV->setAlignment(Align / 8);
509
Chris Lattnerddee4232008-03-03 03:28:21 +0000510 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000511 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000512 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000513
514 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
515 // Prefaced with special LLVM marker to indicate that the name
516 // should not be munged.
517 GV->setName("\01" + ALA->getLabel());
518 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000519
520 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000521 if (D->getStorageClass() == VarDecl::Static)
522 GV->setLinkage(llvm::Function::InternalLinkage);
523 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000524 GV->setLinkage(llvm::Function::DLLImportLinkage);
525 else if (D->getAttr<DLLExportAttr>())
526 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000527 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000528 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000529 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000530 // FIXME: This isn't right. This should handle common linkage and other
531 // stuff.
532 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000533 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000534 case VarDecl::Auto:
535 case VarDecl::Register:
536 assert(0 && "Can't have auto or register globals");
537 case VarDecl::None:
538 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000539 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000540 break;
541 case VarDecl::Extern:
542 case VarDecl::PrivateExtern:
543 // todo: common
544 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000545 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000546 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000547
548 // Emit global variable debug information.
549 CGDebugInfo *DI = getDebugInfo();
550 if(DI) {
551 if(D->getLocation().isValid())
552 DI->setLocation(D->getLocation());
553 DI->EmitGlobalVariable(GV, D);
554 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000555}
Reid Spencer5f016e22007-07-11 17:01:13 +0000556
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000557llvm::GlobalValue *
558CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
559 // FIXME: param attributes for sext/zext etc.
560 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
561 assert(!D->getBody() && "Unexpected alias attr on function with body.");
562
563 const std::string& aliaseeName = AA->getAliasee();
564 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
565 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
566 llvm::Function::ExternalLinkage,
567 D->getName(),
568 aliasee,
569 &getModule());
570 SetGlobalValueAttributes(D, alias);
571 return alias;
572 } else {
573 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000574 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000575 llvm::Function::ExternalLinkage,
576 D->getName(), &getModule());
577
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000578 SetFunctionAttributes(D, F);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000579 return F;
580 }
581}
582
583llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000584 QualType ASTTy = D->getType();
585 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
586 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000587
588 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000589 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000590 if (!Entry)
591 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000592
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000593 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000594}
595
596void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar90db8822008-08-25 06:18:57 +0000597 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000598 if (!Entry) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000599 Entry = EmitForwardFunctionDefinition(D);
600 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000601 // If the types mismatch then we have to rewrite the definition.
602 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
603 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000604 // Otherwise, we have a definition after a prototype with the wrong type.
605 // F is the Function* for the one with the wrong type, we must make a new
606 // Function* and update everything that used F (a declaration) with the new
607 // Function* (which will be a definition).
608 //
609 // This happens if there is a prototype for a function (e.g. "int f()") and
610 // then a definition of a different type (e.g. "int f(int x)"). Start by
611 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000612 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
613 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000614
615 // Replace uses of F with the Function we will endow with a body.
616 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000617 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
618 Entry->replaceAllUsesWith(NewPtrForOldDecl);
619
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000620 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000621 // FIXME: Add GlobalValue->eraseFromParent().
622 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
623 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
624 F->eraseFromParent();
625 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
626 GA->eraseFromParent();
627 } else {
628 assert(0 && "Invalid global variable type.");
629 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000630
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000631 Entry = NewFn;
632 }
633 }
634
635 if (D->getAttr<AliasAttr>()) {
636 ;
637 } else {
638 llvm::Function *Fn = cast<llvm::Function>(Entry);
639 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000640
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000641 SetFunctionAttributesForDefinition(Fn);
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000642
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000643 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
644 AddGlobalCtor(Fn, CA->getPriority());
645 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
646 AddGlobalDtor(Fn, DA->getPriority());
647 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000648 }
649}
650
Chris Lattnerc5b88062008-02-06 05:08:19 +0000651void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
652 // Make sure that this type is translated.
653 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000654}
655
656
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000657/// getBuiltinLibFunction
658llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000659 if (BuiltinID > BuiltinFunctions.size())
660 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000661
Chris Lattner1426fec2007-12-13 00:38:03 +0000662 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
663 // a slot for it.
664 assert(BuiltinID && "Invalid Builtin ID");
665 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000666 if (FunctionSlot)
667 return FunctionSlot;
668
669 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
670
671 // Get the name, skip over the __builtin_ prefix.
672 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
673
674 // Get the type for the builtin.
675 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
676 const llvm::FunctionType *Ty =
677 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
678
679 // FIXME: This has a serious problem with code like this:
680 // void abs() {}
681 // ... __builtin_abs(x);
682 // The two versions of abs will collide. The fix is for the builtin to win,
683 // and for the existing one to be turned into a constantexpr cast of the
684 // builtin. In the case where the existing one is a static function, it
685 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000686 if (llvm::Function *Existing = getModule().getFunction(Name)) {
687 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
688 return FunctionSlot = Existing;
689 assert(Existing == 0 && "FIXME: Name collision");
690 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000691
692 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000693 return FunctionSlot =
694 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
695 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000696}
697
Chris Lattner7acda7c2007-12-18 00:25:38 +0000698llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
699 unsigned NumTys) {
700 return llvm::Intrinsic::getDeclaration(&getModule(),
701 (llvm::Intrinsic::ID)IID, Tys, NumTys);
702}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000703
Reid Spencer5f016e22007-07-11 17:01:13 +0000704llvm::Function *CodeGenModule::getMemCpyFn() {
705 if (MemCpyFn) return MemCpyFn;
706 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000707 switch (Context.Target.getPointerWidth(0)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000708 default: assert(0 && "Unknown ptr width");
709 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
710 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
711 }
Chris Lattner7acda7c2007-12-18 00:25:38 +0000712 return MemCpyFn = getIntrinsic(IID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000713}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000714
Eli Friedman0c995092008-05-26 12:59:39 +0000715llvm::Function *CodeGenModule::getMemMoveFn() {
716 if (MemMoveFn) return MemMoveFn;
717 llvm::Intrinsic::ID IID;
718 switch (Context.Target.getPointerWidth(0)) {
719 default: assert(0 && "Unknown ptr width");
720 case 32: IID = llvm::Intrinsic::memmove_i32; break;
721 case 64: IID = llvm::Intrinsic::memmove_i64; break;
722 }
723 return MemMoveFn = getIntrinsic(IID);
724}
725
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000726llvm::Function *CodeGenModule::getMemSetFn() {
727 if (MemSetFn) return MemSetFn;
728 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000729 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000730 default: assert(0 && "Unknown ptr width");
731 case 32: IID = llvm::Intrinsic::memset_i32; break;
732 case 64: IID = llvm::Intrinsic::memset_i64; break;
733 }
734 return MemSetFn = getIntrinsic(IID);
735}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000736
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000737// We still need to work out the details of handling UTF-16.
738// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000739llvm::Constant *CodeGenModule::
740GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000741 llvm::StringMapEntry<llvm::Constant *> &Entry =
742 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
743
744 if (Entry.getValue())
745 return Entry.getValue();
746
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000747 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
748 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +0000749
750 if (!CFConstantStringClassRef) {
751 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
752 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000753
754 // FIXME: This is fairly broken if
755 // __CFConstantStringClassReference is already defined, in that it
756 // will get renamed and the user will most likely see an opaque
757 // error message. This is a general issue with relying on
758 // particular names.
759 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +0000760 new llvm::GlobalVariable(Ty, false,
761 llvm::GlobalVariable::ExternalLinkage, 0,
762 "__CFConstantStringClassReference",
763 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000764
765 // Decay array -> ptr
766 CFConstantStringClassRef =
767 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000768 }
769
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000770 std::vector<llvm::Constant*> Fields(4);
771
Anders Carlssonc9e20912007-08-21 00:21:21 +0000772 // Class pointer.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000773 Fields[0] = CFConstantStringClassRef;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000774
775 // Flags.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000776 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
777 Fields[1] = llvm::ConstantInt::get(Ty, 0x07C8);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000778
779 // String pointer.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000780 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000781 C = new llvm::GlobalVariable(C->getType(), true,
782 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000783 C, ".str", &getModule());
784 Fields[2] = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000785
786 // String length.
787 Ty = getTypes().ConvertType(getContext().LongTy);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000788 Fields[3] = llvm::ConstantInt::get(Ty, str.length());
Anders Carlssonc9e20912007-08-21 00:21:21 +0000789
790 // The struct.
791 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
792 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000793 llvm::GlobalVariable *GV =
794 new llvm::GlobalVariable(C->getType(), true,
795 llvm::GlobalVariable::InternalLinkage,
796 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000797
Anders Carlsson0c678292007-11-01 00:41:52 +0000798 GV->setSection("__DATA,__cfstring");
799 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000800
Anders Carlsson0c678292007-11-01 00:41:52 +0000801 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000802}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000803
Daniel Dunbar61432932008-08-13 23:20:05 +0000804/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +0000805/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +0000806std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000807 if (E->isWide()) {
808 ErrorUnsupported(E, "wide string");
809 return "FIXME";
810 }
811
Daniel Dunbar1e049762008-08-10 20:25:57 +0000812 const char *StrData = E->getStrData();
813 unsigned Len = E->getByteLength();
814
815 const ConstantArrayType *CAT =
816 getContext().getAsConstantArrayType(E->getType());
817 assert(CAT && "String isn't pointer or array!");
818
819 // Resize the string to the right size
820 // FIXME: What about wchar_t strings?
821 std::string Str(StrData, StrData+Len);
822 uint64_t RealLen = CAT->getSize().getZExtValue();
823 Str.resize(RealLen, '\0');
824
825 return Str;
826}
827
Daniel Dunbar61432932008-08-13 23:20:05 +0000828/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
829/// constant array for the given string literal.
830llvm::Constant *
831CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
832 // FIXME: This can be more efficient.
833 return GetAddrOfConstantString(GetStringForStringLiteral(S));
834}
835
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000836/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000837static llvm::Constant *GenerateStringLiteral(const std::string &str,
838 bool constant,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000839 CodeGenModule &CGM) {
Daniel Dunbar61432932008-08-13 23:20:05 +0000840 // Create Constant for this string literal. Don't add a '\0'.
841 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000842
843 // Create a global variable for this string
844 C = new llvm::GlobalVariable(C->getType(), constant,
845 llvm::GlobalValue::InternalLinkage,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000846 C, ".str", &CGM.getModule());
Daniel Dunbar61432932008-08-13 23:20:05 +0000847
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000848 return C;
849}
850
Daniel Dunbar61432932008-08-13 23:20:05 +0000851/// GetAddrOfConstantString - Returns a pointer to a character array
852/// containing the literal. This contents are exactly that of the
853/// given string, i.e. it will not be null terminated automatically;
854/// see GetAddrOfConstantCString. Note that whether the result is
855/// actually a pointer to an LLVM constant depends on
856/// Feature.WriteableStrings.
857///
858/// The result has pointer to array type.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000859llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
860 // Don't share any string literals if writable-strings is turned on.
861 if (Features.WritableStrings)
862 return GenerateStringLiteral(str, false, *this);
863
864 llvm::StringMapEntry<llvm::Constant *> &Entry =
865 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
866
867 if (Entry.getValue())
868 return Entry.getValue();
869
870 // Create a global variable for this.
871 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
872 Entry.setValue(C);
873 return C;
874}
Daniel Dunbar61432932008-08-13 23:20:05 +0000875
876/// GetAddrOfConstantCString - Returns a pointer to a character
877/// array containing the literal and a terminating '\-'
878/// character. The result has pointer to array type.
879llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str) {
Daniel Dunbar9d9b09c2008-08-15 18:29:12 +0000880 return GetAddrOfConstantString(str + "\0");
Daniel Dunbar61432932008-08-13 23:20:05 +0000881}
Daniel Dunbar41071de2008-08-15 23:26:23 +0000882
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000883/// EmitObjCPropertyImplementations - Emit information for synthesized
884/// properties for an implementation.
885void CodeGenModule::EmitObjCPropertyImplementations(const
886 ObjCImplementationDecl *D) {
887 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
888 e = D->propimpl_end(); i != e; ++i) {
889 ObjCPropertyImplDecl *PID = *i;
890
891 // Dynamic is just for type-checking.
892 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
893 ObjCPropertyDecl *PD = PID->getPropertyDecl();
894
895 // Determine which methods need to be implemented, some may have
896 // been overridden. Note that ::isSynthesized is not the method
897 // we want, that just indicates if the decl came from a
898 // property. What we want to know is if the method is defined in
899 // this implementation.
900 if (!D->getInstanceMethod(PD->getGetterName()))
901 CodeGenFunction(*this).GenerateObjCGetter(PID);
902 if (!PD->isReadOnly() &&
903 !D->getInstanceMethod(PD->getSetterName()))
904 CodeGenFunction(*this).GenerateObjCSetter(PID);
905 }
906 }
907}
908
Daniel Dunbar41071de2008-08-15 23:26:23 +0000909/// EmitTopLevelDecl - Emit code for a single top level declaration.
910void CodeGenModule::EmitTopLevelDecl(Decl *D) {
911 // If an error has occurred, stop code generation, but continue
912 // parsing and semantic analysis (to ensure all warnings and errors
913 // are emitted).
914 if (Diags.hasErrorOccurred())
915 return;
916
917 switch (D->getKind()) {
918 case Decl::Function:
919 case Decl::Var:
920 EmitGlobal(cast<ValueDecl>(D));
921 break;
922
923 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +0000924 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +0000925 break;
926
927 // Objective-C Decls
928
929 // Forward declarations, no (immediate) code generation.
930 case Decl::ObjCClass:
931 case Decl::ObjCCategory:
932 case Decl::ObjCForwardProtocol:
933 case Decl::ObjCInterface:
934 break;
935
936 case Decl::ObjCProtocol:
937 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
938 break;
939
940 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000941 // Categories have properties but don't support synthesize so we
942 // can ignore them here.
943
Daniel Dunbar41071de2008-08-15 23:26:23 +0000944 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
945 break;
946
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000947 case Decl::ObjCImplementation: {
948 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
949 EmitObjCPropertyImplementations(OMD);
950 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +0000951 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000952 }
Daniel Dunbar41071de2008-08-15 23:26:23 +0000953 case Decl::ObjCMethod: {
954 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
955 // If this is not a prototype, emit the body.
956 if (OMD->getBody())
957 CodeGenFunction(*this).GenerateObjCMethod(OMD);
958 break;
959 }
Daniel Dunbar41071de2008-08-15 23:26:23 +0000960 case Decl::ObjCCompatibleAlias:
Daniel Dunbar662174c82008-08-29 17:28:43 +0000961 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar41071de2008-08-15 23:26:23 +0000962 break;
963
964 case Decl::LinkageSpec: {
965 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
966 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +0000967 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +0000968 // FIXME: implement C++ linkage, C linkage works mostly by C
969 // language reuse already.
970 break;
971 }
972
973 case Decl::FileScopeAsm: {
974 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
975 std::string AsmString(AD->getAsmString()->getStrData(),
976 AD->getAsmString()->getByteLength());
977
978 const std::string &S = getModule().getModuleInlineAsm();
979 if (S.empty())
980 getModule().setModuleInlineAsm(AsmString);
981 else
982 getModule().setModuleInlineAsm(S + '\n' + AsmString);
983 break;
984 }
985
986 default:
987 // Make sure we handled everything we should, every other kind is
988 // a non-top-level decl. FIXME: Would be nice to have an
989 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
990 // that easily.
991 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
992 }
993}
994