blob: f14a0858d3038c2856c9eabe5bcfee89595428ac [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"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000019#include "clang/Basic/Diagnostic.h"
Chris Lattnerdb6be562007-11-28 05:34:05 +000020#include "clang/Basic/LangOptions.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 Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000026#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/Intrinsics.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000028#include "llvm/Analysis/Verifier.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000029#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattnerdb6be562007-11-28 05:34:05 +000034CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000035 llvm::Module &M, const llvm::TargetData &TD,
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000036 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000037 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Eli Friedman8f08a252008-05-26 12:59:39 +000038 Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
39 CFConstantStringClassRef(0) {
Chris Lattnercbfb5512008-03-01 08:45:05 +000040 //TODO: Make this selectable at runtime
Chris Lattnerb326b172008-03-30 23:03:07 +000041 Runtime = CreateObjCRuntime(M,
42 getTypes().ConvertType(getContext().IntTy),
43 getTypes().ConvertType(getContext().LongTy));
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000044
45 // If debug info generation is enabled, create the CGDebugInfo object.
46 if (GenerateDebugInfo)
47 DebugInfo = new CGDebugInfo(this);
48 else
49 DebugInfo = NULL;
Chris Lattnercbfb5512008-03-01 08:45:05 +000050}
51
52CodeGenModule::~CodeGenModule() {
Chris Lattnerb326b172008-03-30 23:03:07 +000053 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000054 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000055 AddGlobalCtor(ObjCInitFunction);
Nate Begemanad320b62008-04-20 06:29:50 +000056 EmitStatics();
Chris Lattner753d2592008-03-14 17:18:18 +000057 EmitGlobalCtors();
Nate Begeman52da5c72008-04-18 23:43:57 +000058 EmitAnnotations();
Chris Lattnercbfb5512008-03-01 08:45:05 +000059 delete Runtime;
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000060 delete DebugInfo;
Chris Lattnerb033c4a2008-04-30 16:05:42 +000061 // Run the verifier to check that the generated code is consistent.
62 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000063}
Chris Lattner4b009652007-07-25 00:24:17 +000064
Chris Lattnercf9c9d02007-12-02 07:19:18 +000065/// WarnUnsupported - Print out a warning that codegen doesn't support the
66/// specified stmt yet.
67void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
68 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
69 "cannot codegen this %0 yet");
70 SourceRange Range = S->getSourceRange();
71 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000072 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000073 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000074}
Chris Lattner0e4755d2007-12-02 06:27:33 +000075
Chris Lattner806a5f52008-01-12 07:05:38 +000076/// WarnUnsupported - Print out a warning that codegen doesn't support the
77/// specified decl yet.
78void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
79 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
80 "cannot codegen this %0 yet");
81 std::string Msg = Type;
82 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
83 &Msg, 1);
84}
85
Dan Gohman4751a3a2008-05-22 00:50:06 +000086/// setVisibility - Set the visibility for the given LLVM GlobalValue
87/// according to the given clang AST visibility value.
88void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
89 VisibilityAttr::VisibilityTypes Vis) {
90 switch (Vis) {
91 default: assert(0 && "Unknown visibility!");
92 case VisibilityAttr::DefaultVisibility:
93 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
94 break;
95 case VisibilityAttr::HiddenVisibility:
96 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
97 break;
98 case VisibilityAttr::ProtectedVisibility:
99 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
100 break;
101 }
102}
103
Chris Lattner753d2592008-03-14 17:18:18 +0000104/// AddGlobalCtor - Add a function to the list that will be called before
105/// main() runs.
106void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
107 // TODO: Type coercion of void()* types.
108 GlobalCtors.push_back(Ctor);
109}
110
Chris Lattnerb326b172008-03-30 23:03:07 +0000111/// EmitGlobalCtors - Generates the array of contsturctor functions to be
112/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner753d2592008-03-14 17:18:18 +0000113void CodeGenModule::EmitGlobalCtors() {
Chris Lattnerb326b172008-03-30 23:03:07 +0000114 if (GlobalCtors.empty()) return;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000115
Chris Lattner753d2592008-03-14 17:18:18 +0000116 // Get the type of @llvm.global_ctors
117 std::vector<const llvm::Type*> CtorFields;
118 CtorFields.push_back(llvm::IntegerType::get(32));
119 // Constructor function type
120 std::vector<const llvm::Type*> VoidArgs;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000121 llvm::FunctionType* CtorFuncTy =
122 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
123
Chris Lattner753d2592008-03-14 17:18:18 +0000124 // i32, function type pair
Chris Lattnera18c12e2008-03-19 05:24:56 +0000125 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
126 llvm::StructType* CtorStructTy =
127 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000128 // Array of fields
Chris Lattnera18c12e2008-03-19 05:24:56 +0000129 llvm::ArrayType* GlobalCtorsTy =
130 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner753d2592008-03-14 17:18:18 +0000131
Chris Lattner753d2592008-03-14 17:18:18 +0000132 // Define the global variable
Chris Lattnera18c12e2008-03-19 05:24:56 +0000133 llvm::GlobalVariable *GlobalCtorsVal =
134 new llvm::GlobalVariable(GlobalCtorsTy, false,
135 llvm::GlobalValue::AppendingLinkage,
136 (llvm::Constant*)0, "llvm.global_ctors",
137 &TheModule);
Chris Lattner753d2592008-03-14 17:18:18 +0000138
139 // Populate the array
140 std::vector<llvm::Constant*> CtorValues;
Chris Lattnera18c12e2008-03-19 05:24:56 +0000141 llvm::Constant *MagicNumber =
142 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
143 std::vector<llvm::Constant*> StructValues;
Chris Lattner753d2592008-03-14 17:18:18 +0000144 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattnera18c12e2008-03-19 05:24:56 +0000145 E = GlobalCtors.end(); I != E; ++I) {
146 StructValues.clear();
Chris Lattner753d2592008-03-14 17:18:18 +0000147 StructValues.push_back(MagicNumber);
148 StructValues.push_back(*I);
149
Chris Lattnera18c12e2008-03-19 05:24:56 +0000150 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000151 }
Chris Lattnera18c12e2008-03-19 05:24:56 +0000152
153 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
154 CtorValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000155}
156
Chris Lattnerb326b172008-03-30 23:03:07 +0000157
158
Nate Begeman52da5c72008-04-18 23:43:57 +0000159void CodeGenModule::EmitAnnotations() {
160 if (Annotations.empty())
161 return;
162
163 // Create a new global variable for the ConstantStruct in the Module.
164 llvm::Constant *Array =
165 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
166 Annotations.size()),
167 Annotations);
168 llvm::GlobalValue *gv =
169 new llvm::GlobalVariable(Array->getType(), false,
170 llvm::GlobalValue::AppendingLinkage, Array,
171 "llvm.global.annotations", &TheModule);
172 gv->setSection("llvm.metadata");
173}
174
Chris Lattner0e4755d2007-12-02 06:27:33 +0000175/// ReplaceMapValuesWith - This is a really slow and bad function that
176/// searches for any entries in GlobalDeclMap that point to OldVal, changing
177/// them to point to NewVal. This is badbadbad, FIXME!
178void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
179 llvm::Constant *NewVal) {
180 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
181 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
182 if (I->second == OldVal) I->second = NewVal;
183}
184
185
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000186llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
187 bool isDefinition) {
188 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +0000189 llvm::Constant *&Entry = GlobalDeclMap[D];
Eli Friedman725d2be2008-05-20 09:21:07 +0000190#if 0
191 // FIXME: The cache is currently broken!
Chris Lattner4b009652007-07-25 00:24:17 +0000192 if (Entry) return Entry;
Eli Friedman725d2be2008-05-20 09:21:07 +0000193#endif
194
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000195 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
196
197 // Check to see if the function already exists.
198 llvm::Function *F = getModule().getFunction(D->getName());
199 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
200
201 // If it doesn't already exist, just create and return an entry.
202 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000203 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000204 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
205 D->getName(), &getModule());
Nate Begemandc6262e2008-03-09 03:09:36 +0000206
207 // Set the appropriate calling convention for the Function.
208 if (D->getAttr<FastCallAttr>())
209 F->setCallingConv(llvm::CallingConv::Fast);
210 return Entry = F;
Chris Lattner4b009652007-07-25 00:24:17 +0000211 }
212
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000213 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000214 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000215 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +0000216
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000217 // If this isn't a definition, just return it casted to the right type.
218 if (!isDefinition)
219 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
220
221 // Otherwise, we have a definition after a prototype with the wrong type.
222 // F is the Function* for the one with the wrong type, we must make a new
223 // Function* and update everything that used F (a declaration) with the new
224 // Function* (which will be a definition).
225 //
226 // This happens if there is a prototype for a function (e.g. "int f()") and
227 // then a definition of a different type (e.g. "int f(int x)"). Start by
228 // making a new function of the correct type, RAUW, then steal the name.
Gabor Greif815e2c12008-04-06 20:42:52 +0000229 llvm::Function *NewFn = llvm::Function::Create(FTy,
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000230 llvm::Function::ExternalLinkage,
231 "", &getModule());
232 NewFn->takeName(F);
233
234 // Replace uses of F with the Function we will endow with a body.
235 llvm::Constant *NewPtrForOldDecl =
236 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
237 F->replaceAllUsesWith(NewPtrForOldDecl);
238
239 // FIXME: Update the globaldeclmap for the previous decl of this name. We
240 // really want a way to walk all of these, but we don't have it yet. This
241 // is incredibly slow!
242 ReplaceMapValuesWith(F, NewPtrForOldDecl);
243
244 // Ok, delete the old function now, which is dead.
245 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
246 F->eraseFromParent();
247
248 // Return the new function which has the right type.
249 return Entry = NewFn;
250}
251
Chris Lattner0db06992008-02-05 06:37:34 +0000252static bool IsZeroElementArray(const llvm::Type *Ty) {
253 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
254 return ATy->getNumElements() == 0;
255 return false;
256}
257
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000258llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
259 bool isDefinition) {
260 assert(D->hasGlobalStorage() && "Not a global variable");
261
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000262 // See if it is already in the map.
263 llvm::Constant *&Entry = GlobalDeclMap[D];
264 if (Entry) return Entry;
265
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000266 QualType ASTTy = D->getType();
267 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000268
269 // Check to see if the global already exists.
Chris Lattnered430e92008-02-02 04:43:11 +0000270 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000271
272 // If it doesn't already exist, just create and return an entry.
273 if (GV == 0) {
274 return Entry = new llvm::GlobalVariable(Ty, false,
275 llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000276 0, D->getName(), &getModule(), 0,
277 ASTTy.getAddressSpace());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000278 }
279
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000280 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000281 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000282 if (PTy == GV->getType()) return Entry = GV;
283
284 // If this isn't a definition, just return it casted to the right type.
285 if (!isDefinition)
286 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
287
288
289 // Otherwise, we have a definition after a prototype with the wrong type.
290 // GV is the GlobalVariable* for the one with the wrong type, we must make a
291 /// new GlobalVariable* and update everything that used GV (a declaration)
292 // with the new GlobalVariable* (which will be a definition).
293 //
294 // This happens if there is a prototype for a global (e.g. "extern int x[];")
295 // and then a definition of a different type (e.g. "int x[10];"). Start by
296 // making a new global of the correct type, RAUW, then steal the name.
297 llvm::GlobalVariable *NewGV =
298 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000299 0, D->getName(), &getModule(), 0,
300 ASTTy.getAddressSpace());
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000301 NewGV->takeName(GV);
302
303 // Replace uses of GV with the globalvalue we will endow with a body.
304 llvm::Constant *NewPtrForOldDecl =
305 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
306 GV->replaceAllUsesWith(NewPtrForOldDecl);
307
308 // FIXME: Update the globaldeclmap for the previous decl of this name. We
309 // really want a way to walk all of these, but we don't have it yet. This
310 // is incredibly slow!
311 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
312
Chris Lattner0db06992008-02-05 06:37:34 +0000313 // Verify that GV was a declaration or something like x[] which turns into
314 // [0 x type].
315 assert((GV->isDeclaration() ||
316 IsZeroElementArray(GV->getType()->getElementType())) &&
317 "Shouldn't replace non-declaration");
318
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000319 // Ok, delete the old global now, which is dead.
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000320 GV->eraseFromParent();
321
322 // Return the new global which has the right type.
323 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000324}
325
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000326
Chris Lattnerb326b172008-03-30 23:03:07 +0000327void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
328 // If this is not a prototype, emit the body.
329 if (OMD->getBody())
330 CodeGenFunction(*this).GenerateObjCMethod(OMD);
331}
332
Chris Lattner4b009652007-07-25 00:24:17 +0000333void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
334 // If this is not a prototype, emit the body.
Chris Lattner74bf5552008-05-04 02:29:49 +0000335 if (!FD->isThisDeclarationADefinition())
336 return;
337
338 // If the function is a static, defer code generation until later so we can
339 // easily omit unused statics.
340 if (FD->getStorageClass() != FunctionDecl::Static) {
Chris Lattner4b009652007-07-25 00:24:17 +0000341 CodeGenFunction(*this).GenerateCode(FD);
Chris Lattner74bf5552008-05-04 02:29:49 +0000342 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000343 }
Chris Lattner74bf5552008-05-04 02:29:49 +0000344
345 StaticDecls.push_back(FD);
Nate Begemanad320b62008-04-20 06:29:50 +0000346}
347
348void CodeGenModule::EmitStatics() {
349 // Emit code for each used static decl encountered. Since a previously unused
350 // static decl may become used during the generation of code for a static
351 // function, iterate until no changes are made.
352 bool Changed;
353 do {
354 Changed = false;
355 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Nate Begemanad320b62008-04-20 06:29:50 +0000356 const Decl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000357
358 // Check if we have used a decl with the same name
359 // FIXME: The AST should have some sort of aggregate decls or
360 // global symbol map.
361 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
362 if (!getModule().getFunction(FD->getName()))
363 continue;
364 } else {
365 if (!getModule().getNamedGlobal(cast<VarDecl>(D)->getName()))
366 continue;
367 }
368
Nate Begemanad320b62008-04-20 06:29:50 +0000369 // If this is a function decl, generate code for the static function if it
370 // has a body. Otherwise, we must have a var decl for a static global
371 // variable.
372 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
373 if (FD->getBody())
374 CodeGenFunction(*this).GenerateCode(FD);
375 } else {
Nate Begeman91f52012008-04-20 20:38:08 +0000376 EmitGlobalVarInit(cast<VarDecl>(D));
Nate Begemanad320b62008-04-20 06:29:50 +0000377 }
378 // Erase the used decl from the list.
379 StaticDecls[i] = StaticDecls.back();
380 StaticDecls.pop_back();
381 --i;
382 --e;
383
384 // Remember that we made a change.
385 Changed = true;
386 }
387 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000388}
389
Anders Carlssond76cead2008-01-26 01:36:00 +0000390llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
391 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000392}
393
Nate Begeman8a704172008-04-19 04:17:09 +0000394/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
395/// annotation information for a given GlobalValue. The annotation struct is
396/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
397/// GlobalValue being annotated. The second filed is thee constant string
398/// created from the AnnotateAttr's annotation. The third field is a constant
399/// string containing the name of the translation unit. The fourth field is
400/// the line number in the file of the annotated value declaration.
401///
402/// FIXME: this does not unique the annotation string constants, as llvm-gcc
403/// appears to.
404///
405llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
406 const AnnotateAttr *AA,
407 unsigned LineNo) {
408 llvm::Module *M = &getModule();
409
410 // get [N x i8] constants for the annotation string, and the filename string
411 // which are the 2nd and 3rd elements of the global annotation structure.
412 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
413 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
414 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
415 true);
416
417 // Get the two global values corresponding to the ConstantArrays we just
418 // created to hold the bytes of the strings.
419 llvm::GlobalValue *annoGV =
420 new llvm::GlobalVariable(anno->getType(), false,
421 llvm::GlobalValue::InternalLinkage, anno,
422 GV->getName() + ".str", M);
423 // translation unit name string, emitted into the llvm.metadata section.
424 llvm::GlobalValue *unitGV =
425 new llvm::GlobalVariable(unit->getType(), false,
426 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
427
428 // Create the ConstantStruct that is the global annotion.
429 llvm::Constant *Fields[4] = {
430 llvm::ConstantExpr::getBitCast(GV, SBP),
431 llvm::ConstantExpr::getBitCast(annoGV, SBP),
432 llvm::ConstantExpr::getBitCast(unitGV, SBP),
433 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
434 };
435 return llvm::ConstantStruct::get(Fields, 4, false);
436}
437
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000438void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
Nate Begemanad320b62008-04-20 06:29:50 +0000439 // If the VarDecl is a static, defer code generation until later so we can
440 // easily omit unused statics.
441 if (D->getStorageClass() == VarDecl::Static) {
442 StaticDecls.push_back(D);
443 return;
444 }
445
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000446 // If this is just a forward declaration of the variable, don't emit it now,
447 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000448 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
449 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000450
Nate Begemanad320b62008-04-20 06:29:50 +0000451 EmitGlobalVarInit(D);
452}
453
454void CodeGenModule::EmitGlobalVarInit(const VarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000455 // Get the global, forcing it to be a direct reference.
456 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000457 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000458
459 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000460 llvm::Constant *Init = 0;
461 if (D->getInit() == 0) {
462 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
463 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000464 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner8cd0e932008-03-05 18:54:05 +0000465 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner4b009652007-07-25 00:24:17 +0000466 if (D->getInit()->isIntegerConstantExpr(Value, Context))
467 Init = llvm::ConstantInt::get(Value);
468 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000469
Devang Patel08a10cc2007-10-30 21:27:20 +0000470 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000471 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000472
Nate Begeman8a704172008-04-19 04:17:09 +0000473 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
474 SourceManager &SM = Context.getSourceManager();
475 AddAnnotation(EmitAnnotateAttr(GV, AA,
476 SM.getLogicalLineNumber(D->getLocation())));
477 }
478
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000479 assert(GV->getType()->getElementType() == Init->getType() &&
480 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000481 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000482
483 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000484 setVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000485 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000486
487 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000488 if (D->getStorageClass() == VarDecl::Static)
489 GV->setLinkage(llvm::Function::InternalLinkage);
490 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000491 GV->setLinkage(llvm::Function::DLLImportLinkage);
492 else if (D->getAttr<DLLExportAttr>())
493 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000494 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000495 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000496 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000497 // FIXME: This isn't right. This should handle common linkage and other
498 // stuff.
499 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000500 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000501 case VarDecl::Auto:
502 case VarDecl::Register:
503 assert(0 && "Can't have auto or register globals");
504 case VarDecl::None:
505 if (!D->getInit())
506 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
507 break;
508 case VarDecl::Extern:
509 case VarDecl::PrivateExtern:
510 // todo: common
511 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000512 }
Chris Lattner4b009652007-07-25 00:24:17 +0000513 }
514}
515
516/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
517/// declarator chain.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000518void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
519 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
520 if (D->isFileVarDecl())
521 EmitGlobalVar(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000522}
523
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000524void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
525 // Make sure that this type is translated.
526 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000527}
528
529
Chris Lattnerab862cc2007-08-31 04:31:45 +0000530/// getBuiltinLibFunction
531llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000532 if (BuiltinID > BuiltinFunctions.size())
533 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000534
Chris Lattner9f2d6892007-12-13 00:38:03 +0000535 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
536 // a slot for it.
537 assert(BuiltinID && "Invalid Builtin ID");
538 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000539 if (FunctionSlot)
540 return FunctionSlot;
541
542 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
543
544 // Get the name, skip over the __builtin_ prefix.
545 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
546
547 // Get the type for the builtin.
548 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
549 const llvm::FunctionType *Ty =
550 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
551
552 // FIXME: This has a serious problem with code like this:
553 // void abs() {}
554 // ... __builtin_abs(x);
555 // The two versions of abs will collide. The fix is for the builtin to win,
556 // and for the existing one to be turned into a constantexpr cast of the
557 // builtin. In the case where the existing one is a static function, it
558 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000559 if (llvm::Function *Existing = getModule().getFunction(Name)) {
560 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
561 return FunctionSlot = Existing;
562 assert(Existing == 0 && "FIXME: Name collision");
563 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000564
565 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000566 return FunctionSlot =
567 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
568 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000569}
570
Chris Lattner4b23f942007-12-18 00:25:38 +0000571llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
572 unsigned NumTys) {
573 return llvm::Intrinsic::getDeclaration(&getModule(),
574 (llvm::Intrinsic::ID)IID, Tys, NumTys);
575}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000576
Chris Lattner4b009652007-07-25 00:24:17 +0000577llvm::Function *CodeGenModule::getMemCpyFn() {
578 if (MemCpyFn) return MemCpyFn;
579 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000580 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000581 default: assert(0 && "Unknown ptr width");
582 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
583 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
584 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000585 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000586}
Anders Carlsson36a04872007-08-21 00:21:21 +0000587
Eli Friedman8f08a252008-05-26 12:59:39 +0000588llvm::Function *CodeGenModule::getMemMoveFn() {
589 if (MemMoveFn) return MemMoveFn;
590 llvm::Intrinsic::ID IID;
591 switch (Context.Target.getPointerWidth(0)) {
592 default: assert(0 && "Unknown ptr width");
593 case 32: IID = llvm::Intrinsic::memmove_i32; break;
594 case 64: IID = llvm::Intrinsic::memmove_i64; break;
595 }
596 return MemMoveFn = getIntrinsic(IID);
597}
598
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000599llvm::Function *CodeGenModule::getMemSetFn() {
600 if (MemSetFn) return MemSetFn;
601 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000602 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000603 default: assert(0 && "Unknown ptr width");
604 case 32: IID = llvm::Intrinsic::memset_i32; break;
605 case 64: IID = llvm::Intrinsic::memset_i64; break;
606 }
607 return MemSetFn = getIntrinsic(IID);
608}
Chris Lattner4b23f942007-12-18 00:25:38 +0000609
Chris Lattnerab862cc2007-08-31 04:31:45 +0000610llvm::Constant *CodeGenModule::
611GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000612 llvm::StringMapEntry<llvm::Constant *> &Entry =
613 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
614
615 if (Entry.getValue())
616 return Entry.getValue();
617
618 std::vector<llvm::Constant*> Fields;
619
620 if (!CFConstantStringClassRef) {
621 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
622 Ty = llvm::ArrayType::get(Ty, 0);
623
624 CFConstantStringClassRef =
625 new llvm::GlobalVariable(Ty, false,
626 llvm::GlobalVariable::ExternalLinkage, 0,
627 "__CFConstantStringClassReference",
628 &getModule());
629 }
630
631 // Class pointer.
632 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
633 llvm::Constant *Zeros[] = { Zero, Zero };
634 llvm::Constant *C =
635 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
636 Fields.push_back(C);
637
638 // Flags.
639 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
640 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
641
642 // String pointer.
643 C = llvm::ConstantArray::get(str);
644 C = new llvm::GlobalVariable(C->getType(), true,
645 llvm::GlobalValue::InternalLinkage,
646 C, ".str", &getModule());
647
648 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
649 Fields.push_back(C);
650
651 // String length.
652 Ty = getTypes().ConvertType(getContext().LongTy);
653 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
654
655 // The struct.
656 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
657 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000658 llvm::GlobalVariable *GV =
659 new llvm::GlobalVariable(C->getType(), true,
660 llvm::GlobalVariable::InternalLinkage,
661 C, "", &getModule());
662 GV->setSection("__DATA,__cfstring");
663 Entry.setValue(GV);
664 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000665}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000666
Chris Lattnera6dcce32008-02-11 00:02:17 +0000667/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000668static llvm::Constant *GenerateStringLiteral(const std::string &str,
669 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000670 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000671 // Create Constant for this string literal
672 llvm::Constant *C=llvm::ConstantArray::get(str);
673
674 // Create a global variable for this string
675 C = new llvm::GlobalVariable(C->getType(), constant,
676 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000677 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000678 return C;
679}
680
Chris Lattnera6dcce32008-02-11 00:02:17 +0000681/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
682/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000683llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
684 // Don't share any string literals if writable-strings is turned on.
685 if (Features.WritableStrings)
686 return GenerateStringLiteral(str, false, *this);
687
688 llvm::StringMapEntry<llvm::Constant *> &Entry =
689 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
690
691 if (Entry.getValue())
692 return Entry.getValue();
693
694 // Create a global variable for this.
695 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
696 Entry.setValue(C);
697 return C;
698}