1 //===--- 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/Frontend/CodeGenOptions.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Type.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
31 
32 void CodeGenFunction::EmitDecl(const Decl &D) {
33   switch (D.getKind()) {
34   case Decl::TranslationUnit:
35   case Decl::Namespace:
36   case Decl::UnresolvedUsingTypename:
37   case Decl::ClassTemplateSpecialization:
38   case Decl::ClassTemplatePartialSpecialization:
39   case Decl::TemplateTypeParm:
40   case Decl::UnresolvedUsingValue:
41   case Decl::NonTypeTemplateParm:
42   case Decl::CXXMethod:
43   case Decl::CXXConstructor:
44   case Decl::CXXDestructor:
45   case Decl::CXXConversion:
46   case Decl::Field:
47   case Decl::IndirectField:
48   case Decl::ObjCIvar:
49   case Decl::ObjCAtDefsField:
50   case Decl::ParmVar:
51   case Decl::ImplicitParam:
52   case Decl::ClassTemplate:
53   case Decl::FunctionTemplate:
54   case Decl::TypeAliasTemplate:
55   case Decl::TemplateTemplateParm:
56   case Decl::ObjCMethod:
57   case Decl::ObjCCategory:
58   case Decl::ObjCProtocol:
59   case Decl::ObjCInterface:
60   case Decl::ObjCCategoryImpl:
61   case Decl::ObjCImplementation:
62   case Decl::ObjCProperty:
63   case Decl::ObjCCompatibleAlias:
64   case Decl::AccessSpec:
65   case Decl::LinkageSpec:
66   case Decl::ObjCPropertyImpl:
67   case Decl::ObjCClass:
68   case Decl::ObjCForwardProtocol:
69   case Decl::FileScopeAsm:
70   case Decl::Friend:
71   case Decl::FriendTemplate:
72   case Decl::Block:
73     assert(0 && "Declaration should not be in declstmts!");
74   case Decl::Function:  // void X();
75   case Decl::Record:    // struct/union/class X;
76   case Decl::Enum:      // enum X;
77   case Decl::EnumConstant: // enum ? { X = ? }
78   case Decl::CXXRecord: // struct/union/class X; [C++]
79   case Decl::Using:          // using X; [C++]
80   case Decl::UsingShadow:
81   case Decl::UsingDirective: // using namespace X; [C++]
82   case Decl::NamespaceAlias:
83   case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
84   case Decl::Label:        // __label__ x;
85     // None of these decls require codegen support.
86     return;
87 
88   case Decl::Var: {
89     const VarDecl &VD = cast<VarDecl>(D);
90     assert(VD.isLocalVarDecl() &&
91            "Should not see file-scope variables inside a function!");
92     return EmitVarDecl(VD);
93   }
94 
95   case Decl::Typedef:      // typedef int X;
96   case Decl::TypeAlias: {  // using X = int; [C++0x]
97     const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
98     QualType Ty = TD.getUnderlyingType();
99 
100     if (Ty->isVariablyModifiedType())
101       EmitVLASize(Ty);
102   }
103   }
104 }
105 
106 /// EmitVarDecl - This method handles emission of any variable declaration
107 /// inside a function, including static vars etc.
108 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
109   switch (D.getStorageClass()) {
110   case SC_None:
111   case SC_Auto:
112   case SC_Register:
113     return EmitAutoVarDecl(D);
114   case SC_Static: {
115     llvm::GlobalValue::LinkageTypes Linkage =
116       llvm::GlobalValue::InternalLinkage;
117 
118     // If the function definition has some sort of weak linkage, its
119     // static variables should also be weak so that they get properly
120     // uniqued.  We can't do this in C, though, because there's no
121     // standard way to agree on which variables are the same (i.e.
122     // there's no mangling).
123     if (getContext().getLangOptions().CPlusPlus)
124       if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
125         Linkage = CurFn->getLinkage();
126 
127     return EmitStaticVarDecl(D, Linkage);
128   }
129   case SC_Extern:
130   case SC_PrivateExtern:
131     // Don't emit it now, allow it to be emitted lazily on its first use.
132     return;
133   }
134 
135   assert(0 && "Unknown storage class");
136 }
137 
138 static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
139                                      const char *Separator) {
140   CodeGenModule &CGM = CGF.CGM;
141   if (CGF.getContext().getLangOptions().CPlusPlus) {
142     llvm::StringRef Name = CGM.getMangledName(&D);
143     return Name.str();
144   }
145 
146   std::string ContextName;
147   if (!CGF.CurFuncDecl) {
148     // Better be in a block declared in global scope.
149     const NamedDecl *ND = cast<NamedDecl>(&D);
150     const DeclContext *DC = ND->getDeclContext();
151     if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
152       MangleBuffer Name;
153       CGM.getBlockMangledName(GlobalDecl(), Name, BD);
154       ContextName = Name.getString();
155     }
156     else
157       assert(0 && "Unknown context for block static var decl");
158   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
159     llvm::StringRef Name = CGM.getMangledName(FD);
160     ContextName = Name.str();
161   } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
162     ContextName = CGF.CurFn->getName();
163   else
164     assert(0 && "Unknown context for static var decl");
165 
166   return ContextName + Separator + D.getNameAsString();
167 }
168 
169 llvm::GlobalVariable *
170 CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
171                                      const char *Separator,
172                                      llvm::GlobalValue::LinkageTypes Linkage) {
173   QualType Ty = D.getType();
174   assert(Ty->isConstantSizeType() && "VLAs can't be static");
175 
176   std::string Name = GetStaticDeclName(*this, D, Separator);
177 
178   const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
179   llvm::GlobalVariable *GV =
180     new llvm::GlobalVariable(CGM.getModule(), LTy,
181                              Ty.isConstant(getContext()), Linkage,
182                              CGM.EmitNullConstant(D.getType()), Name, 0,
183                              D.isThreadSpecified(),
184                              CGM.getContext().getTargetAddressSpace(Ty));
185   GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
186   if (Linkage != llvm::GlobalValue::InternalLinkage)
187     GV->setVisibility(CurFn->getVisibility());
188   return GV;
189 }
190 
191 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
192 /// global variable that has already been created for it.  If the initializer
193 /// has a different type than GV does, this may free GV and return a different
194 /// one.  Otherwise it just returns GV.
195 llvm::GlobalVariable *
196 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
197                                                llvm::GlobalVariable *GV) {
198   llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
199 
200   // If constant emission failed, then this should be a C++ static
201   // initializer.
202   if (!Init) {
203     if (!getContext().getLangOptions().CPlusPlus)
204       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
205     else if (Builder.GetInsertBlock()) {
206       // Since we have a static initializer, this global variable can't
207       // be constant.
208       GV->setConstant(false);
209 
210       EmitCXXGuardedInit(D, GV);
211     }
212     return GV;
213   }
214 
215   // The initializer may differ in type from the global. Rewrite
216   // the global to match the initializer.  (We have to do this
217   // because some types, like unions, can't be completely represented
218   // in the LLVM type system.)
219   if (GV->getType()->getElementType() != Init->getType()) {
220     llvm::GlobalVariable *OldGV = GV;
221 
222     GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
223                                   OldGV->isConstant(),
224                                   OldGV->getLinkage(), Init, "",
225                                   /*InsertBefore*/ OldGV,
226                                   D.isThreadSpecified(),
227                            CGM.getContext().getTargetAddressSpace(D.getType()));
228     GV->setVisibility(OldGV->getVisibility());
229 
230     // Steal the name of the old global
231     GV->takeName(OldGV);
232 
233     // Replace all uses of the old global with the new global
234     llvm::Constant *NewPtrForOldDecl =
235     llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
236     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
237 
238     // Erase the old global, since it is no longer used.
239     OldGV->eraseFromParent();
240   }
241 
242   GV->setInitializer(Init);
243   return GV;
244 }
245 
246 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
247                                       llvm::GlobalValue::LinkageTypes Linkage) {
248   llvm::Value *&DMEntry = LocalDeclMap[&D];
249   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
250 
251   llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
252 
253   // Store into LocalDeclMap before generating initializer to handle
254   // circular references.
255   DMEntry = GV;
256 
257   // We can't have a VLA here, but we can have a pointer to a VLA,
258   // even though that doesn't really make any sense.
259   // Make sure to evaluate VLA bounds now so that we have them for later.
260   if (D.getType()->isVariablyModifiedType())
261     EmitVLASize(D.getType());
262 
263   // Local static block variables must be treated as globals as they may be
264   // referenced in their RHS initializer block-literal expresion.
265   CGM.setStaticLocalDeclAddress(&D, GV);
266 
267   // If this value has an initializer, emit it.
268   if (D.getInit())
269     GV = AddInitializerToStaticVarDecl(D, GV);
270 
271   GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
272 
273   // FIXME: Merge attribute handling.
274   if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
275     SourceManager &SM = CGM.getContext().getSourceManager();
276     llvm::Constant *Ann =
277       CGM.EmitAnnotateAttr(GV, AA,
278                            SM.getInstantiationLineNumber(D.getLocation()));
279     CGM.AddAnnotation(Ann);
280   }
281 
282   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
283     GV->setSection(SA->getName());
284 
285   if (D.hasAttr<UsedAttr>())
286     CGM.AddUsedGlobal(GV);
287 
288   // We may have to cast the constant because of the initializer
289   // mismatch above.
290   //
291   // FIXME: It is really dangerous to store this in the map; if anyone
292   // RAUW's the GV uses of this constant will be invalid.
293   const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
294   const llvm::Type *LPtrTy =
295     LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType()));
296   DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
297 
298   // Emit global variable debug descriptor for static vars.
299   CGDebugInfo *DI = getDebugInfo();
300   if (DI) {
301     DI->setLocation(D.getLocation());
302     DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
303   }
304 }
305 
306 namespace {
307   struct CallArrayDtor : EHScopeStack::Cleanup {
308     CallArrayDtor(const CXXDestructorDecl *Dtor,
309                   const ConstantArrayType *Type,
310                   llvm::Value *Loc)
311       : Dtor(Dtor), Type(Type), Loc(Loc) {}
312 
313     const CXXDestructorDecl *Dtor;
314     const ConstantArrayType *Type;
315     llvm::Value *Loc;
316 
317     void Emit(CodeGenFunction &CGF, bool IsForEH) {
318       QualType BaseElementTy = CGF.getContext().getBaseElementType(Type);
319       const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
320       BasePtr = llvm::PointerType::getUnqual(BasePtr);
321       llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(Loc, BasePtr);
322       CGF.EmitCXXAggrDestructorCall(Dtor, Type, BaseAddrPtr);
323     }
324   };
325 
326   struct CallVarDtor : EHScopeStack::Cleanup {
327     CallVarDtor(const CXXDestructorDecl *Dtor,
328                 llvm::Value *NRVOFlag,
329                 llvm::Value *Loc)
330       : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(Loc) {}
331 
332     const CXXDestructorDecl *Dtor;
333     llvm::Value *NRVOFlag;
334     llvm::Value *Loc;
335 
336     void Emit(CodeGenFunction &CGF, bool IsForEH) {
337       // Along the exceptions path we always execute the dtor.
338       bool NRVO = !IsForEH && NRVOFlag;
339 
340       llvm::BasicBlock *SkipDtorBB = 0;
341       if (NRVO) {
342         // If we exited via NRVO, we skip the destructor call.
343         llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
344         SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
345         llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
346         CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
347         CGF.EmitBlock(RunDtorBB);
348       }
349 
350       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
351                                 /*ForVirtualBase=*/false, Loc);
352 
353       if (NRVO) CGF.EmitBlock(SkipDtorBB);
354     }
355   };
356 }
357 
358 namespace {
359   struct CallStackRestore : EHScopeStack::Cleanup {
360     llvm::Value *Stack;
361     CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
362     void Emit(CodeGenFunction &CGF, bool IsForEH) {
363       llvm::Value *V = CGF.Builder.CreateLoad(Stack, "tmp");
364       llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
365       CGF.Builder.CreateCall(F, V);
366     }
367   };
368 
369   struct CallCleanupFunction : EHScopeStack::Cleanup {
370     llvm::Constant *CleanupFn;
371     const CGFunctionInfo &FnInfo;
372     const VarDecl &Var;
373 
374     CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
375                         const VarDecl *Var)
376       : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
377 
378     void Emit(CodeGenFunction &CGF, bool IsForEH) {
379       DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
380                       SourceLocation());
381       // Compute the address of the local variable, in case it's a byref
382       // or something.
383       llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
384 
385       // In some cases, the type of the function argument will be different from
386       // the type of the pointer. An example of this is
387       // void f(void* arg);
388       // __attribute__((cleanup(f))) void *g;
389       //
390       // To fix this we insert a bitcast here.
391       QualType ArgTy = FnInfo.arg_begin()->type;
392       llvm::Value *Arg =
393         CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
394 
395       CallArgList Args;
396       Args.add(RValue::get(Arg),
397                CGF.getContext().getPointerType(Var.getType()));
398       CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
399     }
400   };
401 }
402 
403 
404 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
405 /// non-zero parts of the specified initializer with equal or fewer than
406 /// NumStores scalar stores.
407 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
408                                                 unsigned &NumStores) {
409   // Zero and Undef never requires any extra stores.
410   if (isa<llvm::ConstantAggregateZero>(Init) ||
411       isa<llvm::ConstantPointerNull>(Init) ||
412       isa<llvm::UndefValue>(Init))
413     return true;
414   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
415       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
416       isa<llvm::ConstantExpr>(Init))
417     return Init->isNullValue() || NumStores--;
418 
419   // See if we can emit each element.
420   if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
421     for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
422       llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
423       if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
424         return false;
425     }
426     return true;
427   }
428 
429   // Anything else is hard and scary.
430   return false;
431 }
432 
433 /// emitStoresForInitAfterMemset - For inits that
434 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
435 /// stores that would be required.
436 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
437                                          bool isVolatile, CGBuilderTy &Builder) {
438   // Zero doesn't require any stores.
439   if (isa<llvm::ConstantAggregateZero>(Init) ||
440       isa<llvm::ConstantPointerNull>(Init) ||
441       isa<llvm::UndefValue>(Init))
442     return;
443 
444   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
445       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
446       isa<llvm::ConstantExpr>(Init)) {
447     if (!Init->isNullValue())
448       Builder.CreateStore(Init, Loc, isVolatile);
449     return;
450   }
451 
452   assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
453          "Unknown value type!");
454 
455   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
456     llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
457     if (Elt->isNullValue()) continue;
458 
459     // Otherwise, get a pointer to the element and emit it.
460     emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
461                                  isVolatile, Builder);
462   }
463 }
464 
465 
466 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
467 /// plus some stores to initialize a local variable instead of using a memcpy
468 /// from a constant global.  It is beneficial to use memset if the global is all
469 /// zeros, or mostly zeros and large.
470 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
471                                                   uint64_t GlobalSize) {
472   // If a global is all zeros, always use a memset.
473   if (isa<llvm::ConstantAggregateZero>(Init)) return true;
474 
475 
476   // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
477   // do it if it will require 6 or fewer scalar stores.
478   // TODO: Should budget depends on the size?  Avoiding a large global warrants
479   // plopping in more stores.
480   unsigned StoreBudget = 6;
481   uint64_t SizeLimit = 32;
482 
483   return GlobalSize > SizeLimit &&
484          canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
485 }
486 
487 
488 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
489 /// variable declaration with auto, register, or no storage class specifier.
490 /// These turn into simple stack objects, or GlobalValues depending on target.
491 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
492   AutoVarEmission emission = EmitAutoVarAlloca(D);
493   EmitAutoVarInit(emission);
494   EmitAutoVarCleanups(emission);
495 }
496 
497 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
498 /// local variable.  Does not emit initalization or destruction.
499 CodeGenFunction::AutoVarEmission
500 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
501   QualType Ty = D.getType();
502 
503   AutoVarEmission emission(D);
504 
505   bool isByRef = D.hasAttr<BlocksAttr>();
506   emission.IsByRef = isByRef;
507 
508   CharUnits alignment = getContext().getDeclAlign(&D);
509   emission.Alignment = alignment;
510 
511   llvm::Value *DeclPtr;
512   if (Ty->isConstantSizeType()) {
513     if (!Target.useGlobalsForAutomaticVariables()) {
514       bool NRVO = getContext().getLangOptions().ElideConstructors &&
515                   D.isNRVOVariable();
516 
517       // If this value is a POD array or struct with a statically
518       // determinable constant initializer, there are optimizations we
519       // can do.
520       // TODO: we can potentially constant-evaluate non-POD structs and
521       // arrays as long as the initialization is trivial (e.g. if they
522       // have a non-trivial destructor, but not a non-trivial constructor).
523       if (D.getInit() &&
524           (Ty->isArrayType() || Ty->isRecordType()) && Ty->isPODType() &&
525           D.getInit()->isConstantInitializer(getContext(), false)) {
526 
527         // If the variable's a const type, and it's neither an NRVO
528         // candidate nor a __block variable, emit it as a global instead.
529         if (CGM.getCodeGenOpts().MergeAllConstants && Ty.isConstQualified() &&
530             !NRVO && !isByRef) {
531           EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
532 
533           emission.Address = 0; // signal this condition to later callbacks
534           assert(emission.wasEmittedAsGlobal());
535           return emission;
536         }
537 
538         // Otherwise, tell the initialization code that we're in this case.
539         emission.IsConstantAggregate = true;
540       }
541 
542       // A normal fixed sized variable becomes an alloca in the entry block,
543       // unless it's an NRVO variable.
544       const llvm::Type *LTy = ConvertTypeForMem(Ty);
545 
546       if (NRVO) {
547         // The named return value optimization: allocate this variable in the
548         // return slot, so that we can elide the copy when returning this
549         // variable (C++0x [class.copy]p34).
550         DeclPtr = ReturnValue;
551 
552         if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
553           if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
554             // Create a flag that is used to indicate when the NRVO was applied
555             // to this variable. Set it to zero to indicate that NRVO was not
556             // applied.
557             llvm::Value *Zero = Builder.getFalse();
558             llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
559             EnsureInsertPoint();
560             Builder.CreateStore(Zero, NRVOFlag);
561 
562             // Record the NRVO flag for this variable.
563             NRVOFlags[&D] = NRVOFlag;
564             emission.NRVOFlag = NRVOFlag;
565           }
566         }
567       } else {
568         if (isByRef)
569           LTy = BuildByRefType(&D);
570 
571         llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
572         Alloc->setName(D.getNameAsString());
573 
574         CharUnits allocaAlignment = alignment;
575         if (isByRef)
576           allocaAlignment = std::max(allocaAlignment,
577               getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
578         Alloc->setAlignment(allocaAlignment.getQuantity());
579         DeclPtr = Alloc;
580       }
581     } else {
582       // Targets that don't support recursion emit locals as globals.
583       const char *Class =
584         D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
585       DeclPtr = CreateStaticVarDecl(D, Class,
586                                     llvm::GlobalValue::InternalLinkage);
587     }
588 
589     // FIXME: Can this happen?
590     if (Ty->isVariablyModifiedType())
591       EmitVLASize(Ty);
592   } else {
593     EnsureInsertPoint();
594 
595     if (!DidCallStackSave) {
596       // Save the stack.
597       llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
598 
599       llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
600       llvm::Value *V = Builder.CreateCall(F);
601 
602       Builder.CreateStore(V, Stack);
603 
604       DidCallStackSave = true;
605 
606       // Push a cleanup block and restore the stack there.
607       // FIXME: in general circumstances, this should be an EH cleanup.
608       EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
609     }
610 
611     // Get the element type.
612     const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
613     const llvm::Type *LElemPtrTy =
614       LElemTy->getPointerTo(CGM.getContext().getTargetAddressSpace(Ty));
615 
616     llvm::Value *VLASize = EmitVLASize(Ty);
617 
618     // Allocate memory for the array.
619     llvm::AllocaInst *VLA =
620       Builder.CreateAlloca(llvm::Type::getInt8Ty(getLLVMContext()), VLASize, "vla");
621     VLA->setAlignment(alignment.getQuantity());
622 
623     DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
624   }
625 
626   llvm::Value *&DMEntry = LocalDeclMap[&D];
627   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
628   DMEntry = DeclPtr;
629   emission.Address = DeclPtr;
630 
631   // Emit debug info for local var declaration.
632   if (CGDebugInfo *DI = getDebugInfo()) {
633     assert(HaveInsertPoint() && "Unexpected unreachable point!");
634 
635     DI->setLocation(D.getLocation());
636     if (Target.useGlobalsForAutomaticVariables()) {
637       DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
638     } else
639       DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
640   }
641 
642   return emission;
643 }
644 
645 /// Determines whether the given __block variable is potentially
646 /// captured by the given expression.
647 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
648   // Skip the most common kinds of expressions that make
649   // hierarchy-walking expensive.
650   e = e->IgnoreParenCasts();
651 
652   if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
653     const BlockDecl *block = be->getBlockDecl();
654     for (BlockDecl::capture_const_iterator i = block->capture_begin(),
655            e = block->capture_end(); i != e; ++i) {
656       if (i->getVariable() == &var)
657         return true;
658     }
659 
660     // No need to walk into the subexpressions.
661     return false;
662   }
663 
664   for (Stmt::const_child_range children = e->children(); children; ++children)
665     if (isCapturedBy(var, cast<Expr>(*children)))
666       return true;
667 
668   return false;
669 }
670 
671 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
672   assert(emission.Variable && "emission was not valid!");
673 
674   // If this was emitted as a global constant, we're done.
675   if (emission.wasEmittedAsGlobal()) return;
676 
677   const VarDecl &D = *emission.Variable;
678   QualType type = D.getType();
679 
680   // If this local has an initializer, emit it now.
681   const Expr *Init = D.getInit();
682 
683   // If we are at an unreachable point, we don't need to emit the initializer
684   // unless it contains a label.
685   if (!HaveInsertPoint()) {
686     if (!Init || !ContainsLabel(Init)) return;
687     EnsureInsertPoint();
688   }
689 
690   // Initialize the structure of a __block variable.
691   if (emission.IsByRef)
692     emitByrefStructureInit(emission);
693 
694   if (!Init) return;
695 
696   CharUnits alignment = emission.Alignment;
697 
698   // Check whether this is a byref variable that's potentially
699   // captured and moved by its own initializer.  If so, we'll need to
700   // emit the initializer first, then copy into the variable.
701   bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
702 
703   llvm::Value *Loc =
704     capturedByInit ? emission.Address : emission.getObjectAddress(*this);
705 
706   if (!emission.IsConstantAggregate)
707     return EmitExprAsInit(Init, &D, Loc, alignment, capturedByInit);
708 
709   // If this is a simple aggregate initialization, we can optimize it
710   // in various ways.
711   assert(!capturedByInit && "constant init contains a capturing block?");
712 
713   bool isVolatile = type.isVolatileQualified();
714 
715   llvm::Constant *constant = CGM.EmitConstantExpr(D.getInit(), type, this);
716   assert(constant != 0 && "Wasn't a simple constant init?");
717 
718   llvm::Value *SizeVal =
719     llvm::ConstantInt::get(IntPtrTy,
720                            getContext().getTypeSizeInChars(type).getQuantity());
721 
722   const llvm::Type *BP = Int8PtrTy;
723   if (Loc->getType() != BP)
724     Loc = Builder.CreateBitCast(Loc, BP, "tmp");
725 
726   // If the initializer is all or mostly zeros, codegen with memset then do
727   // a few stores afterward.
728   if (shouldUseMemSetPlusStoresToInitialize(constant,
729                 CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
730     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
731                          alignment.getQuantity(), isVolatile);
732     if (!constant->isNullValue()) {
733       Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
734       emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
735     }
736   } else {
737     // Otherwise, create a temporary global with the initializer then
738     // memcpy from the global to the alloca.
739     std::string Name = GetStaticDeclName(*this, D, ".");
740     llvm::GlobalVariable *GV =
741       new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
742                                llvm::GlobalValue::InternalLinkage,
743                                constant, Name, 0, false, 0);
744     GV->setAlignment(alignment.getQuantity());
745     GV->setUnnamedAddr(true);
746 
747     llvm::Value *SrcPtr = GV;
748     if (SrcPtr->getType() != BP)
749       SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
750 
751     Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
752                          isVolatile);
753   }
754 }
755 
756 /// Emit an expression as an initializer for a variable at the given
757 /// location.  The expression is not necessarily the normal
758 /// initializer for the variable, and the address is not necessarily
759 /// its normal location.
760 ///
761 /// \param init the initializing expression
762 /// \param var the variable to act as if we're initializing
763 /// \param loc the address to initialize; its type is a pointer
764 ///   to the LLVM mapping of the variable's type
765 /// \param alignment the alignment of the address
766 /// \param capturedByInit true if the variable is a __block variable
767 ///   whose address is potentially changed by the initializer
768 void CodeGenFunction::EmitExprAsInit(const Expr *init,
769                                      const VarDecl *var,
770                                      llvm::Value *loc,
771                                      CharUnits alignment,
772                                      bool capturedByInit) {
773   QualType type = var->getType();
774   bool isVolatile = type.isVolatileQualified();
775 
776   if (type->isReferenceType()) {
777     RValue RV = EmitReferenceBindingToExpr(init, var);
778     if (capturedByInit) loc = BuildBlockByrefAddress(loc, var);
779     EmitStoreOfScalar(RV.getScalarVal(), loc, false,
780                       alignment.getQuantity(), type);
781   } else if (!hasAggregateLLVMType(type)) {
782     llvm::Value *V = EmitScalarExpr(init);
783     if (capturedByInit) loc = BuildBlockByrefAddress(loc, var);
784     EmitStoreOfScalar(V, loc, isVolatile, alignment.getQuantity(), type);
785   } else if (type->isAnyComplexType()) {
786     ComplexPairTy complex = EmitComplexExpr(init);
787     if (capturedByInit) loc = BuildBlockByrefAddress(loc, var);
788     StoreComplexToAddr(complex, loc, isVolatile);
789   } else {
790     // TODO: how can we delay here if D is captured by its initializer?
791     EmitAggExpr(init, AggValueSlot::forAddr(loc, isVolatile, true, false));
792   }
793 }
794 
795 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
796   assert(emission.Variable && "emission was not valid!");
797 
798   // If this was emitted as a global constant, we're done.
799   if (emission.wasEmittedAsGlobal()) return;
800 
801   const VarDecl &D = *emission.Variable;
802 
803   // Handle C++ destruction of variables.
804   if (getLangOptions().CPlusPlus) {
805     QualType type = D.getType();
806     QualType baseType = getContext().getBaseElementType(type);
807     if (const RecordType *RT = baseType->getAs<RecordType>()) {
808       CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
809       if (!ClassDecl->hasTrivialDestructor()) {
810         // Note: We suppress the destructor call when the corresponding NRVO
811         // flag has been set.
812 
813         // Note that for __block variables, we want to destroy the
814         // original stack object, not the possible forwarded object.
815         llvm::Value *Loc = emission.getObjectAddress(*this);
816 
817         const CXXDestructorDecl *D = ClassDecl->getDestructor();
818         assert(D && "EmitLocalBlockVarDecl - destructor is nul");
819 
820         if (type != baseType) {
821           const ConstantArrayType *Array =
822             getContext().getAsConstantArrayType(type);
823           assert(Array && "types changed without array?");
824           EHStack.pushCleanup<CallArrayDtor>(NormalAndEHCleanup,
825                                              D, Array, Loc);
826         } else {
827           EHStack.pushCleanup<CallVarDtor>(NormalAndEHCleanup,
828                                            D, emission.NRVOFlag, Loc);
829         }
830       }
831     }
832   }
833 
834   // Handle the cleanup attribute.
835   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
836     const FunctionDecl *FD = CA->getFunctionDecl();
837 
838     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
839     assert(F && "Could not find function!");
840 
841     const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
842     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
843   }
844 
845   // If this is a block variable, call _Block_object_destroy
846   // (on the unforwarded address).
847   if (emission.IsByRef)
848     enterByrefCleanup(emission);
849 }
850 
851 /// Emit an alloca (or GlobalValue depending on target)
852 /// for the specified parameter and set up LocalDeclMap.
853 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
854                                    unsigned ArgNo) {
855   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
856   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
857          "Invalid argument to EmitParmDecl");
858 
859   Arg->setName(D.getName());
860 
861   // Use better IR generation for certain implicit parameters.
862   if (isa<ImplicitParamDecl>(D)) {
863     // The only implicit argument a block has is its literal.
864     if (BlockInfo) {
865       LocalDeclMap[&D] = Arg;
866 
867       if (CGDebugInfo *DI = getDebugInfo()) {
868         DI->setLocation(D.getLocation());
869         DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
870       }
871 
872       return;
873     }
874   }
875 
876   QualType Ty = D.getType();
877 
878   llvm::Value *DeclPtr;
879   // If this is an aggregate or variable sized value, reuse the input pointer.
880   if (!Ty->isConstantSizeType() ||
881       CodeGenFunction::hasAggregateLLVMType(Ty)) {
882     DeclPtr = Arg;
883   } else {
884     // Otherwise, create a temporary to hold the value.
885     DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr");
886 
887     // Store the initial value into the alloca.
888     EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified(),
889                       getContext().getDeclAlign(&D).getQuantity(), Ty,
890                       CGM.getTBAAInfo(Ty));
891   }
892 
893   llvm::Value *&DMEntry = LocalDeclMap[&D];
894   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
895   DMEntry = DeclPtr;
896 
897   // Emit debug info for param declaration.
898   if (CGDebugInfo *DI = getDebugInfo()) {
899     DI->setLocation(D.getLocation());
900     DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
901   }
902 }
903