blob: 28c4c6b4b57b37ee20b83b1efd9335a189ac6ead [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
14// We might split this into multiple files if it gets too unwieldy
15
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
18#include "Mangle.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/StmtCXX.h"
25#include "llvm/ADT/StringExtras.h"
26using namespace clang;
27using namespace CodeGen;
28
29
30
31llvm::Value *CodeGenFunction::LoadCXXThis() {
32 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
33 "Must be in a C++ member function decl to load 'this'");
34 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
35 "Must be in a C++ member function decl to load 'this'");
36
37 // FIXME: What if we're inside a block?
38 // ans: See how CodeGenFunction::LoadObjCSelf() uses
39 // CodeGenFunction::BlockForwardSelf() for how to do this.
40 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
41}
42
43void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
44 EmitGlobal(GlobalDecl(D, Ctor_Complete));
45 EmitGlobal(GlobalDecl(D, Ctor_Base));
46}
47
48void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
49 CXXCtorType Type) {
50
51 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
52
53 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
54
55 SetFunctionDefinitionAttributes(D, Fn);
56 SetLLVMFunctionAttributesForDefinition(D, Fn);
57}
58
59llvm::Function *
60CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
61 CXXCtorType Type) {
62 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
63 const llvm::FunctionType *FTy =
64 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
65 FPT->isVariadic());
66
67 const char *Name = getMangledCXXCtorName(D, Type);
68 return cast<llvm::Function>(
69 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
70}
71
72const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
73 CXXCtorType Type) {
74 llvm::SmallString<256> Name;
75 getMangleContext().mangleCXXCtor(D, Type, Name);
76
77 Name += '\0';
78 return UniqueMangledName(Name.begin(), Name.end());
79}
80
81void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
82 if (D->isVirtual())
83 EmitGlobal(GlobalDecl(D, Dtor_Deleting));
84 EmitGlobal(GlobalDecl(D, Dtor_Complete));
85 EmitGlobal(GlobalDecl(D, Dtor_Base));
86}
87
88void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
89 CXXDtorType Type) {
90 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
91
92 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
93
94 SetFunctionDefinitionAttributes(D, Fn);
95 SetLLVMFunctionAttributesForDefinition(D, Fn);
96}
97
98llvm::Function *
99CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
100 CXXDtorType Type) {
101 const llvm::FunctionType *FTy =
102 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
103
104 const char *Name = getMangledCXXDtorName(D, Type);
105 return cast<llvm::Function>(
106 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
107}
108
109const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
110 CXXDtorType Type) {
111 llvm::SmallString<256> Name;
112 getMangleContext().mangleCXXDtor(D, Type, Name);
113
114 Name += '\0';
115 return UniqueMangledName(Name.begin(), Name.end());
116}
117
118llvm::Constant *
119CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
120 bool Extern,
121 const ThunkAdjustment &ThisAdjustment) {
122 return GenerateCovariantThunk(Fn, GD, Extern,
123 CovariantThunkAdjustment(ThisAdjustment,
124 ThunkAdjustment()));
125}
126
127llvm::Value *
128CodeGenFunction::DynamicTypeAdjust(llvm::Value *V,
129 const ThunkAdjustment &Adjustment) {
130 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
131
132 const llvm::Type *OrigTy = V->getType();
133 if (Adjustment.NonVirtual) {
134 // Do the non-virtual adjustment
135 V = Builder.CreateBitCast(V, Int8PtrTy);
136 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual);
137 V = Builder.CreateBitCast(V, OrigTy);
138 }
139
140 if (!Adjustment.Virtual)
141 return V;
142
143 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 &&
144 "vtable entry unaligned");
145
146 // Do the virtual this adjustment
147 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
148 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo();
149
150 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy);
151 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo());
152 V = Builder.CreateLoad(V, "vtable");
153
154 llvm::Value *VTablePtr = V;
155 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8);
156 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
157 V = Builder.CreateLoad(V);
158 V = Builder.CreateGEP(ThisVal, V);
159
160 return Builder.CreateBitCast(V, OrigTy);
161}
162
163llvm::Constant *
164CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
165 GlobalDecl GD, bool Extern,
166 const CovariantThunkAdjustment &Adjustment) {
167 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
168 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
169 QualType ResultType = FPT->getResultType();
170
171 FunctionArgList Args;
172 ImplicitParamDecl *ThisDecl =
173 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
174 MD->getThisType(getContext()));
175 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
176 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
177 e = MD->param_end();
178 i != e; ++i) {
179 ParmVarDecl *D = *i;
180 Args.push_back(std::make_pair(D, D->getType()));
181 }
182 IdentifierInfo *II
183 = &CGM.getContext().Idents.get("__thunk_named_foo_");
184 FunctionDecl *FD = FunctionDecl::Create(getContext(),
185 getContext().getTranslationUnitDecl(),
186 SourceLocation(), II, ResultType, 0,
187 Extern
188 ? FunctionDecl::Extern
189 : FunctionDecl::Static,
190 false, true);
191 StartFunction(FD, ResultType, Fn, Args, SourceLocation());
192
193 // generate body
194 const llvm::Type *Ty =
195 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
196 FPT->isVariadic());
197 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
198
199 CallArgList CallArgs;
200
201 bool ShouldAdjustReturnPointer = true;
202 QualType ArgType = MD->getThisType(getContext());
203 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this");
204 if (!Adjustment.ThisAdjustment.isEmpty()) {
205 // Do the this adjustment.
206 const llvm::Type *OrigTy = Callee->getType();
207 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment);
208
209 if (!Adjustment.ReturnAdjustment.isEmpty()) {
210 const CovariantThunkAdjustment &ReturnAdjustment =
211 CovariantThunkAdjustment(ThunkAdjustment(),
212 Adjustment.ReturnAdjustment);
213
214 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment);
215
216 Callee = Builder.CreateBitCast(Callee, OrigTy);
217 ShouldAdjustReturnPointer = false;
218 }
219 }
220
221 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType));
222
223 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
224 e = MD->param_end();
225 i != e; ++i) {
226 ParmVarDecl *D = *i;
227 QualType ArgType = D->getType();
228
229 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst);
230 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(),
231 SourceLocation());
232 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType));
233 }
234
235 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs,
236 FPT->getCallConv(),
237 FPT->getNoReturnAttr()),
238 Callee, ReturnValueSlot(), CallArgs, MD);
239 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) {
240 bool CanBeZero = !(ResultType->isReferenceType()
241 // FIXME: attr nonnull can't be zero either
242 /* || ResultType->hasAttr<NonNullAttr>() */ );
243 // Do the return result adjustment.
244 if (CanBeZero) {
245 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
246 llvm::BasicBlock *ZeroBlock = createBasicBlock();
247 llvm::BasicBlock *ContBlock = createBasicBlock();
248
249 const llvm::Type *Ty = RV.getScalarVal()->getType();
250 llvm::Value *Zero = llvm::Constant::getNullValue(Ty);
251 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero),
252 NonZeroBlock, ZeroBlock);
253 EmitBlock(NonZeroBlock);
254 llvm::Value *NZ =
255 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment);
256 EmitBranch(ContBlock);
257 EmitBlock(ZeroBlock);
258 llvm::Value *Z = RV.getScalarVal();
259 EmitBlock(ContBlock);
260 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty);
261 RVOrZero->reserveOperandSpace(2);
262 RVOrZero->addIncoming(NZ, NonZeroBlock);
263 RVOrZero->addIncoming(Z, ZeroBlock);
264 RV = RValue::get(RVOrZero);
265 } else
266 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(),
267 Adjustment.ReturnAdjustment));
268 }
269
270 if (!ResultType->isVoidType())
271 EmitReturnOfRValue(RV, ResultType);
272
273 FinishFunction();
274 return Fn;
275}
276
277llvm::Constant *
278CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
279 const ThunkAdjustment &ThisAdjustment) {
280 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
281
282 // Compute mangled name
283 llvm::SmallString<256> OutName;
284 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
285 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment,
286 OutName);
287 else
288 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
289 OutName += '\0';
290 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
291
292 // Get function for mangled name
293 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
294 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
295}
296
297llvm::Constant *
298CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD,
299 const CovariantThunkAdjustment &Adjustment) {
300 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
301
302 // Compute mangled name
303 llvm::SmallString<256> OutName;
304 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
305 OutName += '\0';
306 const char* Name = UniqueMangledName(OutName.begin(), OutName.end());
307
308 // Get function for mangled name
309 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
310 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
311}
312
313void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) {
314 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD);
315 if (!AdjPtr)
316 return;
317 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr;
318 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
319 for (unsigned i = 0; i < Adj.size(); i++) {
320 GlobalDecl OGD = Adj[i].first;
321 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl());
322 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType();
323 CanQualType oret = getContext().getCanonicalType(nc_oret);
324 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType();
325 CanQualType ret = getContext().getCanonicalType(nc_ret);
326 ThunkAdjustment ReturnAdjustment;
327 if (oret != ret) {
328 QualType qD = nc_ret->getPointeeType();
329 QualType qB = nc_oret->getPointeeType();
330 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl());
331 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl());
332 ReturnAdjustment = ComputeThunkAdjustment(D, B);
333 }
334 ThunkAdjustment ThisAdjustment = Adj[i].second;
335 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace();
336 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) {
337 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment);
338 llvm::Constant *FnConst;
339 if (!ReturnAdjustment.isEmpty())
340 FnConst = GetAddrOfCovariantThunk(GD, CoAdj);
341 else
342 FnConst = GetAddrOfThunk(GD, ThisAdjustment);
343 if (!isa<llvm::Function>(FnConst)) {
344 llvm::Constant *SubExpr =
345 cast<llvm::ConstantExpr>(FnConst)->getOperand(0);
346 llvm::Function *OldFn = cast<llvm::Function>(SubExpr);
347 std::string Name = OldFn->getNameStr();
348 GlobalDeclMap.erase(UniqueMangledName(Name.data(),
349 Name.data() + Name.size() + 1));
350 llvm::Constant *NewFnConst;
351 if (!ReturnAdjustment.isEmpty())
352 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj);
353 else
354 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment);
355 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst);
356 NewFn->takeName(OldFn);
357 llvm::Constant *NewPtrForOldDecl =
358 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType());
359 OldFn->replaceAllUsesWith(NewPtrForOldDecl);
360 OldFn->eraseFromParent();
361 FnConst = NewFn;
362 }
363 llvm::Function *Fn = cast<llvm::Function>(FnConst);
364 if (Fn->isDeclaration()) {
365 llvm::GlobalVariable::LinkageTypes linktype;
366 linktype = llvm::GlobalValue::WeakAnyLinkage;
367 if (!Extern)
368 linktype = llvm::GlobalValue::InternalLinkage;
369 Fn->setLinkage(linktype);
370 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
371 Fn->addFnAttr(llvm::Attribute::NoUnwind);
372 Fn->setAlignment(2);
373 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj);
374 }
375 }
376 }
377}
378
379llvm::Constant *
380CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern,
381 const ThunkAdjustment &ThisAdjustment) {
382 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
383 llvm::SmallString<256> OutName;
384 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) {
385 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment,
386 OutName);
387 } else
388 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName);
389
390 llvm::GlobalVariable::LinkageTypes linktype;
391 linktype = llvm::GlobalValue::WeakAnyLinkage;
392 if (!Extern)
393 linktype = llvm::GlobalValue::InternalLinkage;
394 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
395 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
396 const llvm::FunctionType *FTy =
397 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
398 FPT->isVariadic());
399
400 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
401 &getModule());
402 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment);
403 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
404 return m;
405}
406
407llvm::Constant *
408CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
409 const CovariantThunkAdjustment &Adjustment) {
410 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
411 llvm::SmallString<256> OutName;
412 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName);
413 llvm::GlobalVariable::LinkageTypes linktype;
414 linktype = llvm::GlobalValue::WeakAnyLinkage;
415 if (!Extern)
416 linktype = llvm::GlobalValue::InternalLinkage;
417 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
418 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
419 const llvm::FunctionType *FTy =
420 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
421 FPT->isVariadic());
422
423 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(),
424 &getModule());
425 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment);
426 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
427 return m;
428}
429
430static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex,
431 llvm::Value *This, const llvm::Type *Ty) {
432 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
433
434 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty);
435 Vtable = CGF.Builder.CreateLoad(Vtable);
436
437 llvm::Value *VFuncPtr =
438 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn");
439 return CGF.Builder.CreateLoad(VFuncPtr);
440}
441
442llvm::Value *
443CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
444 const llvm::Type *Ty) {
445 MD = MD->getCanonicalDecl();
446 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD);
447
448 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
449}
450
451llvm::Value *
452CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
453 llvm::Value *&This, const llvm::Type *Ty) {
454 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
455 uint64_t VtableIndex =
456 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type));
457
458 return ::BuildVirtualCall(*this, VtableIndex, This, Ty);
459}