blob: 21b372b3477b835150ce5b31fe0bb23a96943363 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner2c8569d2007-12-02 07:19:18 +000018#include "clang/Basic/Diagnostic.h"
Chris Lattner45e8cbd2007-11-28 05:34:05 +000019#include "clang/Basic/LangOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000021#include "llvm/CallingConv.h"
Chris Lattner8f32f712007-07-14 00:23:28 +000022#include "llvm/Constants.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "llvm/DerivedTypes.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000024#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "llvm/Intrinsics.h"
Christopher Lambce39faa2007-12-02 08:49:54 +000026#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28using namespace CodeGen;
29
30
Chris Lattner45e8cbd2007-11-28 05:34:05 +000031CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-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 Lattner2b94fe32008-03-01 08:45:05 +000035 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
36 //TODO: Make this selectable at runtime
Chris Lattner391d77a2008-03-30 23:03:07 +000037 Runtime = CreateObjCRuntime(M,
38 getTypes().ConvertType(getContext().IntTy),
39 getTypes().ConvertType(getContext().LongTy));
Chris Lattner2b94fe32008-03-01 08:45:05 +000040}
41
42CodeGenModule::~CodeGenModule() {
Chris Lattner391d77a2008-03-30 23:03:07 +000043 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerce5605e2008-03-30 23:25:33 +000044 if (ObjCInitFunction)
Chris Lattner391d77a2008-03-30 23:03:07 +000045 AddGlobalCtor(ObjCInitFunction);
Chris Lattner6d397602008-03-14 17:18:18 +000046 EmitGlobalCtors();
Chris Lattner2b94fe32008-03-01 08:45:05 +000047 delete Runtime;
48}
Reid Spencer5f016e22007-07-11 17:01:13 +000049
Chris Lattner2c8569d2007-12-02 07:19:18 +000050/// WarnUnsupported - Print out a warning that codegen doesn't support the
51/// specified stmt yet.
52void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
53 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
54 "cannot codegen this %0 yet");
55 SourceRange Range = S->getSourceRange();
56 std::string Msg = Type;
Ted Kremenek9c728dc2007-12-12 22:39:36 +000057 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000058 &Msg, 1, &Range, 1);
Chris Lattner2c8569d2007-12-02 07:19:18 +000059}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000060
Chris Lattnerc6fdc342008-01-12 07:05:38 +000061/// WarnUnsupported - Print out a warning that codegen doesn't support the
62/// specified decl yet.
63void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
64 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
65 "cannot codegen this %0 yet");
66 std::string Msg = Type;
67 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
68 &Msg, 1);
69}
70
Chris Lattner6d397602008-03-14 17:18:18 +000071/// AddGlobalCtor - Add a function to the list that will be called before
72/// main() runs.
73void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
74 // TODO: Type coercion of void()* types.
75 GlobalCtors.push_back(Ctor);
76}
77
Chris Lattner391d77a2008-03-30 23:03:07 +000078/// EmitGlobalCtors - Generates the array of contsturctor functions to be
79/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner6d397602008-03-14 17:18:18 +000080void CodeGenModule::EmitGlobalCtors() {
Chris Lattner391d77a2008-03-30 23:03:07 +000081 if (GlobalCtors.empty()) return;
Chris Lattnerce5605e2008-03-30 23:25:33 +000082
Chris Lattner6d397602008-03-14 17:18:18 +000083 // Get the type of @llvm.global_ctors
84 std::vector<const llvm::Type*> CtorFields;
85 CtorFields.push_back(llvm::IntegerType::get(32));
86 // Constructor function type
87 std::vector<const llvm::Type*> VoidArgs;
Chris Lattnerce5605e2008-03-30 23:25:33 +000088 llvm::FunctionType* CtorFuncTy =
89 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
90
Chris Lattner6d397602008-03-14 17:18:18 +000091 // i32, function type pair
Chris Lattner572cf092008-03-19 05:24:56 +000092 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
93 llvm::StructType* CtorStructTy =
94 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner6d397602008-03-14 17:18:18 +000095 // Array of fields
Chris Lattner572cf092008-03-19 05:24:56 +000096 llvm::ArrayType* GlobalCtorsTy =
97 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner6d397602008-03-14 17:18:18 +000098
Chris Lattner6d397602008-03-14 17:18:18 +000099 // Define the global variable
Chris Lattner572cf092008-03-19 05:24:56 +0000100 llvm::GlobalVariable *GlobalCtorsVal =
101 new llvm::GlobalVariable(GlobalCtorsTy, false,
102 llvm::GlobalValue::AppendingLinkage,
103 (llvm::Constant*)0, "llvm.global_ctors",
104 &TheModule);
Chris Lattner6d397602008-03-14 17:18:18 +0000105
106 // Populate the array
107 std::vector<llvm::Constant*> CtorValues;
Chris Lattner572cf092008-03-19 05:24:56 +0000108 llvm::Constant *MagicNumber =
109 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
110 std::vector<llvm::Constant*> StructValues;
Chris Lattner6d397602008-03-14 17:18:18 +0000111 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattner572cf092008-03-19 05:24:56 +0000112 E = GlobalCtors.end(); I != E; ++I) {
113 StructValues.clear();
Chris Lattner6d397602008-03-14 17:18:18 +0000114 StructValues.push_back(MagicNumber);
115 StructValues.push_back(*I);
116
Chris Lattner572cf092008-03-19 05:24:56 +0000117 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner6d397602008-03-14 17:18:18 +0000118 }
Chris Lattner572cf092008-03-19 05:24:56 +0000119
120 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
121 CtorValues));
Chris Lattner6d397602008-03-14 17:18:18 +0000122}
123
Chris Lattner391d77a2008-03-30 23:03:07 +0000124
125
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000126/// ReplaceMapValuesWith - This is a really slow and bad function that
127/// searches for any entries in GlobalDeclMap that point to OldVal, changing
128/// them to point to NewVal. This is badbadbad, FIXME!
129void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
130 llvm::Constant *NewVal) {
131 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
132 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
133 if (I->second == OldVal) I->second = NewVal;
134}
135
136
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000137llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
138 bool isDefinition) {
139 // See if it is already in the map. If so, just return it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 llvm::Constant *&Entry = GlobalDeclMap[D];
141 if (Entry) return Entry;
142
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000143 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
144
145 // Check to see if the function already exists.
146 llvm::Function *F = getModule().getFunction(D->getName());
147 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
148
149 // If it doesn't already exist, just create and return an entry.
150 if (F == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 // FIXME: param attributes for sext/zext etc.
Nate Begemanec9426c2008-03-09 03:09:36 +0000152 F = new llvm::Function(FTy, llvm::Function::ExternalLinkage, D->getName(),
153 &getModule());
154
155 // Set the appropriate calling convention for the Function.
156 if (D->getAttr<FastCallAttr>())
157 F->setCallingConv(llvm::CallingConv::Fast);
158 return Entry = F;
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 }
160
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000161 // If the pointer type matches, just return it.
Christopher Lambddc23f32007-12-17 01:11:20 +0000162 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000163 if (PFTy == F->getType()) return Entry = F;
Chris Lattnerfafad832007-12-02 06:30:46 +0000164
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000165 // If this isn't a definition, just return it casted to the right type.
166 if (!isDefinition)
167 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
168
169 // Otherwise, we have a definition after a prototype with the wrong type.
170 // F is the Function* for the one with the wrong type, we must make a new
171 // Function* and update everything that used F (a declaration) with the new
172 // Function* (which will be a definition).
173 //
174 // This happens if there is a prototype for a function (e.g. "int f()") and
175 // then a definition of a different type (e.g. "int f(int x)"). Start by
176 // making a new function of the correct type, RAUW, then steal the name.
177 llvm::Function *NewFn = new llvm::Function(FTy,
178 llvm::Function::ExternalLinkage,
179 "", &getModule());
180 NewFn->takeName(F);
181
182 // Replace uses of F with the Function we will endow with a body.
183 llvm::Constant *NewPtrForOldDecl =
184 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
185 F->replaceAllUsesWith(NewPtrForOldDecl);
186
187 // FIXME: Update the globaldeclmap for the previous decl of this name. We
188 // really want a way to walk all of these, but we don't have it yet. This
189 // is incredibly slow!
190 ReplaceMapValuesWith(F, NewPtrForOldDecl);
191
192 // Ok, delete the old function now, which is dead.
193 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
194 F->eraseFromParent();
195
196 // Return the new function which has the right type.
197 return Entry = NewFn;
198}
199
Chris Lattnerc4b23a52008-02-05 06:37:34 +0000200static bool IsZeroElementArray(const llvm::Type *Ty) {
201 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
202 return ATy->getNumElements() == 0;
203 return false;
204}
205
Chris Lattner2b9d2ca2007-12-18 08:16:44 +0000206llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
207 bool isDefinition) {
208 assert(D->hasGlobalStorage() && "Not a global variable");
209
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000210 // See if it is already in the map.
211 llvm::Constant *&Entry = GlobalDeclMap[D];
212 if (Entry) return Entry;
213
Christopher Lambebb97e92008-02-04 02:31:56 +0000214 QualType ASTTy = D->getType();
215 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000216
217 // Check to see if the global already exists.
Chris Lattner49573782008-02-02 04:43:11 +0000218 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000219
220 // If it doesn't already exist, just create and return an entry.
221 if (GV == 0) {
222 return Entry = new llvm::GlobalVariable(Ty, false,
223 llvm::GlobalValue::ExternalLinkage,
Christopher Lambebb97e92008-02-04 02:31:56 +0000224 0, D->getName(), &getModule(), 0,
225 ASTTy.getAddressSpace());
Chris Lattnerfafad832007-12-02 06:30:46 +0000226 }
227
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000228 // If the pointer type matches, just return it.
Christopher Lambddc23f32007-12-17 01:11:20 +0000229 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000230 if (PTy == GV->getType()) return Entry = GV;
231
232 // If this isn't a definition, just return it casted to the right type.
233 if (!isDefinition)
234 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
235
236
237 // Otherwise, we have a definition after a prototype with the wrong type.
238 // GV is the GlobalVariable* for the one with the wrong type, we must make a
239 /// new GlobalVariable* and update everything that used GV (a declaration)
240 // with the new GlobalVariable* (which will be a definition).
241 //
242 // This happens if there is a prototype for a global (e.g. "extern int x[];")
243 // and then a definition of a different type (e.g. "int x[10];"). Start by
244 // making a new global of the correct type, RAUW, then steal the name.
245 llvm::GlobalVariable *NewGV =
246 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lambebb97e92008-02-04 02:31:56 +0000247 0, D->getName(), &getModule(), 0,
248 ASTTy.getAddressSpace());
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000249 NewGV->takeName(GV);
250
251 // Replace uses of GV with the globalvalue we will endow with a body.
252 llvm::Constant *NewPtrForOldDecl =
253 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
254 GV->replaceAllUsesWith(NewPtrForOldDecl);
255
256 // FIXME: Update the globaldeclmap for the previous decl of this name. We
257 // really want a way to walk all of these, but we don't have it yet. This
258 // is incredibly slow!
259 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
260
Chris Lattnerc4b23a52008-02-05 06:37:34 +0000261 // Verify that GV was a declaration or something like x[] which turns into
262 // [0 x type].
263 assert((GV->isDeclaration() ||
264 IsZeroElementArray(GV->getType()->getElementType())) &&
265 "Shouldn't replace non-declaration");
266
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000267 // Ok, delete the old global now, which is dead.
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000268 GV->eraseFromParent();
269
270 // Return the new global which has the right type.
271 return Entry = NewGV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000272}
273
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000274
Chris Lattner391d77a2008-03-30 23:03:07 +0000275void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
276 // If this is not a prototype, emit the body.
277 if (OMD->getBody())
278 CodeGenFunction(*this).GenerateObjCMethod(OMD);
279}
280
Chris Lattner88a69ad2007-07-13 05:13:43 +0000281void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 // If this is not a prototype, emit the body.
283 if (FD->getBody())
284 CodeGenFunction(*this).GenerateCode(FD);
285}
286
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000287llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
288 return EmitConstantExpr(Expr);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000289}
290
Chris Lattner88a69ad2007-07-13 05:13:43 +0000291void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000292 // If this is just a forward declaration of the variable, don't emit it now,
293 // allow it to be emitted lazily on its first use.
Chris Lattner88a69ad2007-07-13 05:13:43 +0000294 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
295 return;
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000296
297 // Get the global, forcing it to be a direct reference.
298 llvm::GlobalVariable *GV =
Chris Lattner2b9d2ca2007-12-18 08:16:44 +0000299 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000300
301 // Convert the initializer, or use zero if appropriate.
Chris Lattner8f32f712007-07-14 00:23:28 +0000302 llvm::Constant *Init = 0;
303 if (D->getInit() == 0) {
Chris Lattner88a69ad2007-07-13 05:13:43 +0000304 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
Chris Lattner8f32f712007-07-14 00:23:28 +0000305 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiser7b660002007-10-17 15:00:17 +0000306 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner98be4942008-03-05 18:54:05 +0000307 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner590b6642007-07-15 23:26:56 +0000308 if (D->getInit()->isIntegerConstantExpr(Value, Context))
Chris Lattner8f32f712007-07-14 00:23:28 +0000309 Init = llvm::ConstantInt::get(Value);
310 }
Devang Patel8e53e722007-10-26 16:31:40 +0000311
Devang Patel9e32d4b2007-10-30 21:27:20 +0000312 if (!Init)
Oliver Hunt28247232007-12-02 00:11:25 +0000313 Init = EmitGlobalInit(D->getInit());
Devang Patel8e53e722007-10-26 16:31:40 +0000314
Chris Lattnerf89dfb22007-12-10 00:05:55 +0000315 assert(GV->getType()->getElementType() == Init->getType() &&
316 "Initializer codegen type mismatch!");
Chris Lattner88a69ad2007-07-13 05:13:43 +0000317 GV->setInitializer(Init);
Chris Lattnerddee4232008-03-03 03:28:21 +0000318
319 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
320 GV->setVisibility(attr->getVisibility());
321 // FIXME: else handle -fvisibility
Chris Lattner88a69ad2007-07-13 05:13:43 +0000322
323 // Set the llvm linkage type as appropriate.
Chris Lattnerddee4232008-03-03 03:28:21 +0000324 if (D->getAttr<DLLImportAttr>())
325 GV->setLinkage(llvm::Function::DLLImportLinkage);
326 else if (D->getAttr<DLLExportAttr>())
327 GV->setLinkage(llvm::Function::DLLExportLinkage);
328 else if (D->getAttr<WeakAttr>()) {
329 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
330
331 } else {
332 // FIXME: This isn't right. This should handle common linkage and other
333 // stuff.
334 switch (D->getStorageClass()) {
335 case VarDecl::Auto:
336 case VarDecl::Register:
337 assert(0 && "Can't have auto or register globals");
338 case VarDecl::None:
339 if (!D->getInit())
340 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
341 break;
342 case VarDecl::Extern:
343 case VarDecl::PrivateExtern:
344 // todo: common
345 break;
346 case VarDecl::Static:
347 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
348 break;
349 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000350 }
351}
Reid Spencer5f016e22007-07-11 17:01:13 +0000352
Chris Lattner32b266c2007-07-14 00:16:50 +0000353/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
354/// declarator chain.
355void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
356 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
357 EmitGlobalVar(D);
358}
Reid Spencer5f016e22007-07-11 17:01:13 +0000359
Chris Lattnerc5b88062008-02-06 05:08:19 +0000360void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
361 // Make sure that this type is translated.
362 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000363}
364
365
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000366/// getBuiltinLibFunction
367llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000368 if (BuiltinID > BuiltinFunctions.size())
369 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000370
Chris Lattner1426fec2007-12-13 00:38:03 +0000371 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
372 // a slot for it.
373 assert(BuiltinID && "Invalid Builtin ID");
374 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000375 if (FunctionSlot)
376 return FunctionSlot;
377
378 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
379
380 // Get the name, skip over the __builtin_ prefix.
381 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
382
383 // Get the type for the builtin.
384 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
385 const llvm::FunctionType *Ty =
386 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
387
388 // FIXME: This has a serious problem with code like this:
389 // void abs() {}
390 // ... __builtin_abs(x);
391 // The two versions of abs will collide. The fix is for the builtin to win,
392 // and for the existing one to be turned into a constantexpr cast of the
393 // builtin. In the case where the existing one is a static function, it
394 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000395 if (llvm::Function *Existing = getModule().getFunction(Name)) {
396 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
397 return FunctionSlot = Existing;
398 assert(Existing == 0 && "FIXME: Name collision");
399 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000400
401 // FIXME: param attributes for sext/zext etc.
402 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
403 Name, &getModule());
404}
405
Chris Lattner7acda7c2007-12-18 00:25:38 +0000406llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
407 unsigned NumTys) {
408 return llvm::Intrinsic::getDeclaration(&getModule(),
409 (llvm::Intrinsic::ID)IID, Tys, NumTys);
410}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412llvm::Function *CodeGenModule::getMemCpyFn() {
413 if (MemCpyFn) return MemCpyFn;
414 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000415 switch (Context.Target.getPointerWidth(0)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 default: assert(0 && "Unknown ptr width");
417 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
418 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
419 }
Chris Lattner7acda7c2007-12-18 00:25:38 +0000420 return MemCpyFn = getIntrinsic(IID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000421}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000422
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000423llvm::Function *CodeGenModule::getMemSetFn() {
424 if (MemSetFn) return MemSetFn;
425 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000426 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000427 default: assert(0 && "Unknown ptr width");
428 case 32: IID = llvm::Intrinsic::memset_i32; break;
429 case 64: IID = llvm::Intrinsic::memset_i64; break;
430 }
431 return MemSetFn = getIntrinsic(IID);
432}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000433
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000434llvm::Constant *CodeGenModule::
435GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000436 llvm::StringMapEntry<llvm::Constant *> &Entry =
437 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
438
439 if (Entry.getValue())
440 return Entry.getValue();
441
442 std::vector<llvm::Constant*> Fields;
443
444 if (!CFConstantStringClassRef) {
445 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
446 Ty = llvm::ArrayType::get(Ty, 0);
447
448 CFConstantStringClassRef =
449 new llvm::GlobalVariable(Ty, false,
450 llvm::GlobalVariable::ExternalLinkage, 0,
451 "__CFConstantStringClassReference",
452 &getModule());
453 }
454
455 // Class pointer.
456 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
457 llvm::Constant *Zeros[] = { Zero, Zero };
458 llvm::Constant *C =
459 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
460 Fields.push_back(C);
461
462 // Flags.
463 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
464 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
465
466 // String pointer.
467 C = llvm::ConstantArray::get(str);
468 C = new llvm::GlobalVariable(C->getType(), true,
469 llvm::GlobalValue::InternalLinkage,
470 C, ".str", &getModule());
471
472 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
473 Fields.push_back(C);
474
475 // String length.
476 Ty = getTypes().ConvertType(getContext().LongTy);
477 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
478
479 // The struct.
480 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
481 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000482 llvm::GlobalVariable *GV =
483 new llvm::GlobalVariable(C->getType(), true,
484 llvm::GlobalVariable::InternalLinkage,
485 C, "", &getModule());
486 GV->setSection("__DATA,__cfstring");
487 Entry.setValue(GV);
488 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000489}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000490
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000491/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000492static llvm::Constant *GenerateStringLiteral(const std::string &str,
493 bool constant,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000494 CodeGenModule &CGM) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000495 // Create Constant for this string literal
496 llvm::Constant *C=llvm::ConstantArray::get(str);
497
498 // Create a global variable for this string
499 C = new llvm::GlobalVariable(C->getType(), constant,
500 llvm::GlobalValue::InternalLinkage,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000501 C, ".str", &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000502 return C;
503}
504
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000505/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
506/// array containing the literal. The result is pointer to array type.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000507llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
508 // Don't share any string literals if writable-strings is turned on.
509 if (Features.WritableStrings)
510 return GenerateStringLiteral(str, false, *this);
511
512 llvm::StringMapEntry<llvm::Constant *> &Entry =
513 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
514
515 if (Entry.getValue())
516 return Entry.getValue();
517
518 // Create a global variable for this.
519 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
520 Entry.setValue(C);
521 return C;
522}