blob: 43f399a61f29b990f3c5d89e5be0304409fb7ace [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
37 Runtime = CreateObjCRuntime(M);
38}
39
40CodeGenModule::~CodeGenModule() {
Chris Lattner753d2592008-03-14 17:18:18 +000041 EmitGlobalCtors();
Chris Lattnercbfb5512008-03-01 08:45:05 +000042 delete Runtime;
43}
Chris Lattner4b009652007-07-25 00:24:17 +000044
Chris Lattnercf9c9d02007-12-02 07:19:18 +000045/// WarnUnsupported - Print out a warning that codegen doesn't support the
46/// specified stmt yet.
47void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
48 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
49 "cannot codegen this %0 yet");
50 SourceRange Range = S->getSourceRange();
51 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000052 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000053 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000054}
Chris Lattner0e4755d2007-12-02 06:27:33 +000055
Chris Lattner806a5f52008-01-12 07:05:38 +000056/// WarnUnsupported - Print out a warning that codegen doesn't support the
57/// specified decl yet.
58void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
59 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
60 "cannot codegen this %0 yet");
61 std::string Msg = Type;
62 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
63 &Msg, 1);
64}
65
Chris Lattner753d2592008-03-14 17:18:18 +000066/// AddGlobalCtor - Add a function to the list that will be called before
67/// main() runs.
68void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
69 // TODO: Type coercion of void()* types.
70 GlobalCtors.push_back(Ctor);
71}
72
73void CodeGenModule::EmitGlobalCtors() {
74 // Get the type of @llvm.global_ctors
75 std::vector<const llvm::Type*> CtorFields;
76 CtorFields.push_back(llvm::IntegerType::get(32));
77 // Constructor function type
78 std::vector<const llvm::Type*> VoidArgs;
79 llvm::FunctionType* CtorFuncTy = llvm::FunctionType::get(
80 llvm::Type::VoidTy,
81 VoidArgs,
82 false);
83 // i32, function type pair
84 CtorFields.push_back(llvm::PointerType::getUnqual(CtorFuncTy));
85 llvm::StructType* CtorStructTy = llvm::StructType::get(CtorFields, false);
86 // Array of fields
87 llvm::ArrayType* GlobalCtorsTy = llvm::ArrayType::get(CtorStructTy,
88 GlobalCtors.size());
89
90 const std::string GlobalCtorsVar = std::string("llvm.global_ctors");
91 // Define the global variable
92 llvm::GlobalVariable *GlobalCtorsVal = new llvm::GlobalVariable(
93 GlobalCtorsTy,
94 false,
95 llvm::GlobalValue::AppendingLinkage,
96 (llvm::Constant*)0,
97 GlobalCtorsVar,
98 &TheModule);
99
100 // Populate the array
101 std::vector<llvm::Constant*> CtorValues;
102 llvm::Constant *MagicNumber = llvm::ConstantInt::get(llvm::IntegerType::Int32Ty,
103 65535,
104 false);
105 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
106 E = GlobalCtors.end(); I != E; ++I) {
107 std::vector<llvm::Constant*> StructValues;
108 StructValues.push_back(MagicNumber);
109 StructValues.push_back(*I);
110
111 llvm::Constant* CtorEntry = llvm::ConstantStruct::get(CtorStructTy, StructValues);
112 CtorValues.push_back(CtorEntry);
113 }
114 llvm::Constant* CtorArray = llvm::ConstantArray::get(GlobalCtorsTy, CtorValues);
115 GlobalCtorsVal->setInitializer(CtorArray);
116
117}
118
Chris Lattner0e4755d2007-12-02 06:27:33 +0000119/// ReplaceMapValuesWith - This is a really slow and bad function that
120/// searches for any entries in GlobalDeclMap that point to OldVal, changing
121/// them to point to NewVal. This is badbadbad, FIXME!
122void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
123 llvm::Constant *NewVal) {
124 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
125 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
126 if (I->second == OldVal) I->second = NewVal;
127}
128
129
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000130llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
131 bool isDefinition) {
132 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +0000133 llvm::Constant *&Entry = GlobalDeclMap[D];
134 if (Entry) return Entry;
135
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000136 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
137
138 // Check to see if the function already exists.
139 llvm::Function *F = getModule().getFunction(D->getName());
140 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
141
142 // If it doesn't already exist, just create and return an entry.
143 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000144 // FIXME: param attributes for sext/zext etc.
Nate Begemandc6262e2008-03-09 03:09:36 +0000145 F = new llvm::Function(FTy, llvm::Function::ExternalLinkage, D->getName(),
146 &getModule());
147
148 // Set the appropriate calling convention for the Function.
149 if (D->getAttr<FastCallAttr>())
150 F->setCallingConv(llvm::CallingConv::Fast);
151 return Entry = F;
Chris Lattner4b009652007-07-25 00:24:17 +0000152 }
153
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000154 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000155 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000156 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +0000157
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000158 // If this isn't a definition, just return it casted to the right type.
159 if (!isDefinition)
160 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
161
162 // Otherwise, we have a definition after a prototype with the wrong type.
163 // F is the Function* for the one with the wrong type, we must make a new
164 // Function* and update everything that used F (a declaration) with the new
165 // Function* (which will be a definition).
166 //
167 // This happens if there is a prototype for a function (e.g. "int f()") and
168 // then a definition of a different type (e.g. "int f(int x)"). Start by
169 // making a new function of the correct type, RAUW, then steal the name.
170 llvm::Function *NewFn = new llvm::Function(FTy,
171 llvm::Function::ExternalLinkage,
172 "", &getModule());
173 NewFn->takeName(F);
174
175 // Replace uses of F with the Function we will endow with a body.
176 llvm::Constant *NewPtrForOldDecl =
177 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
178 F->replaceAllUsesWith(NewPtrForOldDecl);
179
180 // FIXME: Update the globaldeclmap for the previous decl of this name. We
181 // really want a way to walk all of these, but we don't have it yet. This
182 // is incredibly slow!
183 ReplaceMapValuesWith(F, NewPtrForOldDecl);
184
185 // Ok, delete the old function now, which is dead.
186 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
187 F->eraseFromParent();
188
189 // Return the new function which has the right type.
190 return Entry = NewFn;
191}
192
Chris Lattner0db06992008-02-05 06:37:34 +0000193static bool IsZeroElementArray(const llvm::Type *Ty) {
194 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
195 return ATy->getNumElements() == 0;
196 return false;
197}
198
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000199llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
200 bool isDefinition) {
201 assert(D->hasGlobalStorage() && "Not a global variable");
202
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000203 // See if it is already in the map.
204 llvm::Constant *&Entry = GlobalDeclMap[D];
205 if (Entry) return Entry;
206
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000207 QualType ASTTy = D->getType();
208 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000209
210 // Check to see if the global already exists.
Chris Lattnered430e92008-02-02 04:43:11 +0000211 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000212
213 // If it doesn't already exist, just create and return an entry.
214 if (GV == 0) {
215 return Entry = new llvm::GlobalVariable(Ty, false,
216 llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000217 0, D->getName(), &getModule(), 0,
218 ASTTy.getAddressSpace());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000219 }
220
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000221 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000222 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000223 if (PTy == GV->getType()) return Entry = GV;
224
225 // If this isn't a definition, just return it casted to the right type.
226 if (!isDefinition)
227 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
228
229
230 // Otherwise, we have a definition after a prototype with the wrong type.
231 // GV is the GlobalVariable* for the one with the wrong type, we must make a
232 /// new GlobalVariable* and update everything that used GV (a declaration)
233 // with the new GlobalVariable* (which will be a definition).
234 //
235 // This happens if there is a prototype for a global (e.g. "extern int x[];")
236 // and then a definition of a different type (e.g. "int x[10];"). Start by
237 // making a new global of the correct type, RAUW, then steal the name.
238 llvm::GlobalVariable *NewGV =
239 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000240 0, D->getName(), &getModule(), 0,
241 ASTTy.getAddressSpace());
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000242 NewGV->takeName(GV);
243
244 // Replace uses of GV with the globalvalue we will endow with a body.
245 llvm::Constant *NewPtrForOldDecl =
246 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
247 GV->replaceAllUsesWith(NewPtrForOldDecl);
248
249 // FIXME: Update the globaldeclmap for the previous decl of this name. We
250 // really want a way to walk all of these, but we don't have it yet. This
251 // is incredibly slow!
252 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
253
Chris Lattner0db06992008-02-05 06:37:34 +0000254 // Verify that GV was a declaration or something like x[] which turns into
255 // [0 x type].
256 assert((GV->isDeclaration() ||
257 IsZeroElementArray(GV->getType()->getElementType())) &&
258 "Shouldn't replace non-declaration");
259
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000260 // Ok, delete the old global now, which is dead.
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000261 GV->eraseFromParent();
262
263 // Return the new global which has the right type.
264 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000265}
266
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000267
Chris Lattner4b009652007-07-25 00:24:17 +0000268void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
269 // If this is not a prototype, emit the body.
270 if (FD->getBody())
271 CodeGenFunction(*this).GenerateCode(FD);
272}
273
Anders Carlssond76cead2008-01-26 01:36:00 +0000274llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
275 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000276}
277
Chris Lattner4b009652007-07-25 00:24:17 +0000278void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000279 // If this is just a forward declaration of the variable, don't emit it now,
280 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000281 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
282 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000283
284 // Get the global, forcing it to be a direct reference.
285 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000286 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000287
288 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000289 llvm::Constant *Init = 0;
290 if (D->getInit() == 0) {
291 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
292 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000293 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner8cd0e932008-03-05 18:54:05 +0000294 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner4b009652007-07-25 00:24:17 +0000295 if (D->getInit()->isIntegerConstantExpr(Value, Context))
296 Init = llvm::ConstantInt::get(Value);
297 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000298
Devang Patel08a10cc2007-10-30 21:27:20 +0000299 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000300 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000301
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000302 assert(GV->getType()->getElementType() == Init->getType() &&
303 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000304 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000305
306 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
307 GV->setVisibility(attr->getVisibility());
308 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000309
310 // Set the llvm linkage type as appropriate.
Chris Lattner402b3372008-03-03 03:28:21 +0000311 if (D->getAttr<DLLImportAttr>())
312 GV->setLinkage(llvm::Function::DLLImportLinkage);
313 else if (D->getAttr<DLLExportAttr>())
314 GV->setLinkage(llvm::Function::DLLExportLinkage);
315 else if (D->getAttr<WeakAttr>()) {
316 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
317
318 } else {
319 // FIXME: This isn't right. This should handle common linkage and other
320 // stuff.
321 switch (D->getStorageClass()) {
322 case VarDecl::Auto:
323 case VarDecl::Register:
324 assert(0 && "Can't have auto or register globals");
325 case VarDecl::None:
326 if (!D->getInit())
327 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
328 break;
329 case VarDecl::Extern:
330 case VarDecl::PrivateExtern:
331 // todo: common
332 break;
333 case VarDecl::Static:
334 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
335 break;
336 }
Chris Lattner4b009652007-07-25 00:24:17 +0000337 }
338}
339
340/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
341/// declarator chain.
342void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
343 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
344 EmitGlobalVar(D);
345}
346
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000347void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
348 // Make sure that this type is translated.
349 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000350}
351
352
Chris Lattnerab862cc2007-08-31 04:31:45 +0000353/// getBuiltinLibFunction
354llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000355 if (BuiltinID > BuiltinFunctions.size())
356 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000357
Chris Lattner9f2d6892007-12-13 00:38:03 +0000358 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
359 // a slot for it.
360 assert(BuiltinID && "Invalid Builtin ID");
361 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000362 if (FunctionSlot)
363 return FunctionSlot;
364
365 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
366
367 // Get the name, skip over the __builtin_ prefix.
368 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
369
370 // Get the type for the builtin.
371 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
372 const llvm::FunctionType *Ty =
373 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
374
375 // FIXME: This has a serious problem with code like this:
376 // void abs() {}
377 // ... __builtin_abs(x);
378 // The two versions of abs will collide. The fix is for the builtin to win,
379 // and for the existing one to be turned into a constantexpr cast of the
380 // builtin. In the case where the existing one is a static function, it
381 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000382 if (llvm::Function *Existing = getModule().getFunction(Name)) {
383 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
384 return FunctionSlot = Existing;
385 assert(Existing == 0 && "FIXME: Name collision");
386 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000387
388 // FIXME: param attributes for sext/zext etc.
389 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
390 Name, &getModule());
391}
392
Chris Lattner4b23f942007-12-18 00:25:38 +0000393llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
394 unsigned NumTys) {
395 return llvm::Intrinsic::getDeclaration(&getModule(),
396 (llvm::Intrinsic::ID)IID, Tys, NumTys);
397}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000398
Chris Lattner4b009652007-07-25 00:24:17 +0000399llvm::Function *CodeGenModule::getMemCpyFn() {
400 if (MemCpyFn) return MemCpyFn;
401 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000402 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000403 default: assert(0 && "Unknown ptr width");
404 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
405 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
406 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000407 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000408}
Anders Carlsson36a04872007-08-21 00:21:21 +0000409
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000410llvm::Function *CodeGenModule::getMemSetFn() {
411 if (MemSetFn) return MemSetFn;
412 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000413 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000414 default: assert(0 && "Unknown ptr width");
415 case 32: IID = llvm::Intrinsic::memset_i32; break;
416 case 64: IID = llvm::Intrinsic::memset_i64; break;
417 }
418 return MemSetFn = getIntrinsic(IID);
419}
Chris Lattner4b23f942007-12-18 00:25:38 +0000420
Chris Lattnerab862cc2007-08-31 04:31:45 +0000421llvm::Constant *CodeGenModule::
422GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000423 llvm::StringMapEntry<llvm::Constant *> &Entry =
424 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
425
426 if (Entry.getValue())
427 return Entry.getValue();
428
429 std::vector<llvm::Constant*> Fields;
430
431 if (!CFConstantStringClassRef) {
432 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
433 Ty = llvm::ArrayType::get(Ty, 0);
434
435 CFConstantStringClassRef =
436 new llvm::GlobalVariable(Ty, false,
437 llvm::GlobalVariable::ExternalLinkage, 0,
438 "__CFConstantStringClassReference",
439 &getModule());
440 }
441
442 // Class pointer.
443 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
444 llvm::Constant *Zeros[] = { Zero, Zero };
445 llvm::Constant *C =
446 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
447 Fields.push_back(C);
448
449 // Flags.
450 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
451 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
452
453 // String pointer.
454 C = llvm::ConstantArray::get(str);
455 C = new llvm::GlobalVariable(C->getType(), true,
456 llvm::GlobalValue::InternalLinkage,
457 C, ".str", &getModule());
458
459 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
460 Fields.push_back(C);
461
462 // String length.
463 Ty = getTypes().ConvertType(getContext().LongTy);
464 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
465
466 // The struct.
467 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
468 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000469 llvm::GlobalVariable *GV =
470 new llvm::GlobalVariable(C->getType(), true,
471 llvm::GlobalVariable::InternalLinkage,
472 C, "", &getModule());
473 GV->setSection("__DATA,__cfstring");
474 Entry.setValue(GV);
475 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000476}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000477
Chris Lattnera6dcce32008-02-11 00:02:17 +0000478/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000479static llvm::Constant *GenerateStringLiteral(const std::string &str,
480 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000481 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000482 // Create Constant for this string literal
483 llvm::Constant *C=llvm::ConstantArray::get(str);
484
485 // Create a global variable for this string
486 C = new llvm::GlobalVariable(C->getType(), constant,
487 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000488 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000489 return C;
490}
491
Chris Lattnera6dcce32008-02-11 00:02:17 +0000492/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
493/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000494llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
495 // Don't share any string literals if writable-strings is turned on.
496 if (Features.WritableStrings)
497 return GenerateStringLiteral(str, false, *this);
498
499 llvm::StringMapEntry<llvm::Constant *> &Entry =
500 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
501
502 if (Entry.getValue())
503 return Entry.getValue();
504
505 // Create a global variable for this.
506 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
507 Entry.setValue(C);
508 return C;
509}