blob: 3340cdff56a7004b6b4ef8b26f55dc890078052c [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
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000017#include "CGObjCRuntime.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000020#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000023#include "llvm/CallingConv.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"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000026#include "llvm/Target/TargetData.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000027#include "llvm/Analysis/Verifier.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29using namespace CodeGen;
30
31
Chris Lattnerdb6be562007-11-28 05:34:05 +000032CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000033 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000034 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000035 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000036 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Eli Friedman8f08a252008-05-26 12:59:39 +000037 CFConstantStringClassRef(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000038
39 if (Features.ObjC1) {
Daniel Dunbar1be1df32008-08-11 21:35:06 +000040 if (Features.NeXTRuntime) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000041 Runtime = CreateMacObjCRuntime(*this);
42 } else {
43 Runtime = CreateGNUObjCRuntime(*this);
44 }
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000045 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000046
47 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000048 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000049}
50
51CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000052 delete Runtime;
53 delete DebugInfo;
54}
55
56void CodeGenModule::Release() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000057 EmitStatics();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000058 if (Runtime)
59 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
60 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000061 EmitCtorList(GlobalCtors, "llvm.global_ctors");
62 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000063 EmitAnnotations();
Chris Lattnerb033c4a2008-04-30 16:05:42 +000064 // Run the verifier to check that the generated code is consistent.
65 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000066}
Chris Lattner4b009652007-07-25 00:24:17 +000067
Chris Lattnercf9c9d02007-12-02 07:19:18 +000068/// WarnUnsupported - Print out a warning that codegen doesn't support the
69/// specified stmt yet.
70void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
71 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
72 "cannot codegen this %0 yet");
73 SourceRange Range = S->getSourceRange();
74 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000075 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000076 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000077}
Chris Lattner0e4755d2007-12-02 06:27:33 +000078
Chris Lattner806a5f52008-01-12 07:05:38 +000079/// WarnUnsupported - Print out a warning that codegen doesn't support the
80/// specified decl yet.
81void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
82 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
83 "cannot codegen this %0 yet");
84 std::string Msg = Type;
85 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
86 &Msg, 1);
87}
88
Dan Gohman4751a3a2008-05-22 00:50:06 +000089/// setVisibility - Set the visibility for the given LLVM GlobalValue
90/// according to the given clang AST visibility value.
91void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
92 VisibilityAttr::VisibilityTypes Vis) {
93 switch (Vis) {
94 default: assert(0 && "Unknown visibility!");
95 case VisibilityAttr::DefaultVisibility:
96 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
97 break;
98 case VisibilityAttr::HiddenVisibility:
99 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
100 break;
101 case VisibilityAttr::ProtectedVisibility:
102 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
103 break;
104 }
105}
106
Chris Lattner753d2592008-03-14 17:18:18 +0000107/// AddGlobalCtor - Add a function to the list that will be called before
108/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000109void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000110 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000111 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000112}
113
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000114/// AddGlobalDtor - Add a function to the list that will be called
115/// when the module is unloaded.
116void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
117 // TODO: Type coercion of void()* types.
118 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
119}
120
121void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
122 // Ctor function type is void()*.
123 llvm::FunctionType* CtorFTy =
124 llvm::FunctionType::get(llvm::Type::VoidTy,
125 std::vector<const llvm::Type*>(),
126 false);
127 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
128
129 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000130 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000131 llvm::StructType::get(llvm::Type::Int32Ty,
132 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000133
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000134 // Construct the constructor and destructor arrays.
135 std::vector<llvm::Constant*> Ctors;
136 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
137 std::vector<llvm::Constant*> S;
138 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
139 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
140 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000141 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000142
143 if (!Ctors.empty()) {
144 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
145 new llvm::GlobalVariable(AT, false,
146 llvm::GlobalValue::AppendingLinkage,
147 llvm::ConstantArray::get(AT, Ctors),
148 GlobalName,
149 &TheModule);
150 }
Chris Lattner753d2592008-03-14 17:18:18 +0000151}
152
Nate Begeman52da5c72008-04-18 23:43:57 +0000153void CodeGenModule::EmitAnnotations() {
154 if (Annotations.empty())
155 return;
156
157 // Create a new global variable for the ConstantStruct in the Module.
158 llvm::Constant *Array =
159 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
160 Annotations.size()),
161 Annotations);
162 llvm::GlobalValue *gv =
163 new llvm::GlobalVariable(Array->getType(), false,
164 llvm::GlobalValue::AppendingLinkage, Array,
165 "llvm.global.annotations", &TheModule);
166 gv->setSection("llvm.metadata");
167}
168
Eli Friedman9be42212008-06-01 15:54:49 +0000169bool hasAggregateLLVMType(QualType T) {
170 return !T->isRealType() && !T->isPointerLikeType() &&
171 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
172}
173
Nuno Lopes78534382008-06-08 15:45:52 +0000174void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
175 llvm::GlobalValue *GV) {
176 // TODO: Set up linkage and many other things. Note, this is a simple
177 // approximation of what we really want.
178 if (FD->getStorageClass() == FunctionDecl::Static)
179 GV->setLinkage(llvm::Function::InternalLinkage);
180 else if (FD->getAttr<DLLImportAttr>())
181 GV->setLinkage(llvm::Function::DLLImportLinkage);
182 else if (FD->getAttr<DLLExportAttr>())
183 GV->setLinkage(llvm::Function::DLLExportLinkage);
184 else if (FD->getAttr<WeakAttr>() || FD->isInline())
185 GV->setLinkage(llvm::Function::WeakLinkage);
186
187 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
188 CodeGenModule::setVisibility(GV, attr->getVisibility());
189 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000190
191 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
192 // Prefaced with special LLVM marker to indicate that the name
193 // should not be munged.
194 GV->setName("\01" + ALA->getLabel());
195 }
Nuno Lopes78534382008-06-08 15:45:52 +0000196}
197
Eli Friedman9be42212008-06-01 15:54:49 +0000198void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
199 llvm::Function *F,
200 const llvm::FunctionType *FTy) {
201 unsigned FuncAttrs = 0;
202 if (FD->getAttr<NoThrowAttr>())
203 FuncAttrs |= llvm::ParamAttr::NoUnwind;
204 if (FD->getAttr<NoReturnAttr>())
205 FuncAttrs |= llvm::ParamAttr::NoReturn;
206
207 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
208 if (FuncAttrs)
209 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
210 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
211 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
212 if (AggregateReturn)
213 ParamAttrList.push_back(
214 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
215 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000216 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
217 if (FTP) {
218 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
219 QualType ParamType = FTP->getArgType(i);
220 unsigned ParamAttrs = 0;
221 if (ParamType->isRecordType())
222 ParamAttrs |= llvm::ParamAttr::ByVal;
Chris Lattner578279d2008-06-26 05:08:00 +0000223 if (ParamType->isSignedIntegerType() &&
224 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000225 ParamAttrs |= llvm::ParamAttr::SExt;
Chris Lattner578279d2008-06-26 05:08:00 +0000226 if (ParamType->isUnsignedIntegerType() &&
227 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000228 ParamAttrs |= llvm::ParamAttr::ZExt;
229 if (ParamAttrs)
230 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
231 ParamAttrs));
232 }
Eli Friedman9be42212008-06-01 15:54:49 +0000233 }
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000234
Eli Friedman9be42212008-06-01 15:54:49 +0000235 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
236 ParamAttrList.size()));
237
238 // Set the appropriate calling convention for the Function.
239 if (FD->getAttr<FastCallAttr>())
240 F->setCallingConv(llvm::CallingConv::Fast);
241
Nuno Lopes78534382008-06-08 15:45:52 +0000242 SetGlobalValueAttributes(FD, F);
Eli Friedman9be42212008-06-01 15:54:49 +0000243}
244
Chris Lattnerb326b172008-03-30 23:03:07 +0000245void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
246 // If this is not a prototype, emit the body.
247 if (OMD->getBody())
248 CodeGenFunction(*this).GenerateObjCMethod(OMD);
249}
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000250void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000251 Runtime->GenerateProtocol(PD);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000252}
253
254void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbarac93e472008-08-15 22:20:32 +0000255 Runtime->GenerateCategory(OCD);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000256}
257
Daniel Dunbarac93e472008-08-15 22:20:32 +0000258void
259CodeGenModule::EmitObjCClassImplementation(const ObjCImplementationDecl *OID) {
260 Runtime->GenerateClass(OID);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000261}
262
Nate Begemanad320b62008-04-20 06:29:50 +0000263void CodeGenModule::EmitStatics() {
264 // Emit code for each used static decl encountered. Since a previously unused
265 // static decl may become used during the generation of code for a static
266 // function, iterate until no changes are made.
267 bool Changed;
268 do {
269 Changed = false;
270 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000271 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000272
273 // Check if we have used a decl with the same name
274 // FIXME: The AST should have some sort of aggregate decls or
275 // global symbol map.
Daniel Dunbarced89142008-08-06 00:03:29 +0000276 if (!GlobalDeclMap.count(D->getName()))
277 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000278
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000279 // Emit the definition.
280 EmitGlobalDefinition(D);
281
Nate Begemanad320b62008-04-20 06:29:50 +0000282 // Erase the used decl from the list.
283 StaticDecls[i] = StaticDecls.back();
284 StaticDecls.pop_back();
285 --i;
286 --e;
287
288 // Remember that we made a change.
289 Changed = true;
290 }
291 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000292}
293
Nate Begeman8a704172008-04-19 04:17:09 +0000294/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
295/// annotation information for a given GlobalValue. The annotation struct is
296/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000297/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000298/// created from the AnnotateAttr's annotation. The third field is a constant
299/// string containing the name of the translation unit. The fourth field is
300/// the line number in the file of the annotated value declaration.
301///
302/// FIXME: this does not unique the annotation string constants, as llvm-gcc
303/// appears to.
304///
305llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
306 const AnnotateAttr *AA,
307 unsigned LineNo) {
308 llvm::Module *M = &getModule();
309
310 // get [N x i8] constants for the annotation string, and the filename string
311 // which are the 2nd and 3rd elements of the global annotation structure.
312 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
313 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
314 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
315 true);
316
317 // Get the two global values corresponding to the ConstantArrays we just
318 // created to hold the bytes of the strings.
319 llvm::GlobalValue *annoGV =
320 new llvm::GlobalVariable(anno->getType(), false,
321 llvm::GlobalValue::InternalLinkage, anno,
322 GV->getName() + ".str", M);
323 // translation unit name string, emitted into the llvm.metadata section.
324 llvm::GlobalValue *unitGV =
325 new llvm::GlobalVariable(unit->getType(), false,
326 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
327
328 // Create the ConstantStruct that is the global annotion.
329 llvm::Constant *Fields[4] = {
330 llvm::ConstantExpr::getBitCast(GV, SBP),
331 llvm::ConstantExpr::getBitCast(annoGV, SBP),
332 llvm::ConstantExpr::getBitCast(unitGV, SBP),
333 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
334 };
335 return llvm::ConstantStruct::get(Fields, 4, false);
336}
337
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000338void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
339 bool isDef, isStatic;
340
341 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
342 isDef = (FD->isThisDeclarationADefinition() ||
343 FD->getAttr<AliasAttr>());
344 isStatic = FD->getStorageClass() == FunctionDecl::Static;
345 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
346 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
347
348 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
349 isStatic = VD->getStorageClass() == VarDecl::Static;
350 } else {
351 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000352 return;
353 }
354
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000355 // Forward declarations are emitted lazily on first use.
356 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000357 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000358
359 // If the global is a static, defer code generation until later so
360 // we can easily omit unused statics.
361 if (isStatic) {
362 StaticDecls.push_back(Global);
363 return;
364 }
365
366 // Otherwise emit the definition.
367 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000368}
369
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000370void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
371 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
372 EmitGlobalFunctionDefinition(FD);
373 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
374 EmitGlobalVarDefinition(VD);
375 } else {
376 assert(0 && "Invalid argument to EmitGlobalDefinition()");
377 }
378}
379
Daniel Dunbar2188c532008-07-30 16:32:24 +0000380 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000381 assert(D->hasGlobalStorage() && "Not a global variable");
382
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000383 QualType ASTTy = D->getType();
384 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000385 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000386
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000387 // Lookup the entry, lazily creating it if necessary.
388 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
389 if (!Entry)
390 Entry = new llvm::GlobalVariable(Ty, false,
391 llvm::GlobalValue::ExternalLinkage,
392 0, D->getName(), &getModule(), 0,
393 ASTTy.getAddressSpace());
394
Daniel Dunbar2188c532008-07-30 16:32:24 +0000395 // Make sure the result is of the correct type.
396 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000397}
398
399void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000400 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000401 QualType ASTTy = D->getType();
402 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000403
Chris Lattner4b009652007-07-25 00:24:17 +0000404 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000405 // This is a tentative definition; tentative definitions are
406 // implicitly initialized with { 0 }
407 const llvm::Type* InitTy;
408 if (ASTTy->isIncompleteArrayType()) {
409 // An incomplete array is normally [ TYPE x 0 ], but we need
410 // to fix it to [ TYPE x 1 ].
411 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
412 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
413 } else {
414 InitTy = VarTy;
415 }
416 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000417 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000418 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000419 }
420 const llvm::Type* InitType = Init->getType();
421
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000422 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
423 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
424
Eli Friedman43a0ce82008-05-30 19:50:47 +0000425 if (!GV) {
426 GV = new llvm::GlobalVariable(InitType, false,
427 llvm::GlobalValue::ExternalLinkage,
428 0, D->getName(), &getModule(), 0,
429 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000430 } else if (GV->getType() !=
431 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000432 // We have a definition after a prototype with the wrong type.
433 // We must make a new GlobalVariable* and update everything that used OldGV
434 // (a declaration or tentative definition) with the new GlobalVariable*
435 // (which will be a definition).
436 //
437 // This happens if there is a prototype for a global (e.g. "extern int x[];")
438 // and then a definition of a different type (e.g. "int x[10];"). This also
439 // happens when an initializer has a different type from the type of the
440 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000441 //
442 // FIXME: This also ends up happening if there's a definition followed by
443 // a tentative definition! (Although Sema rejects that construct
444 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000445
446 // Save the old global
447 llvm::GlobalVariable *OldGV = GV;
448
449 // Make a new global with the correct type
450 GV = new llvm::GlobalVariable(InitType, false,
451 llvm::GlobalValue::ExternalLinkage,
452 0, D->getName(), &getModule(), 0,
453 ASTTy.getAddressSpace());
454 // Steal the name of the old global
455 GV->takeName(OldGV);
456
457 // Replace all uses of the old global with the new global
458 llvm::Constant *NewPtrForOldDecl =
459 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
460 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000461
462 // Erase the old global, since it is no longer used.
463 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000464 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000465
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000466 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000467
Nate Begeman8a704172008-04-19 04:17:09 +0000468 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
469 SourceManager &SM = Context.getSourceManager();
470 AddAnnotation(EmitAnnotateAttr(GV, AA,
471 SM.getLogicalLineNumber(D->getLocation())));
472 }
473
Chris Lattner4b009652007-07-25 00:24:17 +0000474 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000475
Eli Friedman7008e9a2008-05-30 20:39:54 +0000476 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
477 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000478 if (const IncompleteArrayType* IAT =
479 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000480 Align = Context.getTypeAlign(IAT->getElementType());
481 else
482 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000483 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
484 Align = std::max(Align, AA->getAlignment());
485 }
486 GV->setAlignment(Align / 8);
487
Chris Lattner402b3372008-03-03 03:28:21 +0000488 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000489 setVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000490 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000491
492 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
493 // Prefaced with special LLVM marker to indicate that the name
494 // should not be munged.
495 GV->setName("\01" + ALA->getLabel());
496 }
Chris Lattner4b009652007-07-25 00:24:17 +0000497
498 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000499 if (D->getStorageClass() == VarDecl::Static)
500 GV->setLinkage(llvm::Function::InternalLinkage);
501 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000502 GV->setLinkage(llvm::Function::DLLImportLinkage);
503 else if (D->getAttr<DLLExportAttr>())
504 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000505 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000506 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000507 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000508 // FIXME: This isn't right. This should handle common linkage and other
509 // stuff.
510 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000511 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000512 case VarDecl::Auto:
513 case VarDecl::Register:
514 assert(0 && "Can't have auto or register globals");
515 case VarDecl::None:
516 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000517 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000518 break;
519 case VarDecl::Extern:
520 case VarDecl::PrivateExtern:
521 // todo: common
522 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000523 }
Chris Lattner4b009652007-07-25 00:24:17 +0000524 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000525
526 // Emit global variable debug information.
527 CGDebugInfo *DI = getDebugInfo();
528 if(DI) {
529 if(D->getLocation().isValid())
530 DI->setLocation(D->getLocation());
531 DI->EmitGlobalVariable(GV, D);
532 }
Chris Lattner4b009652007-07-25 00:24:17 +0000533}
534
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000535llvm::GlobalValue *
536CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
537 // FIXME: param attributes for sext/zext etc.
538 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
539 assert(!D->getBody() && "Unexpected alias attr on function with body.");
540
541 const std::string& aliaseeName = AA->getAliasee();
542 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
543 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
544 llvm::Function::ExternalLinkage,
545 D->getName(),
546 aliasee,
547 &getModule());
548 SetGlobalValueAttributes(D, alias);
549 return alias;
550 } else {
551 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
552 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
553 llvm::Function *F = llvm::Function::Create(FTy,
554 llvm::Function::ExternalLinkage,
555 D->getName(), &getModule());
556
557 SetFunctionAttributes(D, F, FTy);
558 return F;
559 }
560}
561
562llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000563 QualType ASTTy = D->getType();
564 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
565 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000566
567 // Lookup the entry, lazily creating it if necessary.
568 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
569 if (!Entry)
570 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000571
Daniel Dunbar2188c532008-07-30 16:32:24 +0000572 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000573}
574
575void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000576 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
577 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000578 Entry = EmitForwardFunctionDefinition(D);
579 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000580 // If the types mismatch then we have to rewrite the definition.
581 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
582 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000583 // Otherwise, we have a definition after a prototype with the wrong type.
584 // F is the Function* for the one with the wrong type, we must make a new
585 // Function* and update everything that used F (a declaration) with the new
586 // Function* (which will be a definition).
587 //
588 // This happens if there is a prototype for a function (e.g. "int f()") and
589 // then a definition of a different type (e.g. "int f(int x)"). Start by
590 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000591 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
592 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000593
594 // Replace uses of F with the Function we will endow with a body.
595 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000596 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
597 Entry->replaceAllUsesWith(NewPtrForOldDecl);
598
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000599 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000600 // FIXME: Add GlobalValue->eraseFromParent().
601 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
602 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
603 F->eraseFromParent();
604 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
605 GA->eraseFromParent();
606 } else {
607 assert(0 && "Invalid global variable type.");
608 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000609
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000610 Entry = NewFn;
611 }
612 }
613
614 if (D->getAttr<AliasAttr>()) {
615 ;
616 } else {
617 llvm::Function *Fn = cast<llvm::Function>(Entry);
618 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000619
Daniel Dunbar91692d92008-08-11 17:36:14 +0000620 // Set attributes specific to definition.
621 // FIXME: This needs to be cleaned up by clearly emitting the
622 // declaration / definition at separate times.
623 if (!Features.Exceptions)
624 Fn->addParamAttr(0, llvm::ParamAttr::NoUnwind);
625
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000626 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
627 AddGlobalCtor(Fn, CA->getPriority());
628 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
629 AddGlobalDtor(Fn, DA->getPriority());
630 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000631 }
632}
633
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000634void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
635 // Make sure that this type is translated.
636 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000637}
638
639
Chris Lattnerab862cc2007-08-31 04:31:45 +0000640/// getBuiltinLibFunction
641llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000642 if (BuiltinID > BuiltinFunctions.size())
643 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000644
Chris Lattner9f2d6892007-12-13 00:38:03 +0000645 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
646 // a slot for it.
647 assert(BuiltinID && "Invalid Builtin ID");
648 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000649 if (FunctionSlot)
650 return FunctionSlot;
651
652 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
653
654 // Get the name, skip over the __builtin_ prefix.
655 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
656
657 // Get the type for the builtin.
658 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
659 const llvm::FunctionType *Ty =
660 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
661
662 // FIXME: This has a serious problem with code like this:
663 // void abs() {}
664 // ... __builtin_abs(x);
665 // The two versions of abs will collide. The fix is for the builtin to win,
666 // and for the existing one to be turned into a constantexpr cast of the
667 // builtin. In the case where the existing one is a static function, it
668 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000669 if (llvm::Function *Existing = getModule().getFunction(Name)) {
670 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
671 return FunctionSlot = Existing;
672 assert(Existing == 0 && "FIXME: Name collision");
673 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000674
675 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000676 return FunctionSlot =
677 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
678 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000679}
680
Chris Lattner4b23f942007-12-18 00:25:38 +0000681llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
682 unsigned NumTys) {
683 return llvm::Intrinsic::getDeclaration(&getModule(),
684 (llvm::Intrinsic::ID)IID, Tys, NumTys);
685}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000686
Chris Lattner4b009652007-07-25 00:24:17 +0000687llvm::Function *CodeGenModule::getMemCpyFn() {
688 if (MemCpyFn) return MemCpyFn;
689 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000690 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000691 default: assert(0 && "Unknown ptr width");
692 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
693 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
694 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000695 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000696}
Anders Carlsson36a04872007-08-21 00:21:21 +0000697
Eli Friedman8f08a252008-05-26 12:59:39 +0000698llvm::Function *CodeGenModule::getMemMoveFn() {
699 if (MemMoveFn) return MemMoveFn;
700 llvm::Intrinsic::ID IID;
701 switch (Context.Target.getPointerWidth(0)) {
702 default: assert(0 && "Unknown ptr width");
703 case 32: IID = llvm::Intrinsic::memmove_i32; break;
704 case 64: IID = llvm::Intrinsic::memmove_i64; break;
705 }
706 return MemMoveFn = getIntrinsic(IID);
707}
708
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000709llvm::Function *CodeGenModule::getMemSetFn() {
710 if (MemSetFn) return MemSetFn;
711 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000712 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000713 default: assert(0 && "Unknown ptr width");
714 case 32: IID = llvm::Intrinsic::memset_i32; break;
715 case 64: IID = llvm::Intrinsic::memset_i64; break;
716 }
717 return MemSetFn = getIntrinsic(IID);
718}
Chris Lattner4b23f942007-12-18 00:25:38 +0000719
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000720// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerab862cc2007-08-31 04:31:45 +0000721llvm::Constant *CodeGenModule::
722GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000723 llvm::StringMapEntry<llvm::Constant *> &Entry =
724 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
725
726 if (Entry.getValue())
727 return Entry.getValue();
728
729 std::vector<llvm::Constant*> Fields;
730
731 if (!CFConstantStringClassRef) {
732 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
733 Ty = llvm::ArrayType::get(Ty, 0);
734
735 CFConstantStringClassRef =
736 new llvm::GlobalVariable(Ty, false,
737 llvm::GlobalVariable::ExternalLinkage, 0,
738 "__CFConstantStringClassReference",
739 &getModule());
740 }
741
742 // Class pointer.
743 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
744 llvm::Constant *Zeros[] = { Zero, Zero };
745 llvm::Constant *C =
746 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
747 Fields.push_back(C);
748
749 // Flags.
750 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
751 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
752
753 // String pointer.
754 C = llvm::ConstantArray::get(str);
755 C = new llvm::GlobalVariable(C->getType(), true,
756 llvm::GlobalValue::InternalLinkage,
757 C, ".str", &getModule());
758
759 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
760 Fields.push_back(C);
761
762 // String length.
763 Ty = getTypes().ConvertType(getContext().LongTy);
764 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
765
766 // The struct.
767 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
768 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000769 llvm::GlobalVariable *GV =
770 new llvm::GlobalVariable(C->getType(), true,
771 llvm::GlobalVariable::InternalLinkage,
772 C, "", &getModule());
773 GV->setSection("__DATA,__cfstring");
774 Entry.setValue(GV);
775 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000776}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000777
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000778/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000779/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000780std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000781 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
782 const char *StrData = E->getStrData();
783 unsigned Len = E->getByteLength();
784
785 const ConstantArrayType *CAT =
786 getContext().getAsConstantArrayType(E->getType());
787 assert(CAT && "String isn't pointer or array!");
788
789 // Resize the string to the right size
790 // FIXME: What about wchar_t strings?
791 std::string Str(StrData, StrData+Len);
792 uint64_t RealLen = CAT->getSize().getZExtValue();
793 Str.resize(RealLen, '\0');
794
795 return Str;
796}
797
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000798/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
799/// constant array for the given string literal.
800llvm::Constant *
801CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
802 // FIXME: This can be more efficient.
803 return GetAddrOfConstantString(GetStringForStringLiteral(S));
804}
805
Chris Lattnera6dcce32008-02-11 00:02:17 +0000806/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000807static llvm::Constant *GenerateStringLiteral(const std::string &str,
808 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000809 CodeGenModule &CGM) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000810 // Create Constant for this string literal. Don't add a '\0'.
811 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000812
813 // Create a global variable for this string
814 C = new llvm::GlobalVariable(C->getType(), constant,
815 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000816 C, ".str", &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000817
Chris Lattnerdb6be562007-11-28 05:34:05 +0000818 return C;
819}
820
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000821/// GetAddrOfConstantString - Returns a pointer to a character array
822/// containing the literal. This contents are exactly that of the
823/// given string, i.e. it will not be null terminated automatically;
824/// see GetAddrOfConstantCString. Note that whether the result is
825/// actually a pointer to an LLVM constant depends on
826/// Feature.WriteableStrings.
827///
828/// The result has pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000829llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
830 // Don't share any string literals if writable-strings is turned on.
831 if (Features.WritableStrings)
832 return GenerateStringLiteral(str, false, *this);
833
834 llvm::StringMapEntry<llvm::Constant *> &Entry =
835 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
836
837 if (Entry.getValue())
838 return Entry.getValue();
839
840 // Create a global variable for this.
841 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
842 Entry.setValue(C);
843 return C;
844}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000845
846/// GetAddrOfConstantCString - Returns a pointer to a character
847/// array containing the literal and a terminating '\-'
848/// character. The result has pointer to array type.
849llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str) {
Daniel Dunbarb4278222008-08-15 18:29:12 +0000850 return GetAddrOfConstantString(str + "\0");
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000851}