blob: c5e6a26859e135d8ad4893a0650b70f667e421df [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"
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"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000023#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/Intrinsics.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000025#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27using namespace CodeGen;
28
29
Chris Lattnerdb6be562007-11-28 05:34:05 +000030CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000031 llvm::Module &M, const llvm::TargetData &TD,
32 Diagnostic &diags)
33 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Devang Patela8fccb82007-10-31 20:01:01 +000034 Types(C, M, TD), MemCpyFn(0), CFConstantStringClassRef(0) {}
Chris Lattner4b009652007-07-25 00:24:17 +000035
Chris Lattnercf9c9d02007-12-02 07:19:18 +000036/// WarnUnsupported - Print out a warning that codegen doesn't support the
37/// specified stmt yet.
38void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
39 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
40 "cannot codegen this %0 yet");
41 SourceRange Range = S->getSourceRange();
42 std::string Msg = Type;
43 getDiags().Report(S->getLocStart(), DiagID, &Msg, 1, &Range, 1);
44}
Chris Lattner0e4755d2007-12-02 06:27:33 +000045
46/// ReplaceMapValuesWith - This is a really slow and bad function that
47/// searches for any entries in GlobalDeclMap that point to OldVal, changing
48/// them to point to NewVal. This is badbadbad, FIXME!
49void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
50 llvm::Constant *NewVal) {
51 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
52 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
53 if (I->second == OldVal) I->second = NewVal;
54}
55
56
Chris Lattner1a3c1e22007-12-02 07:09:19 +000057llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
58 bool isDefinition) {
59 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +000060 llvm::Constant *&Entry = GlobalDeclMap[D];
61 if (Entry) return Entry;
62
Chris Lattner1a3c1e22007-12-02 07:09:19 +000063 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
64
65 // Check to see if the function already exists.
66 llvm::Function *F = getModule().getFunction(D->getName());
67 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
68
69 // If it doesn't already exist, just create and return an entry.
70 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +000071 // FIXME: param attributes for sext/zext etc.
72 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
73 D->getName(), &getModule());
74 }
75
Chris Lattner1a3c1e22007-12-02 07:09:19 +000076 // If the pointer type matches, just return it.
77 llvm::Type *PFTy = llvm::PointerType::get(Ty);
78 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +000079
Chris Lattner1a3c1e22007-12-02 07:09:19 +000080 // If this isn't a definition, just return it casted to the right type.
81 if (!isDefinition)
82 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
83
84 // Otherwise, we have a definition after a prototype with the wrong type.
85 // F is the Function* for the one with the wrong type, we must make a new
86 // Function* and update everything that used F (a declaration) with the new
87 // Function* (which will be a definition).
88 //
89 // This happens if there is a prototype for a function (e.g. "int f()") and
90 // then a definition of a different type (e.g. "int f(int x)"). Start by
91 // making a new function of the correct type, RAUW, then steal the name.
92 llvm::Function *NewFn = new llvm::Function(FTy,
93 llvm::Function::ExternalLinkage,
94 "", &getModule());
95 NewFn->takeName(F);
96
97 // Replace uses of F with the Function we will endow with a body.
98 llvm::Constant *NewPtrForOldDecl =
99 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
100 F->replaceAllUsesWith(NewPtrForOldDecl);
101
102 // FIXME: Update the globaldeclmap for the previous decl of this name. We
103 // really want a way to walk all of these, but we don't have it yet. This
104 // is incredibly slow!
105 ReplaceMapValuesWith(F, NewPtrForOldDecl);
106
107 // Ok, delete the old function now, which is dead.
108 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
109 F->eraseFromParent();
110
111 // Return the new function which has the right type.
112 return Entry = NewFn;
113}
114
115llvm::Constant *CodeGenModule::GetAddrOfFileVarDecl(const FileVarDecl *D,
116 bool isDefinition) {
117 // See if it is already in the map.
118 llvm::Constant *&Entry = GlobalDeclMap[D];
119 if (Entry) return Entry;
120
121 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
122
123 // Check to see if the global already exists.
124 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName());
125
126 // If it doesn't already exist, just create and return an entry.
127 if (GV == 0) {
128 return Entry = new llvm::GlobalVariable(Ty, false,
129 llvm::GlobalValue::ExternalLinkage,
130 0, D->getName(), &getModule());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000131 }
132
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000133 // If the pointer type matches, just return it.
134 llvm::Type *PTy = llvm::PointerType::get(Ty);
135 if (PTy == GV->getType()) return Entry = GV;
136
137 // If this isn't a definition, just return it casted to the right type.
138 if (!isDefinition)
139 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
140
141
142 // Otherwise, we have a definition after a prototype with the wrong type.
143 // GV is the GlobalVariable* for the one with the wrong type, we must make a
144 /// new GlobalVariable* and update everything that used GV (a declaration)
145 // with the new GlobalVariable* (which will be a definition).
146 //
147 // This happens if there is a prototype for a global (e.g. "extern int x[];")
148 // and then a definition of a different type (e.g. "int x[10];"). Start by
149 // making a new global of the correct type, RAUW, then steal the name.
150 llvm::GlobalVariable *NewGV =
151 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
152 0, D->getName(), &getModule());
153 NewGV->takeName(GV);
154
155 // Replace uses of GV with the globalvalue we will endow with a body.
156 llvm::Constant *NewPtrForOldDecl =
157 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
158 GV->replaceAllUsesWith(NewPtrForOldDecl);
159
160 // FIXME: Update the globaldeclmap for the previous decl of this name. We
161 // really want a way to walk all of these, but we don't have it yet. This
162 // is incredibly slow!
163 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
164
165 // Ok, delete the old global now, which is dead.
166 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
167 GV->eraseFromParent();
168
169 // Return the new global which has the right type.
170 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000171}
172
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000173
Chris Lattner4b009652007-07-25 00:24:17 +0000174void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
175 // If this is not a prototype, emit the body.
176 if (FD->getBody())
177 CodeGenFunction(*this).GenerateCode(FD);
178}
179
Chris Lattnercef01ec2007-11-23 22:07:55 +0000180static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000181 CodeGenModule &CGM);
Devang Patel08a10cc2007-10-30 21:27:20 +0000182
Chris Lattnercef01ec2007-11-23 22:07:55 +0000183/// GenerateConversionToBool - Generate comparison to zero for conversion to
184/// bool
185static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
186 QualType Source) {
187 if (Source->isRealFloatingType()) {
188 // Compare against 0.0 for fp scalars.
189 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
190 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
191 Zero);
192 }
193
194 assert((Source->isIntegerType() || Source->isPointerType()) &&
195 "Unknown scalar type to convert");
196
197 // Compare against an integer or pointer null.
198 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
199 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
200}
201
202/// GenerateConstantCast - Generates a constant cast to convert the Expression
203/// into the Target type.
204static llvm::Constant *GenerateConstantCast(const Expr *Expression,
205 QualType Target,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000206 CodeGenModule &CGM) {
207 CodeGenTypes& Types = CGM.getTypes();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000208 QualType Source = Expression->getType().getCanonicalType();
209 Target = Target.getCanonicalType();
210
211 assert (!Target->isVoidType());
212
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000213 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000214
215 if (Source == Target)
216 return SubExpr;
217
218 // Handle conversions to bool first, they are special: comparisons against 0.
219 if (Target->isBooleanType())
220 return GenerateConversionToBool(SubExpr, Source);
221
222 const llvm::Type *SourceType = Types.ConvertType(Source);
223 const llvm::Type *TargetType = Types.ConvertType(Target);
224
225 // Ignore conversions like int -> uint.
226 if (SubExpr->getType() == TargetType)
227 return SubExpr;
228
229 // Handle pointer conversions next: pointers can only be converted to/from
230 // other pointers and integers.
231 if (isa<llvm::PointerType>(TargetType)) {
232 // The source value may be an integer, or a pointer.
233 if (isa<llvm::PointerType>(SubExpr->getType()))
234 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
235 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
236 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
237 }
238
239 if (isa<llvm::PointerType>(SourceType)) {
240 // Must be an ptr to int cast.
241 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
242 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
243 }
244
245 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
246 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
247 }
248
249 // Finally, we have the arithmetic types: real int/float.
250 if (isa<llvm::IntegerType>(SourceType)) {
251 bool InputSigned = Source->isSignedIntegerType();
252 if (isa<llvm::IntegerType>(TargetType))
253 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
254 InputSigned);
255 else if (InputSigned)
256 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
257 else
258 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
259 }
260
261 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
262 if (isa<llvm::IntegerType>(TargetType)) {
263 if (Target->isSignedIntegerType())
264 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
265 else
266 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
267 }
268
269 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
270 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
271 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
272 else
273 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
274
275 assert (!"Unsupported cast type in global intialiser.");
276 return 0;
277}
278
Chris Lattnercef01ec2007-11-23 22:07:55 +0000279/// GenerateAggregateInit - Generate a Constant initaliser for global array or
280/// struct typed variables.
281static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000282 CodeGenModule &CGM) {
Chris Lattnercef01ec2007-11-23 22:07:55 +0000283 assert (ILE->getType()->isArrayType() || ILE->getType()->isStructureType());
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000284 CodeGenTypes& Types = CGM.getTypes();
Devang Patel08a10cc2007-10-30 21:27:20 +0000285
286 unsigned NumInitElements = ILE->getNumInits();
Christopher Lamb6db92f32007-12-02 08:49:54 +0000287 unsigned NumInitableElts = NumInitElements;
Devang Patel08a10cc2007-10-30 21:27:20 +0000288
Chris Lattnercef01ec2007-11-23 22:07:55 +0000289 const llvm::CompositeType *CType =
290 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
291 assert(CType);
292 std::vector<llvm::Constant*> Elts;
293
Christopher Lamb6db92f32007-12-02 08:49:54 +0000294 // Initialising an array requires us to automatically initialise any
295 // elements that have not been initialised explicitly
296 const llvm::ArrayType *AType = 0;
297 const llvm::Type *AElemTy = 0;
298 unsigned NumArrayElements = 0;
299
300 // If this is an array, we may have to truncate the initializer
301 if ((AType = dyn_cast<llvm::ArrayType>(CType))) {
302 NumArrayElements = AType->getNumElements();
303 AElemTy = AType->getElementType();
304 NumInitableElts = std::min(NumInitableElts, NumArrayElements);
305 }
306
Devang Patel08a10cc2007-10-30 21:27:20 +0000307 // Copy initializer elements.
308 unsigned i = 0;
Christopher Lamb6db92f32007-12-02 08:49:54 +0000309 for (i = 0; i < NumInitableElts; ++i) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000310 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000311 assert (C && "Failed to create initialiser expression");
312 Elts.push_back(C);
Devang Patel08a10cc2007-10-30 21:27:20 +0000313 }
314
Chris Lattnercef01ec2007-11-23 22:07:55 +0000315 if (ILE->getType()->isStructureType())
316 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000317
318 // Make sure we have an array at this point
Chris Lattnercef01ec2007-11-23 22:07:55 +0000319 assert(AType);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000320
Chris Lattnercef01ec2007-11-23 22:07:55 +0000321 // Initialize remaining array elements.
Devang Patel08a10cc2007-10-30 21:27:20 +0000322 for (; i < NumArrayElements; ++i)
Chris Lattnercef01ec2007-11-23 22:07:55 +0000323 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Christopher Lamb6db92f32007-12-02 08:49:54 +0000324
Chris Lattnercef01ec2007-11-23 22:07:55 +0000325 return llvm::ConstantArray::get(AType, Elts);
326}
327
328/// GenerateConstantExpr - Recursively builds a constant initialiser for the
329/// given expression.
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000330static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
331 CodeGenModule &CGM) {
332 CodeGenTypes& Types = CGM.getTypes();
333 ASTContext& Context = CGM.getContext();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000334 assert ((Expression->isConstantExpr(Context, 0) ||
335 Expression->getStmtClass() == Stmt::InitListExprClass) &&
336 "Only constant global initialisers are supported.");
337
338 QualType type = Expression->getType().getCanonicalType();
339
340 if (type->isIntegerType()) {
341 llvm::APSInt
342 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
343 if (Expression->isIntegerConstantExpr(Value, Context)) {
344 return llvm::ConstantInt::get(Value);
345 }
346 }
347
348 switch (Expression->getStmtClass()) {
349 // Generate constant for floating point literal values.
350 case Stmt::FloatingLiteralClass: {
351 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
352 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
353 }
354
355 // Generate constant for string literal values.
356 case Stmt::StringLiteralClass: {
357 const StringLiteral *SLiteral = cast<StringLiteral>(Expression);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000358 const char *StrData = SLiteral->getStrData();
359 unsigned Len = SLiteral->getByteLength();
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000360 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000361 }
362
363 // Elide parenthesis.
364 case Stmt::ParenExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000365 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000366
367 // Generate constant for sizeof operator.
368 // FIXME: Need to support AlignOf
369 case Stmt::SizeOfAlignOfTypeExprClass: {
370 const SizeOfAlignOfTypeExpr *SOExpr =
371 cast<SizeOfAlignOfTypeExpr>(Expression);
372 assert (SOExpr->isSizeOf());
373 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
374 }
375
376 // Generate constant cast expressions.
377 case Stmt::CastExprClass:
378 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000379 CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000380
381 case Stmt::ImplicitCastExprClass: {
382 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000383
384 // If this is due to array->pointer conversion, emit the array expression as
385 // an l-value.
386 if (ICExpr->getSubExpr()->getType()->isArrayType()) {
Chris Lattner21811c72007-12-02 07:32:25 +0000387 // Note that VLAs can't exist for global variables.
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000388 // The only thing that can have array type like this is a
389 // DeclRefExpr(FileVarDecl)?
390 const DeclRefExpr *DRE = cast<DeclRefExpr>(ICExpr->getSubExpr());
391 const FileVarDecl *FVD = cast<FileVarDecl>(DRE->getDecl());
392 llvm::Constant *C = CGM.GetAddrOfFileVarDecl(FVD, false);
393 assert(isa<llvm::PointerType>(C->getType()) &&
394 isa<llvm::ArrayType>(cast<llvm::PointerType>(C->getType())
Chris Lattner21811c72007-12-02 07:32:25 +0000395 ->getElementType()));
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000396 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
397
398 llvm::Constant *Ops[] = {Idx0, Idx0};
399 return llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
400 }
401
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000402 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000403 }
404
405 // Generate a constant array access expression
406 // FIXME: Clang's semantic analysis incorrectly prevents array access in
407 // global initialisers, preventing us from testing this.
408 case Stmt::ArraySubscriptExprClass: {
409 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000410 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGM);
411 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000412 return llvm::ConstantExpr::getExtractElement(Base, Index);
413 }
414
415 // Generate a constant expression to initialise an aggregate type, such as
416 // an array or struct.
417 case Stmt::InitListExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000418 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000419
420 default:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000421 CGM.WarnUnsupported(Expression, "initializer");
422 return llvm::UndefValue::get(Types.ConvertType(type));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000423 }
Chris Lattnercef01ec2007-11-23 22:07:55 +0000424}
425
Oliver Hunt253e0a72007-12-02 00:11:25 +0000426llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
427 return GenerateConstantExpr(Expression, *this);
Devang Patel08a10cc2007-10-30 21:27:20 +0000428}
429
Chris Lattner4b009652007-07-25 00:24:17 +0000430void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000431 // If this is just a forward declaration of the variable, don't emit it now,
432 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000433 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
434 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000435
436 // Get the global, forcing it to be a direct reference.
437 llvm::GlobalVariable *GV =
438 cast<llvm::GlobalVariable>(GetAddrOfFileVarDecl(D, true));
439
440 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000441 llvm::Constant *Init = 0;
442 if (D->getInit() == 0) {
443 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
444 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000445 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000446 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000447 if (D->getInit()->isIntegerConstantExpr(Value, Context))
448 Init = llvm::ConstantInt::get(Value);
449 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000450
Devang Patel08a10cc2007-10-30 21:27:20 +0000451 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000452 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000453
Devang Patel08a10cc2007-10-30 21:27:20 +0000454 assert(Init && "FIXME: Global variable initializers unimp!");
Chris Lattner4b009652007-07-25 00:24:17 +0000455
456 GV->setInitializer(Init);
457
458 // Set the llvm linkage type as appropriate.
459 // FIXME: This isn't right. This should handle common linkage and other
460 // stuff.
461 switch (D->getStorageClass()) {
462 case VarDecl::Auto:
463 case VarDecl::Register:
464 assert(0 && "Can't have auto or register globals");
465 case VarDecl::None:
466 case VarDecl::Extern:
467 // todo: common
468 break;
469 case VarDecl::Static:
470 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
471 break;
472 }
473}
474
475/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
476/// declarator chain.
477void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
478 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
479 EmitGlobalVar(D);
480}
481
Chris Lattnerab862cc2007-08-31 04:31:45 +0000482/// getBuiltinLibFunction
483llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
484 if (BuiltinFunctions.size() <= BuiltinID)
485 BuiltinFunctions.resize(BuiltinID);
486
487 // Already available?
488 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
489 if (FunctionSlot)
490 return FunctionSlot;
491
492 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
493
494 // Get the name, skip over the __builtin_ prefix.
495 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
496
497 // Get the type for the builtin.
498 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
499 const llvm::FunctionType *Ty =
500 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
501
502 // FIXME: This has a serious problem with code like this:
503 // void abs() {}
504 // ... __builtin_abs(x);
505 // The two versions of abs will collide. The fix is for the builtin to win,
506 // and for the existing one to be turned into a constantexpr cast of the
507 // builtin. In the case where the existing one is a static function, it
508 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000509 if (llvm::Function *Existing = getModule().getFunction(Name)) {
510 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
511 return FunctionSlot = Existing;
512 assert(Existing == 0 && "FIXME: Name collision");
513 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000514
515 // FIXME: param attributes for sext/zext etc.
516 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
517 Name, &getModule());
518}
519
520
Chris Lattner4b009652007-07-25 00:24:17 +0000521llvm::Function *CodeGenModule::getMemCpyFn() {
522 if (MemCpyFn) return MemCpyFn;
523 llvm::Intrinsic::ID IID;
524 uint64_t Size; unsigned Align;
525 Context.Target.getPointerInfo(Size, Align, SourceLocation());
526 switch (Size) {
527 default: assert(0 && "Unknown ptr width");
528 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
529 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
530 }
531 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
532}
Anders Carlsson36a04872007-08-21 00:21:21 +0000533
Chris Lattnerab862cc2007-08-31 04:31:45 +0000534llvm::Constant *CodeGenModule::
535GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000536 llvm::StringMapEntry<llvm::Constant *> &Entry =
537 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
538
539 if (Entry.getValue())
540 return Entry.getValue();
541
542 std::vector<llvm::Constant*> Fields;
543
544 if (!CFConstantStringClassRef) {
545 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
546 Ty = llvm::ArrayType::get(Ty, 0);
547
548 CFConstantStringClassRef =
549 new llvm::GlobalVariable(Ty, false,
550 llvm::GlobalVariable::ExternalLinkage, 0,
551 "__CFConstantStringClassReference",
552 &getModule());
553 }
554
555 // Class pointer.
556 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
557 llvm::Constant *Zeros[] = { Zero, Zero };
558 llvm::Constant *C =
559 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
560 Fields.push_back(C);
561
562 // Flags.
563 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
564 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
565
566 // String pointer.
567 C = llvm::ConstantArray::get(str);
568 C = new llvm::GlobalVariable(C->getType(), true,
569 llvm::GlobalValue::InternalLinkage,
570 C, ".str", &getModule());
571
572 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
573 Fields.push_back(C);
574
575 // String length.
576 Ty = getTypes().ConvertType(getContext().LongTy);
577 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
578
579 // The struct.
580 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
581 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000582 llvm::GlobalVariable *GV =
583 new llvm::GlobalVariable(C->getType(), true,
584 llvm::GlobalVariable::InternalLinkage,
585 C, "", &getModule());
586 GV->setSection("__DATA,__cfstring");
587 Entry.setValue(GV);
588 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000589}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000590
591/// GenerateWritableString -- Creates storage for a string literal
592static llvm::Constant *GenerateStringLiteral(const std::string &str,
593 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000594 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000595 // Create Constant for this string literal
596 llvm::Constant *C=llvm::ConstantArray::get(str);
597
598 // Create a global variable for this string
599 C = new llvm::GlobalVariable(C->getType(), constant,
600 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000601 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000602 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
603 llvm::Constant *Zeros[] = { Zero, Zero };
604 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
605 return C;
606}
607
608/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
609/// element of a character array containing the literal.
610llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
611 // Don't share any string literals if writable-strings is turned on.
612 if (Features.WritableStrings)
613 return GenerateStringLiteral(str, false, *this);
614
615 llvm::StringMapEntry<llvm::Constant *> &Entry =
616 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
617
618 if (Entry.getValue())
619 return Entry.getValue();
620
621 // Create a global variable for this.
622 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
623 Entry.setValue(C);
624 return C;
625}