blob: 87f5c24b82417ceef4c22aadb875e02cdd5cd784 [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
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000199void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
200 llvm::Function *F,
201 const llvm::FunctionType *FTy) {
202 unsigned FuncAttrs = 0;
203 if (FD->getAttr<NoThrowAttr>())
204 FuncAttrs |= llvm::ParamAttr::NoUnwind;
205 if (FD->getAttr<NoReturnAttr>())
206 FuncAttrs |= llvm::ParamAttr::NoReturn;
207
208 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
209 if (FuncAttrs)
210 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
211 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000212 bool AggregateReturn = CodeGenFunction::hasAggregateLLVMType(FD->getResultType());
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000213 if (AggregateReturn)
214 ParamAttrList.push_back(
215 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
216 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000217 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
218 if (FTP) {
219 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
220 QualType ParamType = FTP->getArgType(i);
221 unsigned ParamAttrs = 0;
222 if (ParamType->isRecordType())
223 ParamAttrs |= llvm::ParamAttr::ByVal;
Chris Lattnera4210072008-06-26 05:08:00 +0000224 if (ParamType->isSignedIntegerType() &&
225 ParamType->isPromotableIntegerType())
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000226 ParamAttrs |= llvm::ParamAttr::SExt;
Chris Lattnera4210072008-06-26 05:08:00 +0000227 if (ParamType->isUnsignedIntegerType() &&
228 ParamType->isPromotableIntegerType())
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000229 ParamAttrs |= llvm::ParamAttr::ZExt;
230 if (ParamAttrs)
231 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
232 ParamAttrs));
233 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000234 }
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000235
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000236 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
237 ParamAttrList.size()));
238
239 // Set the appropriate calling convention for the Function.
240 if (FD->getAttr<FastCallAttr>())
241 F->setCallingConv(llvm::CallingConv::Fast);
242
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000243 SetGlobalValueAttributes(FD, F);
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000244}
245
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000246void CodeGenModule::EmitStatics() {
247 // Emit code for each used static decl encountered. Since a previously unused
248 // static decl may become used during the generation of code for a static
249 // function, iterate until no changes are made.
250 bool Changed;
251 do {
252 Changed = false;
253 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000254 const ValueDecl *D = StaticDecls[i];
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000255
256 // Check if we have used a decl with the same name
257 // FIXME: The AST should have some sort of aggregate decls or
258 // global symbol map.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000259 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbara735ad82008-08-06 00:03:29 +0000260 continue;
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000261
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000262 // Emit the definition.
263 EmitGlobalDefinition(D);
264
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000265 // Erase the used decl from the list.
266 StaticDecls[i] = StaticDecls.back();
267 StaticDecls.pop_back();
268 --i;
269 --e;
270
271 // Remember that we made a change.
272 Changed = true;
273 }
274 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000275}
276
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000277/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
278/// annotation information for a given GlobalValue. The annotation struct is
279/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000280/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000281/// created from the AnnotateAttr's annotation. The third field is a constant
282/// string containing the name of the translation unit. The fourth field is
283/// the line number in the file of the annotated value declaration.
284///
285/// FIXME: this does not unique the annotation string constants, as llvm-gcc
286/// appears to.
287///
288llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
289 const AnnotateAttr *AA,
290 unsigned LineNo) {
291 llvm::Module *M = &getModule();
292
293 // get [N x i8] constants for the annotation string, and the filename string
294 // which are the 2nd and 3rd elements of the global annotation structure.
295 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
296 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
297 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
298 true);
299
300 // Get the two global values corresponding to the ConstantArrays we just
301 // created to hold the bytes of the strings.
302 llvm::GlobalValue *annoGV =
303 new llvm::GlobalVariable(anno->getType(), false,
304 llvm::GlobalValue::InternalLinkage, anno,
305 GV->getName() + ".str", M);
306 // translation unit name string, emitted into the llvm.metadata section.
307 llvm::GlobalValue *unitGV =
308 new llvm::GlobalVariable(unit->getType(), false,
309 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
310
311 // Create the ConstantStruct that is the global annotion.
312 llvm::Constant *Fields[4] = {
313 llvm::ConstantExpr::getBitCast(GV, SBP),
314 llvm::ConstantExpr::getBitCast(annoGV, SBP),
315 llvm::ConstantExpr::getBitCast(unitGV, SBP),
316 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
317 };
318 return llvm::ConstantStruct::get(Fields, 4, false);
319}
320
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000321void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
322 bool isDef, isStatic;
323
324 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
325 isDef = (FD->isThisDeclarationADefinition() ||
326 FD->getAttr<AliasAttr>());
327 isStatic = FD->getStorageClass() == FunctionDecl::Static;
328 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
329 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
330
331 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
332 isStatic = VD->getStorageClass() == VarDecl::Static;
333 } else {
334 assert(0 && "Invalid argument to EmitGlobal");
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000335 return;
336 }
337
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000338 // Forward declarations are emitted lazily on first use.
339 if (!isDef)
Chris Lattner88a69ad2007-07-13 05:13:43 +0000340 return;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000341
342 // If the global is a static, defer code generation until later so
343 // we can easily omit unused statics.
344 if (isStatic) {
345 StaticDecls.push_back(Global);
346 return;
347 }
348
349 // Otherwise emit the definition.
350 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000351}
352
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000353void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
354 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
355 EmitGlobalFunctionDefinition(FD);
356 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
357 EmitGlobalVarDefinition(VD);
358 } else {
359 assert(0 && "Invalid argument to EmitGlobalDefinition()");
360 }
361}
362
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000363 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000364 assert(D->hasGlobalStorage() && "Not a global variable");
365
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000366 QualType ASTTy = D->getType();
367 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000368 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000369
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000370 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000371 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000372 if (!Entry)
373 Entry = new llvm::GlobalVariable(Ty, false,
374 llvm::GlobalValue::ExternalLinkage,
375 0, D->getName(), &getModule(), 0,
376 ASTTy.getAddressSpace());
377
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000378 // Make sure the result is of the correct type.
379 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000380}
381
382void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000383 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000384 QualType ASTTy = D->getType();
385 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000386
Chris Lattner8f32f712007-07-14 00:23:28 +0000387 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000388 // This is a tentative definition; tentative definitions are
389 // implicitly initialized with { 0 }
390 const llvm::Type* InitTy;
391 if (ASTTy->isIncompleteArrayType()) {
392 // An incomplete array is normally [ TYPE x 0 ], but we need
393 // to fix it to [ TYPE x 1 ].
394 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
395 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
396 } else {
397 InitTy = VarTy;
398 }
399 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000400 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000401 Init = EmitConstantExpr(D->getInit());
Eli Friedman77ba7082008-05-30 19:50:47 +0000402 }
403 const llvm::Type* InitType = Init->getType();
404
Daniel Dunbar90db8822008-08-25 06:18:57 +0000405 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000406 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
407
Eli Friedman77ba7082008-05-30 19:50:47 +0000408 if (!GV) {
409 GV = new llvm::GlobalVariable(InitType, false,
410 llvm::GlobalValue::ExternalLinkage,
411 0, D->getName(), &getModule(), 0,
412 ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000413 } else if (GV->getType() !=
414 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000415 // We have a definition after a prototype with the wrong type.
416 // We must make a new GlobalVariable* and update everything that used OldGV
417 // (a declaration or tentative definition) with the new GlobalVariable*
418 // (which will be a definition).
419 //
420 // This happens if there is a prototype for a global (e.g. "extern int x[];")
421 // and then a definition of a different type (e.g. "int x[10];"). This also
422 // happens when an initializer has a different type from the type of the
423 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000424 //
425 // FIXME: This also ends up happening if there's a definition followed by
426 // a tentative definition! (Although Sema rejects that construct
427 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000428
429 // Save the old global
430 llvm::GlobalVariable *OldGV = GV;
431
432 // Make a new global with the correct type
433 GV = new llvm::GlobalVariable(InitType, false,
434 llvm::GlobalValue::ExternalLinkage,
435 0, D->getName(), &getModule(), 0,
436 ASTTy.getAddressSpace());
437 // Steal the name of the old global
438 GV->takeName(OldGV);
439
440 // Replace all uses of the old global with the new global
441 llvm::Constant *NewPtrForOldDecl =
442 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
443 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000444
445 // Erase the old global, since it is no longer used.
446 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000447 }
Devang Patel8e53e722007-10-26 16:31:40 +0000448
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000449 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000450
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000451 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
452 SourceManager &SM = Context.getSourceManager();
453 AddAnnotation(EmitAnnotateAttr(GV, AA,
454 SM.getLogicalLineNumber(D->getLocation())));
455 }
456
Chris Lattner88a69ad2007-07-13 05:13:43 +0000457 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000458 GV->setConstant(D->getType().isConstant(Context));
Chris Lattnerddee4232008-03-03 03:28:21 +0000459
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000460 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
461 unsigned Align;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000462 if (const IncompleteArrayType* IAT =
463 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000464 Align = Context.getTypeAlign(IAT->getElementType());
465 else
466 Align = Context.getTypeAlign(D->getType());
Eli Friedman08d78022008-05-29 11:10:27 +0000467 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
468 Align = std::max(Align, AA->getAlignment());
469 }
470 GV->setAlignment(Align / 8);
471
Chris Lattnerddee4232008-03-03 03:28:21 +0000472 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000473 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000474 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000475
476 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
477 // Prefaced with special LLVM marker to indicate that the name
478 // should not be munged.
479 GV->setName("\01" + ALA->getLabel());
480 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000481
482 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000483 if (D->getStorageClass() == VarDecl::Static)
484 GV->setLinkage(llvm::Function::InternalLinkage);
485 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000486 GV->setLinkage(llvm::Function::DLLImportLinkage);
487 else if (D->getAttr<DLLExportAttr>())
488 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000489 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000490 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000491 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000492 // FIXME: This isn't right. This should handle common linkage and other
493 // stuff.
494 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000495 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000496 case VarDecl::Auto:
497 case VarDecl::Register:
498 assert(0 && "Can't have auto or register globals");
499 case VarDecl::None:
500 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000501 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000502 break;
503 case VarDecl::Extern:
504 case VarDecl::PrivateExtern:
505 // todo: common
506 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000507 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000508 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000509
510 // Emit global variable debug information.
511 CGDebugInfo *DI = getDebugInfo();
512 if(DI) {
513 if(D->getLocation().isValid())
514 DI->setLocation(D->getLocation());
515 DI->EmitGlobalVariable(GV, D);
516 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000517}
Reid Spencer5f016e22007-07-11 17:01:13 +0000518
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000519llvm::GlobalValue *
520CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
521 // FIXME: param attributes for sext/zext etc.
522 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
523 assert(!D->getBody() && "Unexpected alias attr on function with body.");
524
525 const std::string& aliaseeName = AA->getAliasee();
526 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
527 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
528 llvm::Function::ExternalLinkage,
529 D->getName(),
530 aliasee,
531 &getModule());
532 SetGlobalValueAttributes(D, alias);
533 return alias;
534 } else {
535 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
536 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
537 llvm::Function *F = llvm::Function::Create(FTy,
538 llvm::Function::ExternalLinkage,
539 D->getName(), &getModule());
540
541 SetFunctionAttributes(D, F, FTy);
542 return F;
543 }
544}
545
546llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000547 QualType ASTTy = D->getType();
548 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
549 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000550
551 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000552 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000553 if (!Entry)
554 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000555
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000556 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000557}
558
559void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar90db8822008-08-25 06:18:57 +0000560 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000561 if (!Entry) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000562 Entry = EmitForwardFunctionDefinition(D);
563 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000564 // If the types mismatch then we have to rewrite the definition.
565 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
566 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000567 // Otherwise, we have a definition after a prototype with the wrong type.
568 // F is the Function* for the one with the wrong type, we must make a new
569 // Function* and update everything that used F (a declaration) with the new
570 // Function* (which will be a definition).
571 //
572 // This happens if there is a prototype for a function (e.g. "int f()") and
573 // then a definition of a different type (e.g. "int f(int x)"). Start by
574 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000575 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
576 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000577
578 // Replace uses of F with the Function we will endow with a body.
579 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000580 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
581 Entry->replaceAllUsesWith(NewPtrForOldDecl);
582
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000583 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000584 // FIXME: Add GlobalValue->eraseFromParent().
585 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
586 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
587 F->eraseFromParent();
588 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
589 GA->eraseFromParent();
590 } else {
591 assert(0 && "Invalid global variable type.");
592 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000593
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000594 Entry = NewFn;
595 }
596 }
597
598 if (D->getAttr<AliasAttr>()) {
599 ;
600 } else {
601 llvm::Function *Fn = cast<llvm::Function>(Entry);
602 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000603
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000604 // Set attributes specific to definition.
605 // FIXME: This needs to be cleaned up by clearly emitting the
606 // declaration / definition at separate times.
607 if (!Features.Exceptions)
608 Fn->addParamAttr(0, llvm::ParamAttr::NoUnwind);
609
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000610 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
611 AddGlobalCtor(Fn, CA->getPriority());
612 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
613 AddGlobalDtor(Fn, DA->getPriority());
614 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000615 }
616}
617
Chris Lattnerc5b88062008-02-06 05:08:19 +0000618void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
619 // Make sure that this type is translated.
620 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000621}
622
623
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000624/// getBuiltinLibFunction
625llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000626 if (BuiltinID > BuiltinFunctions.size())
627 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000628
Chris Lattner1426fec2007-12-13 00:38:03 +0000629 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
630 // a slot for it.
631 assert(BuiltinID && "Invalid Builtin ID");
632 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000633 if (FunctionSlot)
634 return FunctionSlot;
635
636 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
637
638 // Get the name, skip over the __builtin_ prefix.
639 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
640
641 // Get the type for the builtin.
642 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
643 const llvm::FunctionType *Ty =
644 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
645
646 // FIXME: This has a serious problem with code like this:
647 // void abs() {}
648 // ... __builtin_abs(x);
649 // The two versions of abs will collide. The fix is for the builtin to win,
650 // and for the existing one to be turned into a constantexpr cast of the
651 // builtin. In the case where the existing one is a static function, it
652 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000653 if (llvm::Function *Existing = getModule().getFunction(Name)) {
654 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
655 return FunctionSlot = Existing;
656 assert(Existing == 0 && "FIXME: Name collision");
657 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000658
659 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000660 return FunctionSlot =
661 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
662 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000663}
664
Chris Lattner7acda7c2007-12-18 00:25:38 +0000665llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
666 unsigned NumTys) {
667 return llvm::Intrinsic::getDeclaration(&getModule(),
668 (llvm::Intrinsic::ID)IID, Tys, NumTys);
669}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000670
Reid Spencer5f016e22007-07-11 17:01:13 +0000671llvm::Function *CodeGenModule::getMemCpyFn() {
672 if (MemCpyFn) return MemCpyFn;
673 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000674 switch (Context.Target.getPointerWidth(0)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000675 default: assert(0 && "Unknown ptr width");
676 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
677 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
678 }
Chris Lattner7acda7c2007-12-18 00:25:38 +0000679 return MemCpyFn = getIntrinsic(IID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000680}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000681
Eli Friedman0c995092008-05-26 12:59:39 +0000682llvm::Function *CodeGenModule::getMemMoveFn() {
683 if (MemMoveFn) return MemMoveFn;
684 llvm::Intrinsic::ID IID;
685 switch (Context.Target.getPointerWidth(0)) {
686 default: assert(0 && "Unknown ptr width");
687 case 32: IID = llvm::Intrinsic::memmove_i32; break;
688 case 64: IID = llvm::Intrinsic::memmove_i64; break;
689 }
690 return MemMoveFn = getIntrinsic(IID);
691}
692
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000693llvm::Function *CodeGenModule::getMemSetFn() {
694 if (MemSetFn) return MemSetFn;
695 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000696 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000697 default: assert(0 && "Unknown ptr width");
698 case 32: IID = llvm::Intrinsic::memset_i32; break;
699 case 64: IID = llvm::Intrinsic::memset_i64; break;
700 }
701 return MemSetFn = getIntrinsic(IID);
702}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000703
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000704// We still need to work out the details of handling UTF-16.
705// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000706llvm::Constant *CodeGenModule::
707GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000708 llvm::StringMapEntry<llvm::Constant *> &Entry =
709 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
710
711 if (Entry.getValue())
712 return Entry.getValue();
713
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000714 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
715 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +0000716
717 if (!CFConstantStringClassRef) {
718 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
719 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000720
721 // FIXME: This is fairly broken if
722 // __CFConstantStringClassReference is already defined, in that it
723 // will get renamed and the user will most likely see an opaque
724 // error message. This is a general issue with relying on
725 // particular names.
726 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +0000727 new llvm::GlobalVariable(Ty, false,
728 llvm::GlobalVariable::ExternalLinkage, 0,
729 "__CFConstantStringClassReference",
730 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000731
732 // Decay array -> ptr
733 CFConstantStringClassRef =
734 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000735 }
736
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000737 std::vector<llvm::Constant*> Fields(4);
738
Anders Carlssonc9e20912007-08-21 00:21:21 +0000739 // Class pointer.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000740 Fields[0] = CFConstantStringClassRef;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000741
742 // Flags.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000743 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
744 Fields[1] = llvm::ConstantInt::get(Ty, 0x07C8);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000745
746 // String pointer.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000747 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000748 C = new llvm::GlobalVariable(C->getType(), true,
749 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000750 C, ".str", &getModule());
751 Fields[2] = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000752
753 // String length.
754 Ty = getTypes().ConvertType(getContext().LongTy);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000755 Fields[3] = llvm::ConstantInt::get(Ty, str.length());
Anders Carlssonc9e20912007-08-21 00:21:21 +0000756
757 // The struct.
758 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
759 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000760 llvm::GlobalVariable *GV =
761 new llvm::GlobalVariable(C->getType(), true,
762 llvm::GlobalVariable::InternalLinkage,
763 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000764
Anders Carlsson0c678292007-11-01 00:41:52 +0000765 GV->setSection("__DATA,__cfstring");
766 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000767
Anders Carlsson0c678292007-11-01 00:41:52 +0000768 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000769}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000770
Daniel Dunbar61432932008-08-13 23:20:05 +0000771/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +0000772/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +0000773std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000774 if (E->isWide()) {
775 ErrorUnsupported(E, "wide string");
776 return "FIXME";
777 }
778
Daniel Dunbar1e049762008-08-10 20:25:57 +0000779 const char *StrData = E->getStrData();
780 unsigned Len = E->getByteLength();
781
782 const ConstantArrayType *CAT =
783 getContext().getAsConstantArrayType(E->getType());
784 assert(CAT && "String isn't pointer or array!");
785
786 // Resize the string to the right size
787 // FIXME: What about wchar_t strings?
788 std::string Str(StrData, StrData+Len);
789 uint64_t RealLen = CAT->getSize().getZExtValue();
790 Str.resize(RealLen, '\0');
791
792 return Str;
793}
794
Daniel Dunbar61432932008-08-13 23:20:05 +0000795/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
796/// constant array for the given string literal.
797llvm::Constant *
798CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
799 // FIXME: This can be more efficient.
800 return GetAddrOfConstantString(GetStringForStringLiteral(S));
801}
802
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000803/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000804static llvm::Constant *GenerateStringLiteral(const std::string &str,
805 bool constant,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000806 CodeGenModule &CGM) {
Daniel Dunbar61432932008-08-13 23:20:05 +0000807 // Create Constant for this string literal. Don't add a '\0'.
808 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000809
810 // Create a global variable for this string
811 C = new llvm::GlobalVariable(C->getType(), constant,
812 llvm::GlobalValue::InternalLinkage,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000813 C, ".str", &CGM.getModule());
Daniel Dunbar61432932008-08-13 23:20:05 +0000814
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000815 return C;
816}
817
Daniel Dunbar61432932008-08-13 23:20:05 +0000818/// GetAddrOfConstantString - Returns a pointer to a character array
819/// containing the literal. This contents are exactly that of the
820/// given string, i.e. it will not be null terminated automatically;
821/// see GetAddrOfConstantCString. Note that whether the result is
822/// actually a pointer to an LLVM constant depends on
823/// Feature.WriteableStrings.
824///
825/// The result has pointer to array type.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000826llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
827 // Don't share any string literals if writable-strings is turned on.
828 if (Features.WritableStrings)
829 return GenerateStringLiteral(str, false, *this);
830
831 llvm::StringMapEntry<llvm::Constant *> &Entry =
832 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
833
834 if (Entry.getValue())
835 return Entry.getValue();
836
837 // Create a global variable for this.
838 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
839 Entry.setValue(C);
840 return C;
841}
Daniel Dunbar61432932008-08-13 23:20:05 +0000842
843/// GetAddrOfConstantCString - Returns a pointer to a character
844/// array containing the literal and a terminating '\-'
845/// character. The result has pointer to array type.
846llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str) {
Daniel Dunbar9d9b09c2008-08-15 18:29:12 +0000847 return GetAddrOfConstantString(str + "\0");
Daniel Dunbar61432932008-08-13 23:20:05 +0000848}
Daniel Dunbar41071de2008-08-15 23:26:23 +0000849
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000850/// EmitObjCPropertyImplementations - Emit information for synthesized
851/// properties for an implementation.
852void CodeGenModule::EmitObjCPropertyImplementations(const
853 ObjCImplementationDecl *D) {
854 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
855 e = D->propimpl_end(); i != e; ++i) {
856 ObjCPropertyImplDecl *PID = *i;
857
858 // Dynamic is just for type-checking.
859 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
860 ObjCPropertyDecl *PD = PID->getPropertyDecl();
861
862 // Determine which methods need to be implemented, some may have
863 // been overridden. Note that ::isSynthesized is not the method
864 // we want, that just indicates if the decl came from a
865 // property. What we want to know is if the method is defined in
866 // this implementation.
867 if (!D->getInstanceMethod(PD->getGetterName()))
868 CodeGenFunction(*this).GenerateObjCGetter(PID);
869 if (!PD->isReadOnly() &&
870 !D->getInstanceMethod(PD->getSetterName()))
871 CodeGenFunction(*this).GenerateObjCSetter(PID);
872 }
873 }
874}
875
Daniel Dunbar41071de2008-08-15 23:26:23 +0000876/// EmitTopLevelDecl - Emit code for a single top level declaration.
877void CodeGenModule::EmitTopLevelDecl(Decl *D) {
878 // If an error has occurred, stop code generation, but continue
879 // parsing and semantic analysis (to ensure all warnings and errors
880 // are emitted).
881 if (Diags.hasErrorOccurred())
882 return;
883
884 switch (D->getKind()) {
885 case Decl::Function:
886 case Decl::Var:
887 EmitGlobal(cast<ValueDecl>(D));
888 break;
889
890 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +0000891 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +0000892 break;
893
894 // Objective-C Decls
895
896 // Forward declarations, no (immediate) code generation.
897 case Decl::ObjCClass:
898 case Decl::ObjCCategory:
899 case Decl::ObjCForwardProtocol:
900 case Decl::ObjCInterface:
901 break;
902
903 case Decl::ObjCProtocol:
904 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
905 break;
906
907 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000908 // Categories have properties but don't support synthesize so we
909 // can ignore them here.
910
Daniel Dunbar41071de2008-08-15 23:26:23 +0000911 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
912 break;
913
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000914 case Decl::ObjCImplementation: {
915 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
916 EmitObjCPropertyImplementations(OMD);
917 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +0000918 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000919 }
Daniel Dunbar41071de2008-08-15 23:26:23 +0000920 case Decl::ObjCMethod: {
921 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
922 // If this is not a prototype, emit the body.
923 if (OMD->getBody())
924 CodeGenFunction(*this).GenerateObjCMethod(OMD);
925 break;
926 }
Daniel Dunbar41071de2008-08-15 23:26:23 +0000927 case Decl::ObjCCompatibleAlias:
Daniel Dunbar662174c82008-08-29 17:28:43 +0000928 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar41071de2008-08-15 23:26:23 +0000929 break;
930
931 case Decl::LinkageSpec: {
932 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
933 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +0000934 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +0000935 // FIXME: implement C++ linkage, C linkage works mostly by C
936 // language reuse already.
937 break;
938 }
939
940 case Decl::FileScopeAsm: {
941 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
942 std::string AsmString(AD->getAsmString()->getStrData(),
943 AD->getAsmString()->getByteLength());
944
945 const std::string &S = getModule().getModuleInlineAsm();
946 if (S.empty())
947 getModule().setModuleInlineAsm(AsmString);
948 else
949 getModule().setModuleInlineAsm(S + '\n' + AsmString);
950 break;
951 }
952
953 default:
954 // Make sure we handled everything we should, every other kind is
955 // a non-top-level decl. FIXME: Would be nice to have an
956 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
957 // that easily.
958 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
959 }
960}
961