blob: 8374f2bab6c07076c4f032c42c0e7c101a01feb9 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000018#include "clang/Basic/Diagnostic.h"
Chris Lattnerdb6be562007-11-28 05:34:05 +000019#include "clang/Basic/LangOptions.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000021#include "llvm/CallingConv.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "llvm/Constants.h"
23#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000024#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "llvm/Intrinsics.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000026#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28using namespace CodeGen;
29
30
Chris Lattnerdb6be562007-11-28 05:34:05 +000031CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000032 llvm::Module &M, const llvm::TargetData &TD,
33 Diagnostic &diags)
34 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Chris Lattnercbfb5512008-03-01 08:45:05 +000035 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
36 //TODO: Make this selectable at runtime
Chris Lattnerb326b172008-03-30 23:03:07 +000037 Runtime = CreateObjCRuntime(M,
38 getTypes().ConvertType(getContext().IntTy),
39 getTypes().ConvertType(getContext().LongTy));
Chris Lattnercbfb5512008-03-01 08:45:05 +000040}
41
42CodeGenModule::~CodeGenModule() {
Chris Lattnerb326b172008-03-30 23:03:07 +000043 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
44 if (ObjCInitFunction) {
45 AddGlobalCtor(ObjCInitFunction);
46 }
Chris Lattner753d2592008-03-14 17:18:18 +000047 EmitGlobalCtors();
Chris Lattnercbfb5512008-03-01 08:45:05 +000048 delete Runtime;
49}
Chris Lattner4b009652007-07-25 00:24:17 +000050
Chris Lattnercf9c9d02007-12-02 07:19:18 +000051/// WarnUnsupported - Print out a warning that codegen doesn't support the
52/// specified stmt yet.
53void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
54 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
55 "cannot codegen this %0 yet");
56 SourceRange Range = S->getSourceRange();
57 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000058 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000059 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000060}
Chris Lattner0e4755d2007-12-02 06:27:33 +000061
Chris Lattner806a5f52008-01-12 07:05:38 +000062/// WarnUnsupported - Print out a warning that codegen doesn't support the
63/// specified decl yet.
64void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
65 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
66 "cannot codegen this %0 yet");
67 std::string Msg = Type;
68 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
69 &Msg, 1);
70}
71
Chris Lattner753d2592008-03-14 17:18:18 +000072/// AddGlobalCtor - Add a function to the list that will be called before
73/// main() runs.
74void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
75 // TODO: Type coercion of void()* types.
76 GlobalCtors.push_back(Ctor);
77}
78
Chris Lattnerb326b172008-03-30 23:03:07 +000079/// EmitGlobalCtors - Generates the array of contsturctor functions to be
80/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner753d2592008-03-14 17:18:18 +000081void CodeGenModule::EmitGlobalCtors() {
Chris Lattnerb326b172008-03-30 23:03:07 +000082 if (GlobalCtors.empty()) return;
Chris Lattner753d2592008-03-14 17:18:18 +000083 // Get the type of @llvm.global_ctors
84 std::vector<const llvm::Type*> CtorFields;
85 CtorFields.push_back(llvm::IntegerType::get(32));
86 // Constructor function type
87 std::vector<const llvm::Type*> VoidArgs;
88 llvm::FunctionType* CtorFuncTy = llvm::FunctionType::get(
89 llvm::Type::VoidTy,
90 VoidArgs,
91 false);
92 // i32, function type pair
Chris Lattnera18c12e2008-03-19 05:24:56 +000093 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
94 llvm::StructType* CtorStructTy =
95 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner753d2592008-03-14 17:18:18 +000096 // Array of fields
Chris Lattnera18c12e2008-03-19 05:24:56 +000097 llvm::ArrayType* GlobalCtorsTy =
98 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner753d2592008-03-14 17:18:18 +000099
Chris Lattner753d2592008-03-14 17:18:18 +0000100 // Define the global variable
Chris Lattnera18c12e2008-03-19 05:24:56 +0000101 llvm::GlobalVariable *GlobalCtorsVal =
102 new llvm::GlobalVariable(GlobalCtorsTy, false,
103 llvm::GlobalValue::AppendingLinkage,
104 (llvm::Constant*)0, "llvm.global_ctors",
105 &TheModule);
Chris Lattner753d2592008-03-14 17:18:18 +0000106
107 // Populate the array
108 std::vector<llvm::Constant*> CtorValues;
Chris Lattnera18c12e2008-03-19 05:24:56 +0000109 llvm::Constant *MagicNumber =
110 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
111 std::vector<llvm::Constant*> StructValues;
Chris Lattner753d2592008-03-14 17:18:18 +0000112 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattnera18c12e2008-03-19 05:24:56 +0000113 E = GlobalCtors.end(); I != E; ++I) {
114 StructValues.clear();
Chris Lattner753d2592008-03-14 17:18:18 +0000115 StructValues.push_back(MagicNumber);
116 StructValues.push_back(*I);
117
Chris Lattnera18c12e2008-03-19 05:24:56 +0000118 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000119 }
Chris Lattnera18c12e2008-03-19 05:24:56 +0000120
121 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
122 CtorValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000123
124}
125
Chris Lattnerb326b172008-03-30 23:03:07 +0000126
127
Chris Lattner0e4755d2007-12-02 06:27:33 +0000128/// ReplaceMapValuesWith - This is a really slow and bad function that
129/// searches for any entries in GlobalDeclMap that point to OldVal, changing
130/// them to point to NewVal. This is badbadbad, FIXME!
131void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
132 llvm::Constant *NewVal) {
133 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
134 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
135 if (I->second == OldVal) I->second = NewVal;
136}
137
138
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000139llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
140 bool isDefinition) {
141 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +0000142 llvm::Constant *&Entry = GlobalDeclMap[D];
143 if (Entry) return Entry;
144
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000145 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
146
147 // Check to see if the function already exists.
148 llvm::Function *F = getModule().getFunction(D->getName());
149 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
150
151 // If it doesn't already exist, just create and return an entry.
152 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000153 // FIXME: param attributes for sext/zext etc.
Nate Begemandc6262e2008-03-09 03:09:36 +0000154 F = new llvm::Function(FTy, llvm::Function::ExternalLinkage, D->getName(),
155 &getModule());
156
157 // Set the appropriate calling convention for the Function.
158 if (D->getAttr<FastCallAttr>())
159 F->setCallingConv(llvm::CallingConv::Fast);
160 return Entry = F;
Chris Lattner4b009652007-07-25 00:24:17 +0000161 }
162
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000163 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000164 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000165 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +0000166
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000167 // If this isn't a definition, just return it casted to the right type.
168 if (!isDefinition)
169 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
170
171 // Otherwise, we have a definition after a prototype with the wrong type.
172 // F is the Function* for the one with the wrong type, we must make a new
173 // Function* and update everything that used F (a declaration) with the new
174 // Function* (which will be a definition).
175 //
176 // This happens if there is a prototype for a function (e.g. "int f()") and
177 // then a definition of a different type (e.g. "int f(int x)"). Start by
178 // making a new function of the correct type, RAUW, then steal the name.
179 llvm::Function *NewFn = new llvm::Function(FTy,
180 llvm::Function::ExternalLinkage,
181 "", &getModule());
182 NewFn->takeName(F);
183
184 // Replace uses of F with the Function we will endow with a body.
185 llvm::Constant *NewPtrForOldDecl =
186 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
187 F->replaceAllUsesWith(NewPtrForOldDecl);
188
189 // FIXME: Update the globaldeclmap for the previous decl of this name. We
190 // really want a way to walk all of these, but we don't have it yet. This
191 // is incredibly slow!
192 ReplaceMapValuesWith(F, NewPtrForOldDecl);
193
194 // Ok, delete the old function now, which is dead.
195 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
196 F->eraseFromParent();
197
198 // Return the new function which has the right type.
199 return Entry = NewFn;
200}
201
Chris Lattner0db06992008-02-05 06:37:34 +0000202static bool IsZeroElementArray(const llvm::Type *Ty) {
203 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
204 return ATy->getNumElements() == 0;
205 return false;
206}
207
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000208llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
209 bool isDefinition) {
210 assert(D->hasGlobalStorage() && "Not a global variable");
211
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000212 // See if it is already in the map.
213 llvm::Constant *&Entry = GlobalDeclMap[D];
214 if (Entry) return Entry;
215
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000216 QualType ASTTy = D->getType();
217 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000218
219 // Check to see if the global already exists.
Chris Lattnered430e92008-02-02 04:43:11 +0000220 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000221
222 // If it doesn't already exist, just create and return an entry.
223 if (GV == 0) {
224 return Entry = new llvm::GlobalVariable(Ty, false,
225 llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000226 0, D->getName(), &getModule(), 0,
227 ASTTy.getAddressSpace());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000228 }
229
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000230 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000231 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000232 if (PTy == GV->getType()) return Entry = GV;
233
234 // If this isn't a definition, just return it casted to the right type.
235 if (!isDefinition)
236 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
237
238
239 // Otherwise, we have a definition after a prototype with the wrong type.
240 // GV is the GlobalVariable* for the one with the wrong type, we must make a
241 /// new GlobalVariable* and update everything that used GV (a declaration)
242 // with the new GlobalVariable* (which will be a definition).
243 //
244 // This happens if there is a prototype for a global (e.g. "extern int x[];")
245 // and then a definition of a different type (e.g. "int x[10];"). Start by
246 // making a new global of the correct type, RAUW, then steal the name.
247 llvm::GlobalVariable *NewGV =
248 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000249 0, D->getName(), &getModule(), 0,
250 ASTTy.getAddressSpace());
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000251 NewGV->takeName(GV);
252
253 // Replace uses of GV with the globalvalue we will endow with a body.
254 llvm::Constant *NewPtrForOldDecl =
255 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
256 GV->replaceAllUsesWith(NewPtrForOldDecl);
257
258 // FIXME: Update the globaldeclmap for the previous decl of this name. We
259 // really want a way to walk all of these, but we don't have it yet. This
260 // is incredibly slow!
261 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
262
Chris Lattner0db06992008-02-05 06:37:34 +0000263 // Verify that GV was a declaration or something like x[] which turns into
264 // [0 x type].
265 assert((GV->isDeclaration() ||
266 IsZeroElementArray(GV->getType()->getElementType())) &&
267 "Shouldn't replace non-declaration");
268
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000269 // Ok, delete the old global now, which is dead.
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000270 GV->eraseFromParent();
271
272 // Return the new global which has the right type.
273 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000274}
275
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000276
Chris Lattnerb326b172008-03-30 23:03:07 +0000277void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
278 // If this is not a prototype, emit the body.
279 if (OMD->getBody())
280 CodeGenFunction(*this).GenerateObjCMethod(OMD);
281}
282
Chris Lattner4b009652007-07-25 00:24:17 +0000283void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
284 // If this is not a prototype, emit the body.
285 if (FD->getBody())
286 CodeGenFunction(*this).GenerateCode(FD);
287}
288
Anders Carlssond76cead2008-01-26 01:36:00 +0000289llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
290 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000291}
292
Chris Lattner4b009652007-07-25 00:24:17 +0000293void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000294 // If this is just a forward declaration of the variable, don't emit it now,
295 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000296 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
297 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000298
299 // Get the global, forcing it to be a direct reference.
300 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000301 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000302
303 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000304 llvm::Constant *Init = 0;
305 if (D->getInit() == 0) {
306 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
307 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000308 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner8cd0e932008-03-05 18:54:05 +0000309 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner4b009652007-07-25 00:24:17 +0000310 if (D->getInit()->isIntegerConstantExpr(Value, Context))
311 Init = llvm::ConstantInt::get(Value);
312 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000313
Devang Patel08a10cc2007-10-30 21:27:20 +0000314 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000315 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000316
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000317 assert(GV->getType()->getElementType() == Init->getType() &&
318 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000319 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000320
321 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
322 GV->setVisibility(attr->getVisibility());
323 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000324
325 // Set the llvm linkage type as appropriate.
Chris Lattner402b3372008-03-03 03:28:21 +0000326 if (D->getAttr<DLLImportAttr>())
327 GV->setLinkage(llvm::Function::DLLImportLinkage);
328 else if (D->getAttr<DLLExportAttr>())
329 GV->setLinkage(llvm::Function::DLLExportLinkage);
330 else if (D->getAttr<WeakAttr>()) {
331 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
332
333 } else {
334 // FIXME: This isn't right. This should handle common linkage and other
335 // stuff.
336 switch (D->getStorageClass()) {
337 case VarDecl::Auto:
338 case VarDecl::Register:
339 assert(0 && "Can't have auto or register globals");
340 case VarDecl::None:
341 if (!D->getInit())
342 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
343 break;
344 case VarDecl::Extern:
345 case VarDecl::PrivateExtern:
346 // todo: common
347 break;
348 case VarDecl::Static:
349 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
350 break;
351 }
Chris Lattner4b009652007-07-25 00:24:17 +0000352 }
353}
354
355/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
356/// declarator chain.
357void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
358 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
359 EmitGlobalVar(D);
360}
361
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000362void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
363 // Make sure that this type is translated.
364 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000365}
366
367
Chris Lattnerab862cc2007-08-31 04:31:45 +0000368/// getBuiltinLibFunction
369llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000370 if (BuiltinID > BuiltinFunctions.size())
371 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000372
Chris Lattner9f2d6892007-12-13 00:38:03 +0000373 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
374 // a slot for it.
375 assert(BuiltinID && "Invalid Builtin ID");
376 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000377 if (FunctionSlot)
378 return FunctionSlot;
379
380 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
381
382 // Get the name, skip over the __builtin_ prefix.
383 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
384
385 // Get the type for the builtin.
386 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
387 const llvm::FunctionType *Ty =
388 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
389
390 // FIXME: This has a serious problem with code like this:
391 // void abs() {}
392 // ... __builtin_abs(x);
393 // The two versions of abs will collide. The fix is for the builtin to win,
394 // and for the existing one to be turned into a constantexpr cast of the
395 // builtin. In the case where the existing one is a static function, it
396 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000397 if (llvm::Function *Existing = getModule().getFunction(Name)) {
398 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
399 return FunctionSlot = Existing;
400 assert(Existing == 0 && "FIXME: Name collision");
401 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000402
403 // FIXME: param attributes for sext/zext etc.
404 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
405 Name, &getModule());
406}
407
Chris Lattner4b23f942007-12-18 00:25:38 +0000408llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
409 unsigned NumTys) {
410 return llvm::Intrinsic::getDeclaration(&getModule(),
411 (llvm::Intrinsic::ID)IID, Tys, NumTys);
412}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000413
Chris Lattner4b009652007-07-25 00:24:17 +0000414llvm::Function *CodeGenModule::getMemCpyFn() {
415 if (MemCpyFn) return MemCpyFn;
416 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000417 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000418 default: assert(0 && "Unknown ptr width");
419 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
420 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
421 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000422 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000423}
Anders Carlsson36a04872007-08-21 00:21:21 +0000424
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000425llvm::Function *CodeGenModule::getMemSetFn() {
426 if (MemSetFn) return MemSetFn;
427 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000428 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000429 default: assert(0 && "Unknown ptr width");
430 case 32: IID = llvm::Intrinsic::memset_i32; break;
431 case 64: IID = llvm::Intrinsic::memset_i64; break;
432 }
433 return MemSetFn = getIntrinsic(IID);
434}
Chris Lattner4b23f942007-12-18 00:25:38 +0000435
Chris Lattnerab862cc2007-08-31 04:31:45 +0000436llvm::Constant *CodeGenModule::
437GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000438 llvm::StringMapEntry<llvm::Constant *> &Entry =
439 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
440
441 if (Entry.getValue())
442 return Entry.getValue();
443
444 std::vector<llvm::Constant*> Fields;
445
446 if (!CFConstantStringClassRef) {
447 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
448 Ty = llvm::ArrayType::get(Ty, 0);
449
450 CFConstantStringClassRef =
451 new llvm::GlobalVariable(Ty, false,
452 llvm::GlobalVariable::ExternalLinkage, 0,
453 "__CFConstantStringClassReference",
454 &getModule());
455 }
456
457 // Class pointer.
458 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
459 llvm::Constant *Zeros[] = { Zero, Zero };
460 llvm::Constant *C =
461 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
462 Fields.push_back(C);
463
464 // Flags.
465 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
466 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
467
468 // String pointer.
469 C = llvm::ConstantArray::get(str);
470 C = new llvm::GlobalVariable(C->getType(), true,
471 llvm::GlobalValue::InternalLinkage,
472 C, ".str", &getModule());
473
474 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
475 Fields.push_back(C);
476
477 // String length.
478 Ty = getTypes().ConvertType(getContext().LongTy);
479 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
480
481 // The struct.
482 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
483 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000484 llvm::GlobalVariable *GV =
485 new llvm::GlobalVariable(C->getType(), true,
486 llvm::GlobalVariable::InternalLinkage,
487 C, "", &getModule());
488 GV->setSection("__DATA,__cfstring");
489 Entry.setValue(GV);
490 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000491}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000492
Chris Lattnera6dcce32008-02-11 00:02:17 +0000493/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000494static llvm::Constant *GenerateStringLiteral(const std::string &str,
495 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000496 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000497 // Create Constant for this string literal
498 llvm::Constant *C=llvm::ConstantArray::get(str);
499
500 // Create a global variable for this string
501 C = new llvm::GlobalVariable(C->getType(), constant,
502 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000503 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000504 return C;
505}
506
Chris Lattnera6dcce32008-02-11 00:02:17 +0000507/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
508/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000509llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
510 // Don't share any string literals if writable-strings is turned on.
511 if (Features.WritableStrings)
512 return GenerateStringLiteral(str, false, *this);
513
514 llvm::StringMapEntry<llvm::Constant *> &Entry =
515 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
516
517 if (Entry.getValue())
518 return Entry.getValue();
519
520 // Create a global variable for this.
521 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
522 Entry.setValue(C);
523 return C;
524}