blob: 6faf3f88d75b13748b3c75b4ec92b416fddf8f77 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
18#include "clang/Basic/TargetInfo.h"
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000021#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "llvm/Intrinsics.h"
23using namespace clang;
24using namespace CodeGen;
25
26
Devang Patela8fccb82007-10-31 20:01:01 +000027CodeGenModule::CodeGenModule(ASTContext &C, llvm::Module &M,
28 const llvm::TargetData &TD)
29 : Context(C), TheModule(M), TheTargetData(TD),
30 Types(C, M, TD), MemCpyFn(0), CFConstantStringClassRef(0) {}
Chris Lattner4b009652007-07-25 00:24:17 +000031
Steve Naroffcb597472007-09-13 21:41:19 +000032llvm::Constant *CodeGenModule::GetAddrOfGlobalDecl(const ValueDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +000033 // See if it is already in the map.
34 llvm::Constant *&Entry = GlobalDeclMap[D];
35 if (Entry) return Entry;
36
37 QualType ASTTy = cast<ValueDecl>(D)->getType();
38 const llvm::Type *Ty = getTypes().ConvertType(ASTTy);
39 if (isa<FunctionDecl>(D)) {
40 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
41 // FIXME: param attributes for sext/zext etc.
42 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
43 D->getName(), &getModule());
44 }
45
46 assert(isa<FileVarDecl>(D) && "Unknown global decl!");
47
48 return Entry = new llvm::GlobalVariable(Ty, false,
49 llvm::GlobalValue::ExternalLinkage,
50 0, D->getName(), &getModule());
51}
52
53void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
54 // If this is not a prototype, emit the body.
55 if (FD->getBody())
56 CodeGenFunction(*this).GenerateCode(FD);
57}
58
Devang Patel08a10cc2007-10-30 21:27:20 +000059llvm::Constant *CodeGenModule::EmitGlobalInit(const FileVarDecl *D,
60 llvm::GlobalVariable *GV) {
61
62 const InitListExpr *ILE = dyn_cast<InitListExpr>(D->getInit());
63 if (!ILE)
64 return 0;
65
66 unsigned NumInitElements = ILE->getNumInits();
67
68 assert ( ILE->getType()->isArrayType()
69 && "FIXME: Only Array initializers are supported");
70
71 std::vector<llvm::Constant*> ArrayElts;
72 const llvm::PointerType *APType = cast<llvm::PointerType>(GV->getType());
73 const llvm::ArrayType *AType =
74 cast<llvm::ArrayType>(APType->getElementType());
75
76 // Copy initializer elements.
77 unsigned i = 0;
78 for (i = 0; i < NumInitElements; ++i) {
79 assert (ILE->getInit(i)->getType()->isIntegerType()
80 && "Only IntegerType global array initializers are supported");
81 llvm::APSInt
82 Value(static_cast<uint32_t>
83 (getContext().getTypeSize(ILE->getInit(i)->getType(),
84 SourceLocation())));
85 if (ILE->getInit(i)->isIntegerConstantExpr(Value, Context)) {
86 llvm::Constant *C = llvm::ConstantInt::get(Value);
87 ArrayElts.push_back(C);
88 }
89 }
90
91 // Initialize remaining array elements.
92 unsigned NumArrayElements = AType->getNumElements();
93 const llvm::Type *AElemTy = AType->getElementType();
94 for (; i < NumArrayElements; ++i)
95 ArrayElts.push_back(llvm::Constant::getNullValue(AElemTy));
96
97 return llvm::ConstantArray::get(AType, ArrayElts);
98}
99
Chris Lattner4b009652007-07-25 00:24:17 +0000100void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
101 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalDecl(D));
102
103 // If the storage class is external and there is no initializer, just leave it
104 // as a declaration.
105 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
106 return;
107
108 // Otherwise, convert the initializer, or use zero if appropriate.
109 llvm::Constant *Init = 0;
110 if (D->getInit() == 0) {
111 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
112 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000113 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000114 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000115 if (D->getInit()->isIntegerConstantExpr(Value, Context))
116 Init = llvm::ConstantInt::get(Value);
117 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000118
Devang Patel08a10cc2007-10-30 21:27:20 +0000119 if (!Init)
120 Init = EmitGlobalInit(D, GV);
Devang Patel8b5f5302007-10-26 16:31:40 +0000121
Devang Patel08a10cc2007-10-30 21:27:20 +0000122 assert(Init && "FIXME: Global variable initializers unimp!");
Chris Lattner4b009652007-07-25 00:24:17 +0000123
124 GV->setInitializer(Init);
125
126 // Set the llvm linkage type as appropriate.
127 // FIXME: This isn't right. This should handle common linkage and other
128 // stuff.
129 switch (D->getStorageClass()) {
130 case VarDecl::Auto:
131 case VarDecl::Register:
132 assert(0 && "Can't have auto or register globals");
133 case VarDecl::None:
134 case VarDecl::Extern:
135 // todo: common
136 break;
137 case VarDecl::Static:
138 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
139 break;
140 }
141}
142
143/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
144/// declarator chain.
145void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
146 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
147 EmitGlobalVar(D);
148}
149
Chris Lattnerab862cc2007-08-31 04:31:45 +0000150/// getBuiltinLibFunction
151llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
152 if (BuiltinFunctions.size() <= BuiltinID)
153 BuiltinFunctions.resize(BuiltinID);
154
155 // Already available?
156 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
157 if (FunctionSlot)
158 return FunctionSlot;
159
160 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
161
162 // Get the name, skip over the __builtin_ prefix.
163 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
164
165 // Get the type for the builtin.
166 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
167 const llvm::FunctionType *Ty =
168 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
169
170 // FIXME: This has a serious problem with code like this:
171 // void abs() {}
172 // ... __builtin_abs(x);
173 // The two versions of abs will collide. The fix is for the builtin to win,
174 // and for the existing one to be turned into a constantexpr cast of the
175 // builtin. In the case where the existing one is a static function, it
176 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000177 if (llvm::Function *Existing = getModule().getFunction(Name)) {
178 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
179 return FunctionSlot = Existing;
180 assert(Existing == 0 && "FIXME: Name collision");
181 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000182
183 // FIXME: param attributes for sext/zext etc.
184 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
185 Name, &getModule());
186}
187
188
Chris Lattner4b009652007-07-25 00:24:17 +0000189llvm::Function *CodeGenModule::getMemCpyFn() {
190 if (MemCpyFn) return MemCpyFn;
191 llvm::Intrinsic::ID IID;
192 uint64_t Size; unsigned Align;
193 Context.Target.getPointerInfo(Size, Align, SourceLocation());
194 switch (Size) {
195 default: assert(0 && "Unknown ptr width");
196 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
197 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
198 }
199 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
200}
Anders Carlsson36a04872007-08-21 00:21:21 +0000201
Chris Lattnerab862cc2007-08-31 04:31:45 +0000202llvm::Constant *CodeGenModule::
203GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000204 llvm::StringMapEntry<llvm::Constant *> &Entry =
205 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
206
207 if (Entry.getValue())
208 return Entry.getValue();
209
210 std::vector<llvm::Constant*> Fields;
211
212 if (!CFConstantStringClassRef) {
213 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
214 Ty = llvm::ArrayType::get(Ty, 0);
215
216 CFConstantStringClassRef =
217 new llvm::GlobalVariable(Ty, false,
218 llvm::GlobalVariable::ExternalLinkage, 0,
219 "__CFConstantStringClassReference",
220 &getModule());
221 }
222
223 // Class pointer.
224 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
225 llvm::Constant *Zeros[] = { Zero, Zero };
226 llvm::Constant *C =
227 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
228 Fields.push_back(C);
229
230 // Flags.
231 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
232 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
233
234 // String pointer.
235 C = llvm::ConstantArray::get(str);
236 C = new llvm::GlobalVariable(C->getType(), true,
237 llvm::GlobalValue::InternalLinkage,
238 C, ".str", &getModule());
239
240 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
241 Fields.push_back(C);
242
243 // String length.
244 Ty = getTypes().ConvertType(getContext().LongTy);
245 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
246
247 // The struct.
248 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
249 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000250 llvm::GlobalVariable *GV =
251 new llvm::GlobalVariable(C->getType(), true,
252 llvm::GlobalVariable::InternalLinkage,
253 C, "", &getModule());
254 GV->setSection("__DATA,__cfstring");
255 Entry.setValue(GV);
256 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000257}