blob: 793a22050677c195ad4052c5fba5d2ab99239dad [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 to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/CodeGen/CodeGenOptions.h"
24#include "llvm/GlobalVariable.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Type.h"
28using namespace clang;
29using namespace CodeGen;
30
31
32void CodeGenFunction::EmitDecl(const Decl &D) {
33 switch (D.getKind()) {
34 default:
35 CGM.ErrorUnsupported(&D, "decl");
36 return;
37 case Decl::ParmVar:
38 assert(0 && "Parmdecls should not be in declstmts!");
39 case Decl::Function: // void X();
40 case Decl::Record: // struct/union/class X;
41 case Decl::Enum: // enum X;
42 case Decl::EnumConstant: // enum ? { X = ? }
43 case Decl::CXXRecord: // struct/union/class X; [C++]
44 case Decl::Using: // using X; [C++]
45 case Decl::UsingShadow:
46 case Decl::UsingDirective: // using namespace X; [C++]
47 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
48 // None of these decls require codegen support.
49 return;
50
51 case Decl::Var: {
52 const VarDecl &VD = cast<VarDecl>(D);
53 assert(VD.isBlockVarDecl() &&
54 "Should not see file-scope variables inside a function!");
55 return EmitBlockVarDecl(VD);
56 }
57
58 case Decl::Typedef: { // typedef int X;
59 const TypedefDecl &TD = cast<TypedefDecl>(D);
60 QualType Ty = TD.getUnderlyingType();
61
62 if (Ty->isVariablyModifiedType())
63 EmitVLASize(Ty);
64 }
65 }
66}
67
68/// EmitBlockVarDecl - This method handles emission of any variable declaration
69/// inside a function, including static vars etc.
70void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) {
71 if (D.hasAttr<AsmLabelAttr>())
72 CGM.ErrorUnsupported(&D, "__asm__");
73
74 switch (D.getStorageClass()) {
75 case VarDecl::None:
76 case VarDecl::Auto:
77 case VarDecl::Register:
78 return EmitLocalBlockVarDecl(D);
79 case VarDecl::Static: {
80 llvm::GlobalValue::LinkageTypes Linkage =
81 llvm::GlobalValue::InternalLinkage;
82
83 // If this is a static declaration inside an inline function, it must have
84 // weak linkage so that the linker will merge multiple definitions of it.
85 if (getContext().getLangOptions().CPlusPlus) {
86 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) {
87 if (FD->isInlined())
88 Linkage = llvm::GlobalValue::WeakAnyLinkage;
89 }
90 }
91
92 return EmitStaticBlockVarDecl(D, Linkage);
93 }
94 case VarDecl::Extern:
95 case VarDecl::PrivateExtern:
96 // Don't emit it now, allow it to be emitted lazily on its first use.
97 return;
98 }
99
100 assert(0 && "Unknown storage class");
101}
102
103static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
104 const char *Separator) {
105 CodeGenModule &CGM = CGF.CGM;
106 if (CGF.getContext().getLangOptions().CPlusPlus)
107 return CGM.getMangledName(&D);
108
109 std::string ContextName;
110 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl))
111 ContextName = CGM.getMangledName(FD);
112 else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
113 ContextName = CGF.CurFn->getName();
114 else
115 // FIXME: What about in a block??
116 assert(0 && "Unknown context for block var decl");
117
118 return ContextName + Separator + D.getNameAsString();
119}
120
121llvm::GlobalVariable *
122CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D,
123 const char *Separator,
124 llvm::GlobalValue::LinkageTypes Linkage) {
125 QualType Ty = D.getType();
126 assert(Ty->isConstantSizeType() && "VLAs can't be static");
127
128 std::string Name = GetStaticDeclName(*this, D, Separator);
129
130 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
131 llvm::GlobalVariable *GV =
132 new llvm::GlobalVariable(CGM.getModule(), LTy,
133 Ty.isConstant(getContext()), Linkage,
134 CGM.EmitNullConstant(D.getType()), Name, 0,
135 D.isThreadSpecified(), Ty.getAddressSpace());
136 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
137 return GV;
138}
139
140/// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
141/// global variable that has already been created for it. If the initializer
142/// has a different type than GV does, this may free GV and return a different
143/// one. Otherwise it just returns GV.
144llvm::GlobalVariable *
145CodeGenFunction::AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
146 llvm::GlobalVariable *GV) {
147 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
148
149 // If constant emission failed, then this should be a C++ static
150 // initializer.
151 if (!Init) {
152 if (!getContext().getLangOptions().CPlusPlus)
153 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
154 else {
155 // Since we have a static initializer, this global variable can't
156 // be constant.
157 GV->setConstant(false);
158
159 EmitStaticCXXBlockVarDeclInit(D, GV);
160 }
161 return GV;
162 }
163
164 // The initializer may differ in type from the global. Rewrite
165 // the global to match the initializer. (We have to do this
166 // because some types, like unions, can't be completely represented
167 // in the LLVM type system.)
168 if (GV->getType() != Init->getType()) {
169 llvm::GlobalVariable *OldGV = GV;
170
171 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
172 OldGV->isConstant(),
173 OldGV->getLinkage(), Init, "",
174 0, D.isThreadSpecified(),
175 D.getType().getAddressSpace());
176
177 // Steal the name of the old global
178 GV->takeName(OldGV);
179
180 // Replace all uses of the old global with the new global
181 llvm::Constant *NewPtrForOldDecl =
182 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
183 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
184
185 // Erase the old global, since it is no longer used.
186 OldGV->eraseFromParent();
187 }
188
189 GV->setInitializer(Init);
190 return GV;
191}
192
193void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D,
194 llvm::GlobalValue::LinkageTypes Linkage) {
195 llvm::Value *&DMEntry = LocalDeclMap[&D];
196 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
197
198 llvm::GlobalVariable *GV = CreateStaticBlockVarDecl(D, ".", Linkage);
199
200 // Store into LocalDeclMap before generating initializer to handle
201 // circular references.
202 DMEntry = GV;
203
204 // Make sure to evaluate VLA bounds now so that we have them for later.
205 //
206 // FIXME: Can this happen?
207 if (D.getType()->isVariablyModifiedType())
208 EmitVLASize(D.getType());
209
210 // If this value has an initializer, emit it.
211 if (D.getInit())
212 GV = AddInitializerToGlobalBlockVarDecl(D, GV);
213
214 // FIXME: Merge attribute handling.
215 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
216 SourceManager &SM = CGM.getContext().getSourceManager();
217 llvm::Constant *Ann =
218 CGM.EmitAnnotateAttr(GV, AA,
219 SM.getInstantiationLineNumber(D.getLocation()));
220 CGM.AddAnnotation(Ann);
221 }
222
223 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
224 GV->setSection(SA->getName());
225
226 if (D.hasAttr<UsedAttr>())
227 CGM.AddUsedGlobal(GV);
228
229 // We may have to cast the constant because of the initializer
230 // mismatch above.
231 //
232 // FIXME: It is really dangerous to store this in the map; if anyone
233 // RAUW's the GV uses of this constant will be invalid.
234 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
235 const llvm::Type *LPtrTy =
236 llvm::PointerType::get(LTy, D.getType().getAddressSpace());
237 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
238
239 // Emit global variable debug descriptor for static vars.
240 CGDebugInfo *DI = getDebugInfo();
241 if (DI) {
242 DI->setLocation(D.getLocation());
243 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
244 }
245}
246
247unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
248 assert(ByRefValueInfo.count(VD) && "Did not find value!");
249
250 return ByRefValueInfo.find(VD)->second.second;
251}
252
253/// BuildByRefType - This routine changes a __block variable declared as T x
254/// into:
255///
256/// struct {
257/// void *__isa;
258/// void *__forwarding;
259/// int32_t __flags;
260/// int32_t __size;
261/// void *__copy_helper; // only if needed
262/// void *__destroy_helper; // only if needed
263/// char padding[X]; // only if needed
264/// T x;
265/// } x
266///
267const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) {
268 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
269 if (Info.first)
270 return Info.first;
271
272 QualType Ty = D->getType();
273
274 std::vector<const llvm::Type *> Types;
275
276 const llvm::PointerType *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
277
278 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(VMContext);
279
280 // void *__isa;
281 Types.push_back(Int8PtrTy);
282
283 // void *__forwarding;
284 Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
285
286 // int32_t __flags;
287 Types.push_back(llvm::Type::getInt32Ty(VMContext));
288
289 // int32_t __size;
290 Types.push_back(llvm::Type::getInt32Ty(VMContext));
291
292 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
293 if (HasCopyAndDispose) {
294 /// void *__copy_helper;
295 Types.push_back(Int8PtrTy);
296
297 /// void *__destroy_helper;
298 Types.push_back(Int8PtrTy);
299 }
300
301 bool Packed = false;
302 CharUnits Align = getContext().getDeclAlign(D);
303 if (Align > CharUnits::fromQuantity(Target.getPointerAlign(0) / 8)) {
304 // We have to insert padding.
305
306 // The struct above has 2 32-bit integers.
307 unsigned CurrentOffsetInBytes = 4 * 2;
308
309 // And either 2 or 4 pointers.
310 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
311 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
312
313 // Align the offset.
314 unsigned AlignedOffsetInBytes =
315 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
316
317 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
318 if (NumPaddingBytes > 0) {
319 const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
320 // FIXME: We need a sema error for alignment larger than the minimum of
321 // the maximal stack alignmint and the alignment of malloc on the system.
322 if (NumPaddingBytes > 1)
323 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
324
325 Types.push_back(Ty);
326
327 // We want a packed struct.
328 Packed = true;
329 }
330 }
331
332 // T x;
333 Types.push_back(ConvertType(Ty));
334
335 const llvm::Type *T = llvm::StructType::get(VMContext, Types, Packed);
336
337 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
338 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
339 ByRefTypeHolder.get());
340
341 Info.first = ByRefTypeHolder.get();
342
343 Info.second = Types.size() - 1;
344
345 return Info.first;
346}
347
348/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
349/// variable declaration with auto, register, or no storage class specifier.
350/// These turn into simple stack objects, or GlobalValues depending on target.
351void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
352 QualType Ty = D.getType();
353 bool isByRef = D.hasAttr<BlocksAttr>();
354 bool needsDispose = false;
355 CharUnits Align = CharUnits::Zero();
356 bool IsSimpleConstantInitializer = false;
357
358 llvm::Value *DeclPtr;
359 if (Ty->isConstantSizeType()) {
360 if (!Target.useGlobalsForAutomaticVariables()) {
361
362 // If this value is an array or struct, is POD, and if the initializer is
363 // a staticly determinable constant, try to optimize it.
364 if (D.getInit() && !isByRef &&
365 (Ty->isArrayType() || Ty->isRecordType()) &&
366 Ty->isPODType() &&
367 D.getInit()->isConstantInitializer(getContext())) {
368 // If this variable is marked 'const', emit the value as a global.
369 if (CGM.getCodeGenOpts().MergeAllConstants &&
370 Ty.isConstant(getContext())) {
371 EmitStaticBlockVarDecl(D, llvm::GlobalValue::InternalLinkage);
372 return;
373 }
374
375 IsSimpleConstantInitializer = true;
376 }
377
378 // A normal fixed sized variable becomes an alloca in the entry block.
379 const llvm::Type *LTy = ConvertTypeForMem(Ty);
380 if (isByRef)
381 LTy = BuildByRefType(&D);
382 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
383 Alloc->setName(D.getNameAsString());
384
385 Align = getContext().getDeclAlign(&D);
386 if (isByRef)
387 Align = std::max(Align,
388 CharUnits::fromQuantity(Target.getPointerAlign(0) / 8));
389 Alloc->setAlignment(Align.getQuantity());
390 DeclPtr = Alloc;
391 } else {
392 // Targets that don't support recursion emit locals as globals.
393 const char *Class =
394 D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
395 DeclPtr = CreateStaticBlockVarDecl(D, Class,
396 llvm::GlobalValue
397 ::InternalLinkage);
398 }
399
400 // FIXME: Can this happen?
401 if (Ty->isVariablyModifiedType())
402 EmitVLASize(Ty);
403 } else {
404 EnsureInsertPoint();
405
406 if (!DidCallStackSave) {
407 // Save the stack.
408 const llvm::Type *LTy = llvm::Type::getInt8PtrTy(VMContext);
409 llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
410
411 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
412 llvm::Value *V = Builder.CreateCall(F);
413
414 Builder.CreateStore(V, Stack);
415
416 DidCallStackSave = true;
417
418 {
419 // Push a cleanup block and restore the stack there.
420 DelayedCleanupBlock scope(*this);
421
422 V = Builder.CreateLoad(Stack, "tmp");
423 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
424 Builder.CreateCall(F, V);
425 }
426 }
427
428 // Get the element type.
429 const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
430 const llvm::Type *LElemPtrTy =
431 llvm::PointerType::get(LElemTy, D.getType().getAddressSpace());
432
433 llvm::Value *VLASize = EmitVLASize(Ty);
434
435 // Downcast the VLA size expression
436 VLASize = Builder.CreateIntCast(VLASize, llvm::Type::getInt32Ty(VMContext),
437 false, "tmp");
438
439 // Allocate memory for the array.
440 llvm::AllocaInst *VLA =
441 Builder.CreateAlloca(llvm::Type::getInt8Ty(VMContext), VLASize, "vla");
442 VLA->setAlignment(getContext().getDeclAlign(&D).getQuantity());
443
444 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
445 }
446
447 llvm::Value *&DMEntry = LocalDeclMap[&D];
448 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
449 DMEntry = DeclPtr;
450
451 // Emit debug info for local var declaration.
452 if (CGDebugInfo *DI = getDebugInfo()) {
453 assert(HaveInsertPoint() && "Unexpected unreachable point!");
454
455 DI->setLocation(D.getLocation());
456 if (Target.useGlobalsForAutomaticVariables()) {
457 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
458 } else
459 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
460 }
461
462 // If this local has an initializer, emit it now.
463 const Expr *Init = D.getInit();
464
465 // If we are at an unreachable point, we don't need to emit the initializer
466 // unless it contains a label.
467 if (!HaveInsertPoint()) {
468 if (!ContainsLabel(Init))
469 Init = 0;
470 else
471 EnsureInsertPoint();
472 }
473
474 if (Init) {
475 llvm::Value *Loc = DeclPtr;
476 if (isByRef)
477 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
478 D.getNameAsString());
479
480 bool isVolatile =
481 getContext().getCanonicalType(D.getType()).isVolatileQualified();
482
483 // If the initializer was a simple constant initializer, we can optimize it
484 // in various ways.
485 if (IsSimpleConstantInitializer) {
486 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(),D.getType(),this);
487 assert(Init != 0 && "Wasn't a simple constant init?");
488
489 llvm::Value *AlignVal =
490 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
491 Align.getQuantity());
492 const llvm::Type *IntPtr =
493 llvm::IntegerType::get(VMContext, LLVMPointerWidth);
494 llvm::Value *SizeVal =
495 llvm::ConstantInt::get(IntPtr,
496 getContext().getTypeSizeInChars(Ty).getQuantity());
497
498 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
499 if (Loc->getType() != BP)
500 Loc = Builder.CreateBitCast(Loc, BP, "tmp");
501
502 // If the initializer is all zeros, codegen with memset.
503 if (isa<llvm::ConstantAggregateZero>(Init)) {
504 llvm::Value *Zero =
505 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 0);
506 Builder.CreateCall4(CGM.getMemSetFn(), Loc, Zero, SizeVal, AlignVal);
507 } else {
508 // Otherwise, create a temporary global with the initializer then
509 // memcpy from the global to the alloca.
510 std::string Name = GetStaticDeclName(*this, D, ".");
511 llvm::GlobalVariable *GV =
512 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), true,
513 llvm::GlobalValue::InternalLinkage,
514 Init, Name, 0, false, 0);
515 GV->setAlignment(Align.getQuantity());
516
517 llvm::Value *SrcPtr = GV;
518 if (SrcPtr->getType() != BP)
519 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
520
521 Builder.CreateCall4(CGM.getMemCpyFn(), Loc, SrcPtr, SizeVal, AlignVal);
522 }
523 } else if (Ty->isReferenceType()) {
524 RValue RV = EmitReferenceBindingToExpr(Init, /*IsInitializer=*/true);
525 EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Ty);
526 } else if (!hasAggregateLLVMType(Init->getType())) {
527 llvm::Value *V = EmitScalarExpr(Init);
528 EmitStoreOfScalar(V, Loc, isVolatile, D.getType());
529 } else if (Init->getType()->isAnyComplexType()) {
530 EmitComplexExprIntoAddr(Init, Loc, isVolatile);
531 } else {
532 EmitAggExpr(Init, Loc, isVolatile);
533 }
534 }
535
536 if (isByRef) {
537 const llvm::PointerType *PtrToInt8Ty = llvm::Type::getInt8PtrTy(VMContext);
538
539 EnsureInsertPoint();
540 llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
541 llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
542 llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
543 llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
544 llvm::Value *V;
545 int flag = 0;
546 int flags = 0;
547
548 needsDispose = true;
549
550 if (Ty->isBlockPointerType()) {
551 flag |= BLOCK_FIELD_IS_BLOCK;
552 flags |= BLOCK_HAS_COPY_DISPOSE;
553 } else if (BlockRequiresCopying(Ty)) {
554 flag |= BLOCK_FIELD_IS_OBJECT;
555 flags |= BLOCK_HAS_COPY_DISPOSE;
556 }
557
558 // FIXME: Someone double check this.
559 if (Ty.isObjCGCWeak())
560 flag |= BLOCK_FIELD_IS_WEAK;
561
562 int isa = 0;
563 if (flag&BLOCK_FIELD_IS_WEAK)
564 isa = 1;
565 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), isa);
566 V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa");
567 Builder.CreateStore(V, isa_field);
568
569 Builder.CreateStore(DeclPtr, forwarding_field);
570
571 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), flags);
572 Builder.CreateStore(V, flags_field);
573
574 const llvm::Type *V1;
575 V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
576 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
577 CGM.GetTargetTypeStoreSize(V1).getQuantity());
578 Builder.CreateStore(V, size_field);
579
580 if (flags & BLOCK_HAS_COPY_DISPOSE) {
581 BlockHasCopyDispose = true;
582 llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
583 Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag,
584 Align.getQuantity()),
585 copy_helper);
586
587 llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
588 Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag,
589 Align.getQuantity()),
590 destroy_helper);
591 }
592 }
593
594 // Handle CXX destruction of variables.
595 QualType DtorTy(Ty);
596 while (const ArrayType *Array = getContext().getAsArrayType(DtorTy))
597 DtorTy = getContext().getBaseElementType(Array);
598 if (const RecordType *RT = DtorTy->getAs<RecordType>())
599 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
600 if (!ClassDecl->hasTrivialDestructor()) {
601 const CXXDestructorDecl *D = ClassDecl->getDestructor(getContext());
602 assert(D && "EmitLocalBlockVarDecl - destructor is nul");
603
604 if (const ConstantArrayType *Array =
605 getContext().getAsConstantArrayType(Ty)) {
606 {
607 DelayedCleanupBlock Scope(*this);
608 QualType BaseElementTy = getContext().getBaseElementType(Array);
609 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
610 BasePtr = llvm::PointerType::getUnqual(BasePtr);
611 llvm::Value *BaseAddrPtr =
612 Builder.CreateBitCast(DeclPtr, BasePtr);
613 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
614
615 // Make sure to jump to the exit block.
616 EmitBranch(Scope.getCleanupExitBlock());
617 }
618 if (Exceptions) {
619 EHCleanupBlock Cleanup(*this);
620 QualType BaseElementTy = getContext().getBaseElementType(Array);
621 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
622 BasePtr = llvm::PointerType::getUnqual(BasePtr);
623 llvm::Value *BaseAddrPtr =
624 Builder.CreateBitCast(DeclPtr, BasePtr);
625 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
626 }
627 } else {
628 {
629 DelayedCleanupBlock Scope(*this);
630 EmitCXXDestructorCall(D, Dtor_Complete, DeclPtr);
631
632 // Make sure to jump to the exit block.
633 EmitBranch(Scope.getCleanupExitBlock());
634 }
635 if (Exceptions) {
636 EHCleanupBlock Cleanup(*this);
637 EmitCXXDestructorCall(D, Dtor_Complete, DeclPtr);
638 }
639 }
640 }
641 }
642
643 // Handle the cleanup attribute
644 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
645 const FunctionDecl *FD = CA->getFunctionDecl();
646
647 llvm::Constant* F = CGM.GetAddrOfFunction(FD);
648 assert(F && "Could not find function!");
649
650 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
651
652 // In some cases, the type of the function argument will be different from
653 // the type of the pointer. An example of this is
654 // void f(void* arg);
655 // __attribute__((cleanup(f))) void *g;
656 //
657 // To fix this we insert a bitcast here.
658 QualType ArgTy = Info.arg_begin()->type;
659 {
660 DelayedCleanupBlock scope(*this);
661
662 CallArgList Args;
663 Args.push_back(std::make_pair(RValue::get(Builder.CreateBitCast(DeclPtr,
664 ConvertType(ArgTy))),
665 getContext().getPointerType(D.getType())));
666 EmitCall(Info, F, ReturnValueSlot(), Args);
667 }
668 if (Exceptions) {
669 EHCleanupBlock Cleanup(*this);
670
671 CallArgList Args;
672 Args.push_back(std::make_pair(RValue::get(Builder.CreateBitCast(DeclPtr,
673 ConvertType(ArgTy))),
674 getContext().getPointerType(D.getType())));
675 EmitCall(Info, F, ReturnValueSlot(), Args);
676 }
677 }
678
679 if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly) {
680 {
681 DelayedCleanupBlock scope(*this);
682 llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
683 V = Builder.CreateLoad(V);
684 BuildBlockRelease(V);
685 }
686 // FIXME: Turn this on and audit the codegen
687 if (0 && Exceptions) {
688 EHCleanupBlock Cleanup(*this);
689 llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
690 V = Builder.CreateLoad(V);
691 BuildBlockRelease(V);
692 }
693 }
694}
695
696/// Emit an alloca (or GlobalValue depending on target)
697/// for the specified parameter and set up LocalDeclMap.
698void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
699 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
700 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
701 "Invalid argument to EmitParmDecl");
702 QualType Ty = D.getType();
703 CanQualType CTy = getContext().getCanonicalType(Ty);
704
705 llvm::Value *DeclPtr;
706 // If this is an aggregate or variable sized value, reuse the input pointer.
707 if (!Ty->isConstantSizeType() ||
708 CodeGenFunction::hasAggregateLLVMType(Ty)) {
709 DeclPtr = Arg;
710 } else {
711 // Otherwise, create a temporary to hold the value.
712 DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr");
713
714 // Store the initial value into the alloca.
715 EmitStoreOfScalar(Arg, DeclPtr, CTy.isVolatileQualified(), Ty);
716 }
717 Arg->setName(D.getName());
718
719 llvm::Value *&DMEntry = LocalDeclMap[&D];
720 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
721 DMEntry = DeclPtr;
722
723 // Emit debug info for param declaration.
724 if (CGDebugInfo *DI = getDebugInfo()) {
725 DI->setLocation(D.getLocation());
726 DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
727 }
728}