blob: ec61d667eed035adc36dc8c73028e7ad326bb728 [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),
Chris Lattnercbfb5512008-03-01 08:45:05 +000038 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
39 //TODO: Make this selectable at runtime
Chris Lattnerb326b172008-03-30 23:03:07 +000040 Runtime = CreateObjCRuntime(M,
41 getTypes().ConvertType(getContext().IntTy),
42 getTypes().ConvertType(getContext().LongTy));
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000043
44 // If debug info generation is enabled, create the CGDebugInfo object.
45 if (GenerateDebugInfo)
46 DebugInfo = new CGDebugInfo(this);
47 else
48 DebugInfo = NULL;
Chris Lattnercbfb5512008-03-01 08:45:05 +000049}
50
51CodeGenModule::~CodeGenModule() {
Chris Lattnerb326b172008-03-30 23:03:07 +000052 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000053 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000054 AddGlobalCtor(ObjCInitFunction);
Nate Begemanad320b62008-04-20 06:29:50 +000055 EmitStatics();
Chris Lattner753d2592008-03-14 17:18:18 +000056 EmitGlobalCtors();
Nate Begeman52da5c72008-04-18 23:43:57 +000057 EmitAnnotations();
Chris Lattnercbfb5512008-03-01 08:45:05 +000058 delete Runtime;
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000059 delete DebugInfo;
Chris Lattnerb033c4a2008-04-30 16:05:42 +000060 // Run the verifier to check that the generated code is consistent.
61 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000062}
Chris Lattner4b009652007-07-25 00:24:17 +000063
Chris Lattnercf9c9d02007-12-02 07:19:18 +000064/// WarnUnsupported - Print out a warning that codegen doesn't support the
65/// specified stmt yet.
66void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
67 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
68 "cannot codegen this %0 yet");
69 SourceRange Range = S->getSourceRange();
70 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000071 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000072 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000073}
Chris Lattner0e4755d2007-12-02 06:27:33 +000074
Chris Lattner806a5f52008-01-12 07:05:38 +000075/// WarnUnsupported - Print out a warning that codegen doesn't support the
76/// specified decl yet.
77void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
78 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
79 "cannot codegen this %0 yet");
80 std::string Msg = Type;
81 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
82 &Msg, 1);
83}
84
Dan Gohman4751a3a2008-05-22 00:50:06 +000085/// setVisibility - Set the visibility for the given LLVM GlobalValue
86/// according to the given clang AST visibility value.
87void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
88 VisibilityAttr::VisibilityTypes Vis) {
89 switch (Vis) {
90 default: assert(0 && "Unknown visibility!");
91 case VisibilityAttr::DefaultVisibility:
92 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
93 break;
94 case VisibilityAttr::HiddenVisibility:
95 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
96 break;
97 case VisibilityAttr::ProtectedVisibility:
98 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
99 break;
100 }
101}
102
Chris Lattner753d2592008-03-14 17:18:18 +0000103/// AddGlobalCtor - Add a function to the list that will be called before
104/// main() runs.
105void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
106 // TODO: Type coercion of void()* types.
107 GlobalCtors.push_back(Ctor);
108}
109
Chris Lattnerb326b172008-03-30 23:03:07 +0000110/// EmitGlobalCtors - Generates the array of contsturctor functions to be
111/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner753d2592008-03-14 17:18:18 +0000112void CodeGenModule::EmitGlobalCtors() {
Chris Lattnerb326b172008-03-30 23:03:07 +0000113 if (GlobalCtors.empty()) return;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000114
Chris Lattner753d2592008-03-14 17:18:18 +0000115 // Get the type of @llvm.global_ctors
116 std::vector<const llvm::Type*> CtorFields;
117 CtorFields.push_back(llvm::IntegerType::get(32));
118 // Constructor function type
119 std::vector<const llvm::Type*> VoidArgs;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000120 llvm::FunctionType* CtorFuncTy =
121 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
122
Chris Lattner753d2592008-03-14 17:18:18 +0000123 // i32, function type pair
Chris Lattnera18c12e2008-03-19 05:24:56 +0000124 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
125 llvm::StructType* CtorStructTy =
126 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000127 // Array of fields
Chris Lattnera18c12e2008-03-19 05:24:56 +0000128 llvm::ArrayType* GlobalCtorsTy =
129 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner753d2592008-03-14 17:18:18 +0000130
Chris Lattner753d2592008-03-14 17:18:18 +0000131 // Define the global variable
Chris Lattnera18c12e2008-03-19 05:24:56 +0000132 llvm::GlobalVariable *GlobalCtorsVal =
133 new llvm::GlobalVariable(GlobalCtorsTy, false,
134 llvm::GlobalValue::AppendingLinkage,
135 (llvm::Constant*)0, "llvm.global_ctors",
136 &TheModule);
Chris Lattner753d2592008-03-14 17:18:18 +0000137
138 // Populate the array
139 std::vector<llvm::Constant*> CtorValues;
Chris Lattnera18c12e2008-03-19 05:24:56 +0000140 llvm::Constant *MagicNumber =
141 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
142 std::vector<llvm::Constant*> StructValues;
Chris Lattner753d2592008-03-14 17:18:18 +0000143 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattnera18c12e2008-03-19 05:24:56 +0000144 E = GlobalCtors.end(); I != E; ++I) {
145 StructValues.clear();
Chris Lattner753d2592008-03-14 17:18:18 +0000146 StructValues.push_back(MagicNumber);
147 StructValues.push_back(*I);
148
Chris Lattnera18c12e2008-03-19 05:24:56 +0000149 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000150 }
Chris Lattnera18c12e2008-03-19 05:24:56 +0000151
152 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
153 CtorValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000154}
155
Chris Lattnerb326b172008-03-30 23:03:07 +0000156
157
Nate Begeman52da5c72008-04-18 23:43:57 +0000158void CodeGenModule::EmitAnnotations() {
159 if (Annotations.empty())
160 return;
161
162 // Create a new global variable for the ConstantStruct in the Module.
163 llvm::Constant *Array =
164 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
165 Annotations.size()),
166 Annotations);
167 llvm::GlobalValue *gv =
168 new llvm::GlobalVariable(Array->getType(), false,
169 llvm::GlobalValue::AppendingLinkage, Array,
170 "llvm.global.annotations", &TheModule);
171 gv->setSection("llvm.metadata");
172}
173
Chris Lattner0e4755d2007-12-02 06:27:33 +0000174/// ReplaceMapValuesWith - This is a really slow and bad function that
175/// searches for any entries in GlobalDeclMap that point to OldVal, changing
176/// them to point to NewVal. This is badbadbad, FIXME!
177void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
178 llvm::Constant *NewVal) {
179 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
180 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
181 if (I->second == OldVal) I->second = NewVal;
182}
183
184
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000185llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
186 bool isDefinition) {
187 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +0000188 llvm::Constant *&Entry = GlobalDeclMap[D];
Eli Friedman725d2be2008-05-20 09:21:07 +0000189#if 0
190 // FIXME: The cache is currently broken!
Chris Lattner4b009652007-07-25 00:24:17 +0000191 if (Entry) return Entry;
Eli Friedman725d2be2008-05-20 09:21:07 +0000192#endif
193
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000194 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
195
196 // Check to see if the function already exists.
197 llvm::Function *F = getModule().getFunction(D->getName());
198 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
199
200 // If it doesn't already exist, just create and return an entry.
201 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000202 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000203 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
204 D->getName(), &getModule());
Nate Begemandc6262e2008-03-09 03:09:36 +0000205
206 // Set the appropriate calling convention for the Function.
207 if (D->getAttr<FastCallAttr>())
208 F->setCallingConv(llvm::CallingConv::Fast);
209 return Entry = F;
Chris Lattner4b009652007-07-25 00:24:17 +0000210 }
211
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000212 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000213 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000214 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +0000215
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000216 // If this isn't a definition, just return it casted to the right type.
217 if (!isDefinition)
218 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
219
220 // Otherwise, we have a definition after a prototype with the wrong type.
221 // F is the Function* for the one with the wrong type, we must make a new
222 // Function* and update everything that used F (a declaration) with the new
223 // Function* (which will be a definition).
224 //
225 // This happens if there is a prototype for a function (e.g. "int f()") and
226 // then a definition of a different type (e.g. "int f(int x)"). Start by
227 // making a new function of the correct type, RAUW, then steal the name.
Gabor Greif815e2c12008-04-06 20:42:52 +0000228 llvm::Function *NewFn = llvm::Function::Create(FTy,
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000229 llvm::Function::ExternalLinkage,
230 "", &getModule());
231 NewFn->takeName(F);
232
233 // Replace uses of F with the Function we will endow with a body.
234 llvm::Constant *NewPtrForOldDecl =
235 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
236 F->replaceAllUsesWith(NewPtrForOldDecl);
237
238 // FIXME: Update the globaldeclmap for the previous decl of this name. We
239 // really want a way to walk all of these, but we don't have it yet. This
240 // is incredibly slow!
241 ReplaceMapValuesWith(F, NewPtrForOldDecl);
242
243 // Ok, delete the old function now, which is dead.
244 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
245 F->eraseFromParent();
246
247 // Return the new function which has the right type.
248 return Entry = NewFn;
249}
250
Chris Lattner0db06992008-02-05 06:37:34 +0000251static bool IsZeroElementArray(const llvm::Type *Ty) {
252 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
253 return ATy->getNumElements() == 0;
254 return false;
255}
256
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000257llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
258 bool isDefinition) {
259 assert(D->hasGlobalStorage() && "Not a global variable");
260
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000261 // See if it is already in the map.
262 llvm::Constant *&Entry = GlobalDeclMap[D];
263 if (Entry) return Entry;
264
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000265 QualType ASTTy = D->getType();
266 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000267
268 // Check to see if the global already exists.
Chris Lattnered430e92008-02-02 04:43:11 +0000269 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000270
271 // If it doesn't already exist, just create and return an entry.
272 if (GV == 0) {
273 return Entry = new llvm::GlobalVariable(Ty, false,
274 llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000275 0, D->getName(), &getModule(), 0,
276 ASTTy.getAddressSpace());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000277 }
278
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000279 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000280 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000281 if (PTy == GV->getType()) return Entry = GV;
282
283 // If this isn't a definition, just return it casted to the right type.
284 if (!isDefinition)
285 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
286
287
288 // Otherwise, we have a definition after a prototype with the wrong type.
289 // GV is the GlobalVariable* for the one with the wrong type, we must make a
290 /// new GlobalVariable* and update everything that used GV (a declaration)
291 // with the new GlobalVariable* (which will be a definition).
292 //
293 // This happens if there is a prototype for a global (e.g. "extern int x[];")
294 // and then a definition of a different type (e.g. "int x[10];"). Start by
295 // making a new global of the correct type, RAUW, then steal the name.
296 llvm::GlobalVariable *NewGV =
297 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000298 0, D->getName(), &getModule(), 0,
299 ASTTy.getAddressSpace());
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000300 NewGV->takeName(GV);
301
302 // Replace uses of GV with the globalvalue we will endow with a body.
303 llvm::Constant *NewPtrForOldDecl =
304 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
305 GV->replaceAllUsesWith(NewPtrForOldDecl);
306
307 // FIXME: Update the globaldeclmap for the previous decl of this name. We
308 // really want a way to walk all of these, but we don't have it yet. This
309 // is incredibly slow!
310 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
311
Chris Lattner0db06992008-02-05 06:37:34 +0000312 // Verify that GV was a declaration or something like x[] which turns into
313 // [0 x type].
314 assert((GV->isDeclaration() ||
315 IsZeroElementArray(GV->getType()->getElementType())) &&
316 "Shouldn't replace non-declaration");
317
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000318 // Ok, delete the old global now, which is dead.
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000319 GV->eraseFromParent();
320
321 // Return the new global which has the right type.
322 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000323}
324
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000325
Chris Lattnerb326b172008-03-30 23:03:07 +0000326void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
327 // If this is not a prototype, emit the body.
328 if (OMD->getBody())
329 CodeGenFunction(*this).GenerateObjCMethod(OMD);
330}
331
Chris Lattner4b009652007-07-25 00:24:17 +0000332void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
333 // If this is not a prototype, emit the body.
Chris Lattner74bf5552008-05-04 02:29:49 +0000334 if (!FD->isThisDeclarationADefinition())
335 return;
336
337 // If the function is a static, defer code generation until later so we can
338 // easily omit unused statics.
339 if (FD->getStorageClass() != FunctionDecl::Static) {
Chris Lattner4b009652007-07-25 00:24:17 +0000340 CodeGenFunction(*this).GenerateCode(FD);
Chris Lattner74bf5552008-05-04 02:29:49 +0000341 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000342 }
Chris Lattner74bf5552008-05-04 02:29:49 +0000343
344 // We need to check the Module here to see if GetAddrOfFunctionDecl() has
345 // already added this function to the Module because the address of the
346 // function's prototype was taken. If this is the case, call
347 // GetAddrOfFunctionDecl to insert the static FunctionDecl into the used
348 // GlobalDeclsMap, so that EmitStatics will generate code for it later.
349 //
350 // Example:
351 // static int foo();
352 // int bar() { return foo(); }
353 // static int foo() { return 5; }
354 if (getModule().getFunction(FD->getName()))
355 GetAddrOfFunctionDecl(FD, true);
356
357 StaticDecls.push_back(FD);
Nate Begemanad320b62008-04-20 06:29:50 +0000358}
359
360void CodeGenModule::EmitStatics() {
361 // Emit code for each used static decl encountered. Since a previously unused
362 // static decl may become used during the generation of code for a static
363 // function, iterate until no changes are made.
364 bool Changed;
365 do {
366 Changed = false;
367 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
368 // Check the map of used decls for our static. If not found, continue.
369 const Decl *D = StaticDecls[i];
Nate Begeman91f52012008-04-20 20:38:08 +0000370 if (!GlobalDeclMap.count(D))
Nate Begemanad320b62008-04-20 06:29:50 +0000371 continue;
372
373 // If this is a function decl, generate code for the static function if it
374 // has a body. Otherwise, we must have a var decl for a static global
375 // variable.
376 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
377 if (FD->getBody())
378 CodeGenFunction(*this).GenerateCode(FD);
379 } else {
Nate Begeman91f52012008-04-20 20:38:08 +0000380 EmitGlobalVarInit(cast<VarDecl>(D));
Nate Begemanad320b62008-04-20 06:29:50 +0000381 }
382 // Erase the used decl from the list.
383 StaticDecls[i] = StaticDecls.back();
384 StaticDecls.pop_back();
385 --i;
386 --e;
387
388 // Remember that we made a change.
389 Changed = true;
390 }
391 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000392}
393
Anders Carlssond76cead2008-01-26 01:36:00 +0000394llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
395 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000396}
397
Nate Begeman8a704172008-04-19 04:17:09 +0000398/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
399/// annotation information for a given GlobalValue. The annotation struct is
400/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
401/// GlobalValue being annotated. The second filed is thee constant string
402/// created from the AnnotateAttr's annotation. The third field is a constant
403/// string containing the name of the translation unit. The fourth field is
404/// the line number in the file of the annotated value declaration.
405///
406/// FIXME: this does not unique the annotation string constants, as llvm-gcc
407/// appears to.
408///
409llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
410 const AnnotateAttr *AA,
411 unsigned LineNo) {
412 llvm::Module *M = &getModule();
413
414 // get [N x i8] constants for the annotation string, and the filename string
415 // which are the 2nd and 3rd elements of the global annotation structure.
416 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
417 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
418 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
419 true);
420
421 // Get the two global values corresponding to the ConstantArrays we just
422 // created to hold the bytes of the strings.
423 llvm::GlobalValue *annoGV =
424 new llvm::GlobalVariable(anno->getType(), false,
425 llvm::GlobalValue::InternalLinkage, anno,
426 GV->getName() + ".str", M);
427 // translation unit name string, emitted into the llvm.metadata section.
428 llvm::GlobalValue *unitGV =
429 new llvm::GlobalVariable(unit->getType(), false,
430 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
431
432 // Create the ConstantStruct that is the global annotion.
433 llvm::Constant *Fields[4] = {
434 llvm::ConstantExpr::getBitCast(GV, SBP),
435 llvm::ConstantExpr::getBitCast(annoGV, SBP),
436 llvm::ConstantExpr::getBitCast(unitGV, SBP),
437 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
438 };
439 return llvm::ConstantStruct::get(Fields, 4, false);
440}
441
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000442void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
Nate Begemanad320b62008-04-20 06:29:50 +0000443 // If the VarDecl is a static, defer code generation until later so we can
444 // easily omit unused statics.
445 if (D->getStorageClass() == VarDecl::Static) {
446 StaticDecls.push_back(D);
447 return;
448 }
449
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000450 // If this is just a forward declaration of the variable, don't emit it now,
451 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000452 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
453 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000454
Nate Begemanad320b62008-04-20 06:29:50 +0000455 EmitGlobalVarInit(D);
456}
457
458void CodeGenModule::EmitGlobalVarInit(const VarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000459 // Get the global, forcing it to be a direct reference.
460 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000461 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000462
463 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000464 llvm::Constant *Init = 0;
465 if (D->getInit() == 0) {
466 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
467 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000468 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner8cd0e932008-03-05 18:54:05 +0000469 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner4b009652007-07-25 00:24:17 +0000470 if (D->getInit()->isIntegerConstantExpr(Value, Context))
471 Init = llvm::ConstantInt::get(Value);
472 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000473
Devang Patel08a10cc2007-10-30 21:27:20 +0000474 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000475 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000476
Nate Begeman8a704172008-04-19 04:17:09 +0000477 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
478 SourceManager &SM = Context.getSourceManager();
479 AddAnnotation(EmitAnnotateAttr(GV, AA,
480 SM.getLogicalLineNumber(D->getLocation())));
481 }
482
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000483 assert(GV->getType()->getElementType() == Init->getType() &&
484 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000485 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000486
487 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000488 setVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000489 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000490
491 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000492 if (D->getStorageClass() == VarDecl::Static)
493 GV->setLinkage(llvm::Function::InternalLinkage);
494 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000495 GV->setLinkage(llvm::Function::DLLImportLinkage);
496 else if (D->getAttr<DLLExportAttr>())
497 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000498 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000499 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000500 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000501 // FIXME: This isn't right. This should handle common linkage and other
502 // stuff.
503 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000504 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000505 case VarDecl::Auto:
506 case VarDecl::Register:
507 assert(0 && "Can't have auto or register globals");
508 case VarDecl::None:
509 if (!D->getInit())
510 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
511 break;
512 case VarDecl::Extern:
513 case VarDecl::PrivateExtern:
514 // todo: common
515 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000516 }
Chris Lattner4b009652007-07-25 00:24:17 +0000517 }
518}
519
520/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
521/// declarator chain.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000522void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
523 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
524 if (D->isFileVarDecl())
525 EmitGlobalVar(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000526}
527
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000528void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
529 // Make sure that this type is translated.
530 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000531}
532
533
Chris Lattnerab862cc2007-08-31 04:31:45 +0000534/// getBuiltinLibFunction
535llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000536 if (BuiltinID > BuiltinFunctions.size())
537 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000538
Chris Lattner9f2d6892007-12-13 00:38:03 +0000539 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
540 // a slot for it.
541 assert(BuiltinID && "Invalid Builtin ID");
542 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000543 if (FunctionSlot)
544 return FunctionSlot;
545
546 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
547
548 // Get the name, skip over the __builtin_ prefix.
549 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
550
551 // Get the type for the builtin.
552 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
553 const llvm::FunctionType *Ty =
554 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
555
556 // FIXME: This has a serious problem with code like this:
557 // void abs() {}
558 // ... __builtin_abs(x);
559 // The two versions of abs will collide. The fix is for the builtin to win,
560 // and for the existing one to be turned into a constantexpr cast of the
561 // builtin. In the case where the existing one is a static function, it
562 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000563 if (llvm::Function *Existing = getModule().getFunction(Name)) {
564 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
565 return FunctionSlot = Existing;
566 assert(Existing == 0 && "FIXME: Name collision");
567 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000568
569 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000570 return FunctionSlot =
571 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
572 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000573}
574
Chris Lattner4b23f942007-12-18 00:25:38 +0000575llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
576 unsigned NumTys) {
577 return llvm::Intrinsic::getDeclaration(&getModule(),
578 (llvm::Intrinsic::ID)IID, Tys, NumTys);
579}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000580
Chris Lattner4b009652007-07-25 00:24:17 +0000581llvm::Function *CodeGenModule::getMemCpyFn() {
582 if (MemCpyFn) return MemCpyFn;
583 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000584 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000585 default: assert(0 && "Unknown ptr width");
586 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
587 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
588 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000589 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000590}
Anders Carlsson36a04872007-08-21 00:21:21 +0000591
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000592llvm::Function *CodeGenModule::getMemSetFn() {
593 if (MemSetFn) return MemSetFn;
594 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000595 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000596 default: assert(0 && "Unknown ptr width");
597 case 32: IID = llvm::Intrinsic::memset_i32; break;
598 case 64: IID = llvm::Intrinsic::memset_i64; break;
599 }
600 return MemSetFn = getIntrinsic(IID);
601}
Chris Lattner4b23f942007-12-18 00:25:38 +0000602
Chris Lattnerab862cc2007-08-31 04:31:45 +0000603llvm::Constant *CodeGenModule::
604GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000605 llvm::StringMapEntry<llvm::Constant *> &Entry =
606 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
607
608 if (Entry.getValue())
609 return Entry.getValue();
610
611 std::vector<llvm::Constant*> Fields;
612
613 if (!CFConstantStringClassRef) {
614 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
615 Ty = llvm::ArrayType::get(Ty, 0);
616
617 CFConstantStringClassRef =
618 new llvm::GlobalVariable(Ty, false,
619 llvm::GlobalVariable::ExternalLinkage, 0,
620 "__CFConstantStringClassReference",
621 &getModule());
622 }
623
624 // Class pointer.
625 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
626 llvm::Constant *Zeros[] = { Zero, Zero };
627 llvm::Constant *C =
628 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
629 Fields.push_back(C);
630
631 // Flags.
632 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
633 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
634
635 // String pointer.
636 C = llvm::ConstantArray::get(str);
637 C = new llvm::GlobalVariable(C->getType(), true,
638 llvm::GlobalValue::InternalLinkage,
639 C, ".str", &getModule());
640
641 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
642 Fields.push_back(C);
643
644 // String length.
645 Ty = getTypes().ConvertType(getContext().LongTy);
646 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
647
648 // The struct.
649 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
650 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000651 llvm::GlobalVariable *GV =
652 new llvm::GlobalVariable(C->getType(), true,
653 llvm::GlobalVariable::InternalLinkage,
654 C, "", &getModule());
655 GV->setSection("__DATA,__cfstring");
656 Entry.setValue(GV);
657 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000658}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000659
Chris Lattnera6dcce32008-02-11 00:02:17 +0000660/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000661static llvm::Constant *GenerateStringLiteral(const std::string &str,
662 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000663 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000664 // Create Constant for this string literal
665 llvm::Constant *C=llvm::ConstantArray::get(str);
666
667 // Create a global variable for this string
668 C = new llvm::GlobalVariable(C->getType(), constant,
669 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000670 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000671 return C;
672}
673
Chris Lattnera6dcce32008-02-11 00:02:17 +0000674/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
675/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000676llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
677 // Don't share any string literals if writable-strings is turned on.
678 if (Features.WritableStrings)
679 return GenerateStringLiteral(str, false, *this);
680
681 llvm::StringMapEntry<llvm::Constant *> &Entry =
682 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
683
684 if (Entry.getValue())
685 return Entry.getValue();
686
687 // Create a global variable for this.
688 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
689 Entry.setValue(C);
690 return C;
691}