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 "CodeGenFunction.h"
15 #include "CGDebugInfo.h"
16 #include "CGOpenCLRuntime.h"
17 #include "CodeGenModule.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/Type.h"
29 using namespace clang;
30 using namespace CodeGen;
31 
32 
33 void CodeGenFunction::EmitDecl(const Decl &D) {
34   switch (D.getKind()) {
35   case Decl::TranslationUnit:
36   case Decl::Namespace:
37   case Decl::UnresolvedUsingTypename:
38   case Decl::ClassTemplateSpecialization:
39   case Decl::ClassTemplatePartialSpecialization:
40   case Decl::TemplateTypeParm:
41   case Decl::UnresolvedUsingValue:
42   case Decl::NonTypeTemplateParm:
43   case Decl::CXXMethod:
44   case Decl::CXXConstructor:
45   case Decl::CXXDestructor:
46   case Decl::CXXConversion:
47   case Decl::Field:
48   case Decl::IndirectField:
49   case Decl::ObjCIvar:
50   case Decl::ObjCAtDefsField:
51   case Decl::ParmVar:
52   case Decl::ImplicitParam:
53   case Decl::ClassTemplate:
54   case Decl::FunctionTemplate:
55   case Decl::TypeAliasTemplate:
56   case Decl::TemplateTemplateParm:
57   case Decl::ObjCMethod:
58   case Decl::ObjCCategory:
59   case Decl::ObjCProtocol:
60   case Decl::ObjCInterface:
61   case Decl::ObjCCategoryImpl:
62   case Decl::ObjCImplementation:
63   case Decl::ObjCProperty:
64   case Decl::ObjCCompatibleAlias:
65   case Decl::AccessSpec:
66   case Decl::LinkageSpec:
67   case Decl::ObjCPropertyImpl:
68   case Decl::FileScopeAsm:
69   case Decl::Friend:
70   case Decl::FriendTemplate:
71   case Decl::Block:
72   case Decl::ClassScopeFunctionSpecialization:
73     llvm_unreachable("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   case Decl::Import:
86     // None of these decls require codegen support.
87     return;
88 
89   case Decl::Var: {
90     const VarDecl &VD = cast<VarDecl>(D);
91     assert(VD.isLocalVarDecl() &&
92            "Should not see file-scope variables inside a function!");
93     return EmitVarDecl(VD);
94   }
95 
96   case Decl::Typedef:      // typedef int X;
97   case Decl::TypeAlias: {  // using X = int; [C++0x]
98     const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
99     QualType Ty = TD.getUnderlyingType();
100 
101     if (Ty->isVariablyModifiedType())
102       EmitVariablyModifiedType(Ty);
103   }
104   }
105 }
106 
107 /// EmitVarDecl - This method handles emission of any variable declaration
108 /// inside a function, including static vars etc.
109 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
110   switch (D.getStorageClassAsWritten()) {
111   case SC_None:
112   case SC_Auto:
113   case SC_Register:
114     return EmitAutoVarDecl(D);
115   case SC_Static: {
116     llvm::GlobalValue::LinkageTypes Linkage =
117       llvm::GlobalValue::InternalLinkage;
118 
119     // If the function definition has some sort of weak linkage, its
120     // static variables should also be weak so that they get properly
121     // uniqued.  We can't do this in C, though, because there's no
122     // standard way to agree on which variables are the same (i.e.
123     // there's no mangling).
124     if (getLangOpts().CPlusPlus)
125       if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
126         Linkage = CurFn->getLinkage();
127 
128     return EmitStaticVarDecl(D, Linkage);
129   }
130   case SC_Extern:
131   case SC_PrivateExtern:
132     // Don't emit it now, allow it to be emitted lazily on its first use.
133     return;
134   case SC_OpenCLWorkGroupLocal:
135     return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
136   }
137 
138   llvm_unreachable("Unknown storage class");
139 }
140 
141 static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
142                                      const char *Separator) {
143   CodeGenModule &CGM = CGF.CGM;
144   if (CGF.getLangOpts().CPlusPlus) {
145     StringRef Name = CGM.getMangledName(&D);
146     return Name.str();
147   }
148 
149   std::string ContextName;
150   if (!CGF.CurFuncDecl) {
151     // Better be in a block declared in global scope.
152     const NamedDecl *ND = cast<NamedDecl>(&D);
153     const DeclContext *DC = ND->getDeclContext();
154     if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
155       MangleBuffer Name;
156       CGM.getBlockMangledName(GlobalDecl(), Name, BD);
157       ContextName = Name.getString();
158     }
159     else
160       llvm_unreachable("Unknown context for block static var decl");
161   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
162     StringRef Name = CGM.getMangledName(FD);
163     ContextName = Name.str();
164   } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
165     ContextName = CGF.CurFn->getName();
166   else
167     llvm_unreachable("Unknown context for static var decl");
168 
169   return ContextName + Separator + D.getNameAsString();
170 }
171 
172 llvm::GlobalVariable *
173 CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
174                                      const char *Separator,
175                                      llvm::GlobalValue::LinkageTypes Linkage) {
176   QualType Ty = D.getType();
177   assert(Ty->isConstantSizeType() && "VLAs can't be static");
178 
179   // Use the label if the variable is renamed with the asm-label extension.
180   std::string Name;
181   if (D.hasAttr<AsmLabelAttr>())
182     Name = CGM.getMangledName(&D);
183   else
184     Name = GetStaticDeclName(*this, D, Separator);
185 
186   llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
187   unsigned AddrSpace =
188    CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
189   llvm::GlobalVariable *GV =
190     new llvm::GlobalVariable(CGM.getModule(), LTy,
191                              Ty.isConstant(getContext()), Linkage,
192                              CGM.EmitNullConstant(D.getType()), Name, 0,
193                              llvm::GlobalVariable::NotThreadLocal,
194                              AddrSpace);
195   GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
196   if (Linkage != llvm::GlobalValue::InternalLinkage)
197     GV->setVisibility(CurFn->getVisibility());
198 
199   if (D.isThreadSpecified())
200     CGM.setTLSMode(GV, D);
201 
202   return GV;
203 }
204 
205 /// hasNontrivialDestruction - Determine whether a type's destruction is
206 /// non-trivial. If so, and the variable uses static initialization, we must
207 /// register its destructor to run on exit.
208 static bool hasNontrivialDestruction(QualType T) {
209   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
210   return RD && !RD->hasTrivialDestructor();
211 }
212 
213 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
214 /// global variable that has already been created for it.  If the initializer
215 /// has a different type than GV does, this may free GV and return a different
216 /// one.  Otherwise it just returns GV.
217 llvm::GlobalVariable *
218 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
219                                                llvm::GlobalVariable *GV) {
220   llvm::Constant *Init = CGM.EmitConstantInit(D, this);
221 
222   // If constant emission failed, then this should be a C++ static
223   // initializer.
224   if (!Init) {
225     if (!getLangOpts().CPlusPlus)
226       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
227     else if (Builder.GetInsertBlock()) {
228       // Since we have a static initializer, this global variable can't
229       // be constant.
230       GV->setConstant(false);
231 
232       EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
233     }
234     return GV;
235   }
236 
237   // The initializer may differ in type from the global. Rewrite
238   // the global to match the initializer.  (We have to do this
239   // because some types, like unions, can't be completely represented
240   // in the LLVM type system.)
241   if (GV->getType()->getElementType() != Init->getType()) {
242     llvm::GlobalVariable *OldGV = GV;
243 
244     GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
245                                   OldGV->isConstant(),
246                                   OldGV->getLinkage(), Init, "",
247                                   /*InsertBefore*/ OldGV,
248                                   OldGV->getThreadLocalMode(),
249                            CGM.getContext().getTargetAddressSpace(D.getType()));
250     GV->setVisibility(OldGV->getVisibility());
251 
252     // Steal the name of the old global
253     GV->takeName(OldGV);
254 
255     // Replace all uses of the old global with the new global
256     llvm::Constant *NewPtrForOldDecl =
257     llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
258     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
259 
260     // Erase the old global, since it is no longer used.
261     OldGV->eraseFromParent();
262   }
263 
264   GV->setConstant(CGM.isTypeConstant(D.getType(), true));
265   GV->setInitializer(Init);
266 
267   if (hasNontrivialDestruction(D.getType())) {
268     // We have a constant initializer, but a nontrivial destructor. We still
269     // need to perform a guarded "initialization" in order to register the
270     // destructor.
271     EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
272   }
273 
274   return GV;
275 }
276 
277 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
278                                       llvm::GlobalValue::LinkageTypes Linkage) {
279   llvm::Value *&DMEntry = LocalDeclMap[&D];
280   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
281 
282   // Check to see if we already have a global variable for this
283   // declaration.  This can happen when double-emitting function
284   // bodies, e.g. with complete and base constructors.
285   llvm::Constant *addr =
286     CGM.getStaticLocalDeclAddress(&D);
287 
288   llvm::GlobalVariable *var;
289   if (addr) {
290     var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
291   } else {
292     addr = var = CreateStaticVarDecl(D, ".", Linkage);
293   }
294 
295   // Store into LocalDeclMap before generating initializer to handle
296   // circular references.
297   DMEntry = addr;
298   CGM.setStaticLocalDeclAddress(&D, addr);
299 
300   // We can't have a VLA here, but we can have a pointer to a VLA,
301   // even though that doesn't really make any sense.
302   // Make sure to evaluate VLA bounds now so that we have them for later.
303   if (D.getType()->isVariablyModifiedType())
304     EmitVariablyModifiedType(D.getType());
305 
306   // Save the type in case adding the initializer forces a type change.
307   llvm::Type *expectedType = addr->getType();
308 
309   // If this value has an initializer, emit it.
310   if (D.getInit())
311     var = AddInitializerToStaticVarDecl(D, var);
312 
313   var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
314 
315   if (D.hasAttr<AnnotateAttr>())
316     CGM.AddGlobalAnnotations(&D, var);
317 
318   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
319     var->setSection(SA->getName());
320 
321   if (D.hasAttr<UsedAttr>())
322     CGM.AddUsedGlobal(var);
323 
324   // We may have to cast the constant because of the initializer
325   // mismatch above.
326   //
327   // FIXME: It is really dangerous to store this in the map; if anyone
328   // RAUW's the GV uses of this constant will be invalid.
329   llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
330   DMEntry = castedAddr;
331   CGM.setStaticLocalDeclAddress(&D, castedAddr);
332 
333   // Emit global variable debug descriptor for static vars.
334   CGDebugInfo *DI = getDebugInfo();
335   if (DI &&
336       CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
337     DI->setLocation(D.getLocation());
338     DI->EmitGlobalVariable(var, &D);
339   }
340 }
341 
342 namespace {
343   struct DestroyObject : EHScopeStack::Cleanup {
344     DestroyObject(llvm::Value *addr, QualType type,
345                   CodeGenFunction::Destroyer *destroyer,
346                   bool useEHCleanupForArray)
347       : addr(addr), type(type), destroyer(destroyer),
348         useEHCleanupForArray(useEHCleanupForArray) {}
349 
350     llvm::Value *addr;
351     QualType type;
352     CodeGenFunction::Destroyer *destroyer;
353     bool useEHCleanupForArray;
354 
355     void Emit(CodeGenFunction &CGF, Flags flags) {
356       // Don't use an EH cleanup recursively from an EH cleanup.
357       bool useEHCleanupForArray =
358         flags.isForNormalCleanup() && this->useEHCleanupForArray;
359 
360       CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
361     }
362   };
363 
364   struct DestroyNRVOVariable : EHScopeStack::Cleanup {
365     DestroyNRVOVariable(llvm::Value *addr,
366                         const CXXDestructorDecl *Dtor,
367                         llvm::Value *NRVOFlag)
368       : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
369 
370     const CXXDestructorDecl *Dtor;
371     llvm::Value *NRVOFlag;
372     llvm::Value *Loc;
373 
374     void Emit(CodeGenFunction &CGF, Flags flags) {
375       // Along the exceptions path we always execute the dtor.
376       bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
377 
378       llvm::BasicBlock *SkipDtorBB = 0;
379       if (NRVO) {
380         // If we exited via NRVO, we skip the destructor call.
381         llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
382         SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
383         llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
384         CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
385         CGF.EmitBlock(RunDtorBB);
386       }
387 
388       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
389                                 /*ForVirtualBase=*/false, Loc);
390 
391       if (NRVO) CGF.EmitBlock(SkipDtorBB);
392     }
393   };
394 
395   struct CallStackRestore : EHScopeStack::Cleanup {
396     llvm::Value *Stack;
397     CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
398     void Emit(CodeGenFunction &CGF, Flags flags) {
399       llvm::Value *V = CGF.Builder.CreateLoad(Stack);
400       llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
401       CGF.Builder.CreateCall(F, V);
402     }
403   };
404 
405   struct ExtendGCLifetime : EHScopeStack::Cleanup {
406     const VarDecl &Var;
407     ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
408 
409     void Emit(CodeGenFunction &CGF, Flags flags) {
410       // Compute the address of the local variable, in case it's a
411       // byref or something.
412       DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
413                       Var.getType(), VK_LValue, SourceLocation());
414       llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
415       CGF.EmitExtendGCLifetime(value);
416     }
417   };
418 
419   struct CallCleanupFunction : EHScopeStack::Cleanup {
420     llvm::Constant *CleanupFn;
421     const CGFunctionInfo &FnInfo;
422     const VarDecl &Var;
423 
424     CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
425                         const VarDecl *Var)
426       : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
427 
428     void Emit(CodeGenFunction &CGF, Flags flags) {
429       DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
430                       Var.getType(), VK_LValue, SourceLocation());
431       // Compute the address of the local variable, in case it's a byref
432       // or something.
433       llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
434 
435       // In some cases, the type of the function argument will be different from
436       // the type of the pointer. An example of this is
437       // void f(void* arg);
438       // __attribute__((cleanup(f))) void *g;
439       //
440       // To fix this we insert a bitcast here.
441       QualType ArgTy = FnInfo.arg_begin()->type;
442       llvm::Value *Arg =
443         CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
444 
445       CallArgList Args;
446       Args.add(RValue::get(Arg),
447                CGF.getContext().getPointerType(Var.getType()));
448       CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
449     }
450   };
451 }
452 
453 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
454 /// variable with lifetime.
455 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
456                                     llvm::Value *addr,
457                                     Qualifiers::ObjCLifetime lifetime) {
458   switch (lifetime) {
459   case Qualifiers::OCL_None:
460     llvm_unreachable("present but none");
461 
462   case Qualifiers::OCL_ExplicitNone:
463     // nothing to do
464     break;
465 
466   case Qualifiers::OCL_Strong: {
467     CodeGenFunction::Destroyer *destroyer =
468       (var.hasAttr<ObjCPreciseLifetimeAttr>()
469        ? CodeGenFunction::destroyARCStrongPrecise
470        : CodeGenFunction::destroyARCStrongImprecise);
471 
472     CleanupKind cleanupKind = CGF.getARCCleanupKind();
473     CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
474                     cleanupKind & EHCleanup);
475     break;
476   }
477   case Qualifiers::OCL_Autoreleasing:
478     // nothing to do
479     break;
480 
481   case Qualifiers::OCL_Weak:
482     // __weak objects always get EH cleanups; otherwise, exceptions
483     // could cause really nasty crashes instead of mere leaks.
484     CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
485                     CodeGenFunction::destroyARCWeak,
486                     /*useEHCleanup*/ true);
487     break;
488   }
489 }
490 
491 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
492   if (const Expr *e = dyn_cast<Expr>(s)) {
493     // Skip the most common kinds of expressions that make
494     // hierarchy-walking expensive.
495     s = e = e->IgnoreParenCasts();
496 
497     if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
498       return (ref->getDecl() == &var);
499     if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
500       const BlockDecl *block = be->getBlockDecl();
501       for (BlockDecl::capture_const_iterator i = block->capture_begin(),
502            e = block->capture_end(); i != e; ++i) {
503         if (i->getVariable() == &var)
504           return true;
505       }
506     }
507   }
508 
509   for (Stmt::const_child_range children = s->children(); children; ++children)
510     // children might be null; as in missing decl or conditional of an if-stmt.
511     if ((*children) && isAccessedBy(var, *children))
512       return true;
513 
514   return false;
515 }
516 
517 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
518   if (!decl) return false;
519   if (!isa<VarDecl>(decl)) return false;
520   const VarDecl *var = cast<VarDecl>(decl);
521   return isAccessedBy(*var, e);
522 }
523 
524 static void drillIntoBlockVariable(CodeGenFunction &CGF,
525                                    LValue &lvalue,
526                                    const VarDecl *var) {
527   lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
528 }
529 
530 void CodeGenFunction::EmitScalarInit(const Expr *init,
531                                      const ValueDecl *D,
532                                      LValue lvalue,
533                                      bool capturedByInit) {
534   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
535   if (!lifetime) {
536     llvm::Value *value = EmitScalarExpr(init);
537     if (capturedByInit)
538       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
539     EmitStoreThroughLValue(RValue::get(value), lvalue, true);
540     return;
541   }
542 
543   // If we're emitting a value with lifetime, we have to do the
544   // initialization *before* we leave the cleanup scopes.
545   if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
546     enterFullExpression(ewc);
547     init = ewc->getSubExpr();
548   }
549   CodeGenFunction::RunCleanupsScope Scope(*this);
550 
551   // We have to maintain the illusion that the variable is
552   // zero-initialized.  If the variable might be accessed in its
553   // initializer, zero-initialize before running the initializer, then
554   // actually perform the initialization with an assign.
555   bool accessedByInit = false;
556   if (lifetime != Qualifiers::OCL_ExplicitNone)
557     accessedByInit = (capturedByInit || isAccessedBy(D, init));
558   if (accessedByInit) {
559     LValue tempLV = lvalue;
560     // Drill down to the __block object if necessary.
561     if (capturedByInit) {
562       // We can use a simple GEP for this because it can't have been
563       // moved yet.
564       tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
565                                    getByRefValueLLVMField(cast<VarDecl>(D))));
566     }
567 
568     llvm::PointerType *ty
569       = cast<llvm::PointerType>(tempLV.getAddress()->getType());
570     ty = cast<llvm::PointerType>(ty->getElementType());
571 
572     llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
573 
574     // If __weak, we want to use a barrier under certain conditions.
575     if (lifetime == Qualifiers::OCL_Weak)
576       EmitARCInitWeak(tempLV.getAddress(), zero);
577 
578     // Otherwise just do a simple store.
579     else
580       EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
581   }
582 
583   // Emit the initializer.
584   llvm::Value *value = 0;
585 
586   switch (lifetime) {
587   case Qualifiers::OCL_None:
588     llvm_unreachable("present but none");
589 
590   case Qualifiers::OCL_ExplicitNone:
591     // nothing to do
592     value = EmitScalarExpr(init);
593     break;
594 
595   case Qualifiers::OCL_Strong: {
596     value = EmitARCRetainScalarExpr(init);
597     break;
598   }
599 
600   case Qualifiers::OCL_Weak: {
601     // No way to optimize a producing initializer into this.  It's not
602     // worth optimizing for, because the value will immediately
603     // disappear in the common case.
604     value = EmitScalarExpr(init);
605 
606     if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
607     if (accessedByInit)
608       EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
609     else
610       EmitARCInitWeak(lvalue.getAddress(), value);
611     return;
612   }
613 
614   case Qualifiers::OCL_Autoreleasing:
615     value = EmitARCRetainAutoreleaseScalarExpr(init);
616     break;
617   }
618 
619   if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
620 
621   // If the variable might have been accessed by its initializer, we
622   // might have to initialize with a barrier.  We have to do this for
623   // both __weak and __strong, but __weak got filtered out above.
624   if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
625     llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
626     EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
627     EmitARCRelease(oldValue, /*precise*/ false);
628     return;
629   }
630 
631   EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
632 }
633 
634 /// EmitScalarInit - Initialize the given lvalue with the given object.
635 void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
636   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
637   if (!lifetime)
638     return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
639 
640   switch (lifetime) {
641   case Qualifiers::OCL_None:
642     llvm_unreachable("present but none");
643 
644   case Qualifiers::OCL_ExplicitNone:
645     // nothing to do
646     break;
647 
648   case Qualifiers::OCL_Strong:
649     init = EmitARCRetain(lvalue.getType(), init);
650     break;
651 
652   case Qualifiers::OCL_Weak:
653     // Initialize and then skip the primitive store.
654     EmitARCInitWeak(lvalue.getAddress(), init);
655     return;
656 
657   case Qualifiers::OCL_Autoreleasing:
658     init = EmitARCRetainAutorelease(lvalue.getType(), init);
659     break;
660   }
661 
662   EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
663 }
664 
665 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
666 /// non-zero parts of the specified initializer with equal or fewer than
667 /// NumStores scalar stores.
668 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
669                                                 unsigned &NumStores) {
670   // Zero and Undef never requires any extra stores.
671   if (isa<llvm::ConstantAggregateZero>(Init) ||
672       isa<llvm::ConstantPointerNull>(Init) ||
673       isa<llvm::UndefValue>(Init))
674     return true;
675   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
676       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
677       isa<llvm::ConstantExpr>(Init))
678     return Init->isNullValue() || NumStores--;
679 
680   // See if we can emit each element.
681   if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
682     for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
683       llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
684       if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
685         return false;
686     }
687     return true;
688   }
689 
690   if (llvm::ConstantDataSequential *CDS =
691         dyn_cast<llvm::ConstantDataSequential>(Init)) {
692     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
693       llvm::Constant *Elt = CDS->getElementAsConstant(i);
694       if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
695         return false;
696     }
697     return true;
698   }
699 
700   // Anything else is hard and scary.
701   return false;
702 }
703 
704 /// emitStoresForInitAfterMemset - For inits that
705 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
706 /// stores that would be required.
707 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
708                                          bool isVolatile, CGBuilderTy &Builder) {
709   assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
710          "called emitStoresForInitAfterMemset for zero or undef value.");
711 
712   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
713       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
714       isa<llvm::ConstantExpr>(Init)) {
715     Builder.CreateStore(Init, Loc, isVolatile);
716     return;
717   }
718 
719   if (llvm::ConstantDataSequential *CDS =
720         dyn_cast<llvm::ConstantDataSequential>(Init)) {
721     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
722       llvm::Constant *Elt = CDS->getElementAsConstant(i);
723 
724       // If necessary, get a pointer to the element and emit it.
725       if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
726         emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
727                                      isVolatile, Builder);
728     }
729     return;
730   }
731 
732   assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
733          "Unknown value type!");
734 
735   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
736     llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
737 
738     // If necessary, get a pointer to the element and emit it.
739     if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
740       emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
741                                    isVolatile, Builder);
742   }
743 }
744 
745 
746 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
747 /// plus some stores to initialize a local variable instead of using a memcpy
748 /// from a constant global.  It is beneficial to use memset if the global is all
749 /// zeros, or mostly zeros and large.
750 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
751                                                   uint64_t GlobalSize) {
752   // If a global is all zeros, always use a memset.
753   if (isa<llvm::ConstantAggregateZero>(Init)) return true;
754 
755 
756   // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
757   // do it if it will require 6 or fewer scalar stores.
758   // TODO: Should budget depends on the size?  Avoiding a large global warrants
759   // plopping in more stores.
760   unsigned StoreBudget = 6;
761   uint64_t SizeLimit = 32;
762 
763   return GlobalSize > SizeLimit &&
764          canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
765 }
766 
767 
768 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
769 /// variable declaration with auto, register, or no storage class specifier.
770 /// These turn into simple stack objects, or GlobalValues depending on target.
771 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
772   AutoVarEmission emission = EmitAutoVarAlloca(D);
773   EmitAutoVarInit(emission);
774   EmitAutoVarCleanups(emission);
775 }
776 
777 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
778 /// local variable.  Does not emit initalization or destruction.
779 CodeGenFunction::AutoVarEmission
780 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
781   QualType Ty = D.getType();
782 
783   AutoVarEmission emission(D);
784 
785   bool isByRef = D.hasAttr<BlocksAttr>();
786   emission.IsByRef = isByRef;
787 
788   CharUnits alignment = getContext().getDeclAlign(&D);
789   emission.Alignment = alignment;
790 
791   // If the type is variably-modified, emit all the VLA sizes for it.
792   if (Ty->isVariablyModifiedType())
793     EmitVariablyModifiedType(Ty);
794 
795   llvm::Value *DeclPtr;
796   if (Ty->isConstantSizeType()) {
797     if (!Target.useGlobalsForAutomaticVariables()) {
798       bool NRVO = getLangOpts().ElideConstructors &&
799                   D.isNRVOVariable();
800 
801       // If this value is a POD array or struct with a statically
802       // determinable constant initializer, there are optimizations we can do.
803       //
804       // TODO: We should constant-evaluate the initializer of any variable,
805       // as long as it is initialized by a constant expression. Currently,
806       // isConstantInitializer produces wrong answers for structs with
807       // reference or bitfield members, and a few other cases, and checking
808       // for POD-ness protects us from some of these.
809       if (D.getInit() &&
810           (Ty->isArrayType() || Ty->isRecordType()) &&
811           (Ty.isPODType(getContext()) ||
812            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
813           D.getInit()->isConstantInitializer(getContext(), false)) {
814 
815         // If the variable's a const type, and it's neither an NRVO
816         // candidate nor a __block variable and has no mutable members,
817         // emit it as a global instead.
818         if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
819             CGM.isTypeConstant(Ty, true)) {
820           EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
821 
822           emission.Address = 0; // signal this condition to later callbacks
823           assert(emission.wasEmittedAsGlobal());
824           return emission;
825         }
826 
827         // Otherwise, tell the initialization code that we're in this case.
828         emission.IsConstantAggregate = true;
829       }
830 
831       // A normal fixed sized variable becomes an alloca in the entry block,
832       // unless it's an NRVO variable.
833       llvm::Type *LTy = ConvertTypeForMem(Ty);
834 
835       if (NRVO) {
836         // The named return value optimization: allocate this variable in the
837         // return slot, so that we can elide the copy when returning this
838         // variable (C++0x [class.copy]p34).
839         DeclPtr = ReturnValue;
840 
841         if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
842           if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
843             // Create a flag that is used to indicate when the NRVO was applied
844             // to this variable. Set it to zero to indicate that NRVO was not
845             // applied.
846             llvm::Value *Zero = Builder.getFalse();
847             llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
848             EnsureInsertPoint();
849             Builder.CreateStore(Zero, NRVOFlag);
850 
851             // Record the NRVO flag for this variable.
852             NRVOFlags[&D] = NRVOFlag;
853             emission.NRVOFlag = NRVOFlag;
854           }
855         }
856       } else {
857         if (isByRef)
858           LTy = BuildByRefType(&D);
859 
860         llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
861         Alloc->setName(D.getName());
862 
863         CharUnits allocaAlignment = alignment;
864         if (isByRef)
865           allocaAlignment = std::max(allocaAlignment,
866               getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
867         Alloc->setAlignment(allocaAlignment.getQuantity());
868         DeclPtr = Alloc;
869       }
870     } else {
871       // Targets that don't support recursion emit locals as globals.
872       const char *Class =
873         D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
874       DeclPtr = CreateStaticVarDecl(D, Class,
875                                     llvm::GlobalValue::InternalLinkage);
876     }
877   } else {
878     EnsureInsertPoint();
879 
880     if (!DidCallStackSave) {
881       // Save the stack.
882       llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
883 
884       llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
885       llvm::Value *V = Builder.CreateCall(F);
886 
887       Builder.CreateStore(V, Stack);
888 
889       DidCallStackSave = true;
890 
891       // Push a cleanup block and restore the stack there.
892       // FIXME: in general circumstances, this should be an EH cleanup.
893       EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
894     }
895 
896     llvm::Value *elementCount;
897     QualType elementType;
898     llvm::tie(elementCount, elementType) = getVLASize(Ty);
899 
900     llvm::Type *llvmTy = ConvertTypeForMem(elementType);
901 
902     // Allocate memory for the array.
903     llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
904     vla->setAlignment(alignment.getQuantity());
905 
906     DeclPtr = vla;
907   }
908 
909   llvm::Value *&DMEntry = LocalDeclMap[&D];
910   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
911   DMEntry = DeclPtr;
912   emission.Address = DeclPtr;
913 
914   // Emit debug info for local var declaration.
915   if (HaveInsertPoint())
916     if (CGDebugInfo *DI = getDebugInfo()) {
917       if (CGM.getCodeGenOpts().getDebugInfo()
918             >= CodeGenOptions::LimitedDebugInfo) {
919         DI->setLocation(D.getLocation());
920         if (Target.useGlobalsForAutomaticVariables()) {
921           DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr),
922                                  &D);
923         } else
924           DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
925       }
926     }
927 
928   if (D.hasAttr<AnnotateAttr>())
929       EmitVarAnnotations(&D, emission.Address);
930 
931   return emission;
932 }
933 
934 /// Determines whether the given __block variable is potentially
935 /// captured by the given expression.
936 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
937   // Skip the most common kinds of expressions that make
938   // hierarchy-walking expensive.
939   e = e->IgnoreParenCasts();
940 
941   if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
942     const BlockDecl *block = be->getBlockDecl();
943     for (BlockDecl::capture_const_iterator i = block->capture_begin(),
944            e = block->capture_end(); i != e; ++i) {
945       if (i->getVariable() == &var)
946         return true;
947     }
948 
949     // No need to walk into the subexpressions.
950     return false;
951   }
952 
953   if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
954     const CompoundStmt *CS = SE->getSubStmt();
955     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
956 	   BE = CS->body_end(); BI != BE; ++BI)
957       if (Expr *E = dyn_cast<Expr>((*BI))) {
958         if (isCapturedBy(var, E))
959             return true;
960       }
961       else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
962           // special case declarations
963           for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
964                I != E; ++I) {
965               if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
966                 Expr *Init = VD->getInit();
967                 if (Init && isCapturedBy(var, Init))
968                   return true;
969               }
970           }
971       }
972       else
973         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
974         // Later, provide code to poke into statements for capture analysis.
975         return true;
976     return false;
977   }
978 
979   for (Stmt::const_child_range children = e->children(); children; ++children)
980     if (isCapturedBy(var, cast<Expr>(*children)))
981       return true;
982 
983   return false;
984 }
985 
986 /// \brief Determine whether the given initializer is trivial in the sense
987 /// that it requires no code to be generated.
988 static bool isTrivialInitializer(const Expr *Init) {
989   if (!Init)
990     return true;
991 
992   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
993     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
994       if (Constructor->isTrivial() &&
995           Constructor->isDefaultConstructor() &&
996           !Construct->requiresZeroInitialization())
997         return true;
998 
999   return false;
1000 }
1001 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1002   assert(emission.Variable && "emission was not valid!");
1003 
1004   // If this was emitted as a global constant, we're done.
1005   if (emission.wasEmittedAsGlobal()) return;
1006 
1007   const VarDecl &D = *emission.Variable;
1008   QualType type = D.getType();
1009 
1010   // If this local has an initializer, emit it now.
1011   const Expr *Init = D.getInit();
1012 
1013   // If we are at an unreachable point, we don't need to emit the initializer
1014   // unless it contains a label.
1015   if (!HaveInsertPoint()) {
1016     if (!Init || !ContainsLabel(Init)) return;
1017     EnsureInsertPoint();
1018   }
1019 
1020   // Initialize the structure of a __block variable.
1021   if (emission.IsByRef)
1022     emitByrefStructureInit(emission);
1023 
1024   if (isTrivialInitializer(Init))
1025     return;
1026 
1027   CharUnits alignment = emission.Alignment;
1028 
1029   // Check whether this is a byref variable that's potentially
1030   // captured and moved by its own initializer.  If so, we'll need to
1031   // emit the initializer first, then copy into the variable.
1032   bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1033 
1034   llvm::Value *Loc =
1035     capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1036 
1037   llvm::Constant *constant = 0;
1038   if (emission.IsConstantAggregate) {
1039     assert(!capturedByInit && "constant init contains a capturing block?");
1040     constant = CGM.EmitConstantInit(D, this);
1041   }
1042 
1043   if (!constant) {
1044     LValue lv = MakeAddrLValue(Loc, type, alignment);
1045     lv.setNonGC(true);
1046     return EmitExprAsInit(Init, &D, lv, capturedByInit);
1047   }
1048 
1049   // If this is a simple aggregate initialization, we can optimize it
1050   // in various ways.
1051   bool isVolatile = type.isVolatileQualified();
1052 
1053   llvm::Value *SizeVal =
1054     llvm::ConstantInt::get(IntPtrTy,
1055                            getContext().getTypeSizeInChars(type).getQuantity());
1056 
1057   llvm::Type *BP = Int8PtrTy;
1058   if (Loc->getType() != BP)
1059     Loc = Builder.CreateBitCast(Loc, BP);
1060 
1061   // If the initializer is all or mostly zeros, codegen with memset then do
1062   // a few stores afterward.
1063   if (shouldUseMemSetPlusStoresToInitialize(constant,
1064                 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1065     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1066                          alignment.getQuantity(), isVolatile);
1067     // Zero and undef don't require a stores.
1068     if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1069       Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1070       emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
1071     }
1072   } else {
1073     // Otherwise, create a temporary global with the initializer then
1074     // memcpy from the global to the alloca.
1075     std::string Name = GetStaticDeclName(*this, D, ".");
1076     llvm::GlobalVariable *GV =
1077       new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1078                                llvm::GlobalValue::PrivateLinkage,
1079                                constant, Name);
1080     GV->setAlignment(alignment.getQuantity());
1081     GV->setUnnamedAddr(true);
1082 
1083     llvm::Value *SrcPtr = GV;
1084     if (SrcPtr->getType() != BP)
1085       SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1086 
1087     Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1088                          isVolatile);
1089   }
1090 }
1091 
1092 /// Emit an expression as an initializer for a variable at the given
1093 /// location.  The expression is not necessarily the normal
1094 /// initializer for the variable, and the address is not necessarily
1095 /// its normal location.
1096 ///
1097 /// \param init the initializing expression
1098 /// \param var the variable to act as if we're initializing
1099 /// \param loc the address to initialize; its type is a pointer
1100 ///   to the LLVM mapping of the variable's type
1101 /// \param alignment the alignment of the address
1102 /// \param capturedByInit true if the variable is a __block variable
1103 ///   whose address is potentially changed by the initializer
1104 void CodeGenFunction::EmitExprAsInit(const Expr *init,
1105                                      const ValueDecl *D,
1106                                      LValue lvalue,
1107                                      bool capturedByInit) {
1108   QualType type = D->getType();
1109 
1110   if (type->isReferenceType()) {
1111     RValue rvalue = EmitReferenceBindingToExpr(init, D);
1112     if (capturedByInit)
1113       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1114     EmitStoreThroughLValue(rvalue, lvalue, true);
1115   } else if (!hasAggregateLLVMType(type)) {
1116     EmitScalarInit(init, D, lvalue, capturedByInit);
1117   } else if (type->isAnyComplexType()) {
1118     ComplexPairTy complex = EmitComplexExpr(init);
1119     if (capturedByInit)
1120       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1121     StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
1122   } else {
1123     // TODO: how can we delay here if D is captured by its initializer?
1124     EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1125                                               AggValueSlot::IsDestructed,
1126                                          AggValueSlot::DoesNotNeedGCBarriers,
1127                                               AggValueSlot::IsNotAliased));
1128     MaybeEmitStdInitializerListCleanup(lvalue.getAddress(), init);
1129   }
1130 }
1131 
1132 /// Enter a destroy cleanup for the given local variable.
1133 void CodeGenFunction::emitAutoVarTypeCleanup(
1134                             const CodeGenFunction::AutoVarEmission &emission,
1135                             QualType::DestructionKind dtorKind) {
1136   assert(dtorKind != QualType::DK_none);
1137 
1138   // Note that for __block variables, we want to destroy the
1139   // original stack object, not the possibly forwarded object.
1140   llvm::Value *addr = emission.getObjectAddress(*this);
1141 
1142   const VarDecl *var = emission.Variable;
1143   QualType type = var->getType();
1144 
1145   CleanupKind cleanupKind = NormalAndEHCleanup;
1146   CodeGenFunction::Destroyer *destroyer = 0;
1147 
1148   switch (dtorKind) {
1149   case QualType::DK_none:
1150     llvm_unreachable("no cleanup for trivially-destructible variable");
1151 
1152   case QualType::DK_cxx_destructor:
1153     // If there's an NRVO flag on the emission, we need a different
1154     // cleanup.
1155     if (emission.NRVOFlag) {
1156       assert(!type->isArrayType());
1157       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1158       EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1159                                                emission.NRVOFlag);
1160       return;
1161     }
1162     break;
1163 
1164   case QualType::DK_objc_strong_lifetime:
1165     // Suppress cleanups for pseudo-strong variables.
1166     if (var->isARCPseudoStrong()) return;
1167 
1168     // Otherwise, consider whether to use an EH cleanup or not.
1169     cleanupKind = getARCCleanupKind();
1170 
1171     // Use the imprecise destroyer by default.
1172     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1173       destroyer = CodeGenFunction::destroyARCStrongImprecise;
1174     break;
1175 
1176   case QualType::DK_objc_weak_lifetime:
1177     break;
1178   }
1179 
1180   // If we haven't chosen a more specific destroyer, use the default.
1181   if (!destroyer) destroyer = getDestroyer(dtorKind);
1182 
1183   // Use an EH cleanup in array destructors iff the destructor itself
1184   // is being pushed as an EH cleanup.
1185   bool useEHCleanup = (cleanupKind & EHCleanup);
1186   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1187                                      useEHCleanup);
1188 }
1189 
1190 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1191   assert(emission.Variable && "emission was not valid!");
1192 
1193   // If this was emitted as a global constant, we're done.
1194   if (emission.wasEmittedAsGlobal()) return;
1195 
1196   // If we don't have an insertion point, we're done.  Sema prevents
1197   // us from jumping into any of these scopes anyway.
1198   if (!HaveInsertPoint()) return;
1199 
1200   const VarDecl &D = *emission.Variable;
1201 
1202   // Check the type for a cleanup.
1203   if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1204     emitAutoVarTypeCleanup(emission, dtorKind);
1205 
1206   // In GC mode, honor objc_precise_lifetime.
1207   if (getLangOpts().getGC() != LangOptions::NonGC &&
1208       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1209     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1210   }
1211 
1212   // Handle the cleanup attribute.
1213   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1214     const FunctionDecl *FD = CA->getFunctionDecl();
1215 
1216     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1217     assert(F && "Could not find function!");
1218 
1219     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1220     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1221   }
1222 
1223   // If this is a block variable, call _Block_object_destroy
1224   // (on the unforwarded address).
1225   if (emission.IsByRef)
1226     enterByrefCleanup(emission);
1227 }
1228 
1229 CodeGenFunction::Destroyer *
1230 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1231   switch (kind) {
1232   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1233   case QualType::DK_cxx_destructor:
1234     return destroyCXXObject;
1235   case QualType::DK_objc_strong_lifetime:
1236     return destroyARCStrongPrecise;
1237   case QualType::DK_objc_weak_lifetime:
1238     return destroyARCWeak;
1239   }
1240   llvm_unreachable("Unknown DestructionKind");
1241 }
1242 
1243 /// pushDestroy - Push the standard destructor for the given type.
1244 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1245                                   llvm::Value *addr, QualType type) {
1246   assert(dtorKind && "cannot push destructor for trivial type");
1247 
1248   CleanupKind cleanupKind = getCleanupKind(dtorKind);
1249   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1250               cleanupKind & EHCleanup);
1251 }
1252 
1253 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
1254                                   QualType type, Destroyer *destroyer,
1255                                   bool useEHCleanupForArray) {
1256   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1257                                      destroyer, useEHCleanupForArray);
1258 }
1259 
1260 /// emitDestroy - Immediately perform the destruction of the given
1261 /// object.
1262 ///
1263 /// \param addr - the address of the object; a type*
1264 /// \param type - the type of the object; if an array type, all
1265 ///   objects are destroyed in reverse order
1266 /// \param destroyer - the function to call to destroy individual
1267 ///   elements
1268 /// \param useEHCleanupForArray - whether an EH cleanup should be
1269 ///   used when destroying array elements, in case one of the
1270 ///   destructions throws an exception
1271 void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
1272                                   Destroyer *destroyer,
1273                                   bool useEHCleanupForArray) {
1274   const ArrayType *arrayType = getContext().getAsArrayType(type);
1275   if (!arrayType)
1276     return destroyer(*this, addr, type);
1277 
1278   llvm::Value *begin = addr;
1279   llvm::Value *length = emitArrayLength(arrayType, type, begin);
1280 
1281   // Normally we have to check whether the array is zero-length.
1282   bool checkZeroLength = true;
1283 
1284   // But if the array length is constant, we can suppress that.
1285   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1286     // ...and if it's constant zero, we can just skip the entire thing.
1287     if (constLength->isZero()) return;
1288     checkZeroLength = false;
1289   }
1290 
1291   llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1292   emitArrayDestroy(begin, end, type, destroyer,
1293                    checkZeroLength, useEHCleanupForArray);
1294 }
1295 
1296 /// emitArrayDestroy - Destroys all the elements of the given array,
1297 /// beginning from last to first.  The array cannot be zero-length.
1298 ///
1299 /// \param begin - a type* denoting the first element of the array
1300 /// \param end - a type* denoting one past the end of the array
1301 /// \param type - the element type of the array
1302 /// \param destroyer - the function to call to destroy elements
1303 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1304 ///   the remaining elements in case the destruction of a single
1305 ///   element throws
1306 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1307                                        llvm::Value *end,
1308                                        QualType type,
1309                                        Destroyer *destroyer,
1310                                        bool checkZeroLength,
1311                                        bool useEHCleanup) {
1312   assert(!type->isArrayType());
1313 
1314   // The basic structure here is a do-while loop, because we don't
1315   // need to check for the zero-element case.
1316   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1317   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1318 
1319   if (checkZeroLength) {
1320     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1321                                                 "arraydestroy.isempty");
1322     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1323   }
1324 
1325   // Enter the loop body, making that address the current address.
1326   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1327   EmitBlock(bodyBB);
1328   llvm::PHINode *elementPast =
1329     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1330   elementPast->addIncoming(end, entryBB);
1331 
1332   // Shift the address back by one element.
1333   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1334   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1335                                                    "arraydestroy.element");
1336 
1337   if (useEHCleanup)
1338     pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1339 
1340   // Perform the actual destruction there.
1341   destroyer(*this, element, type);
1342 
1343   if (useEHCleanup)
1344     PopCleanupBlock();
1345 
1346   // Check whether we've reached the end.
1347   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1348   Builder.CreateCondBr(done, doneBB, bodyBB);
1349   elementPast->addIncoming(element, Builder.GetInsertBlock());
1350 
1351   // Done.
1352   EmitBlock(doneBB);
1353 }
1354 
1355 /// Perform partial array destruction as if in an EH cleanup.  Unlike
1356 /// emitArrayDestroy, the element type here may still be an array type.
1357 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1358                                     llvm::Value *begin, llvm::Value *end,
1359                                     QualType type,
1360                                     CodeGenFunction::Destroyer *destroyer) {
1361   // If the element type is itself an array, drill down.
1362   unsigned arrayDepth = 0;
1363   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1364     // VLAs don't require a GEP index to walk into.
1365     if (!isa<VariableArrayType>(arrayType))
1366       arrayDepth++;
1367     type = arrayType->getElementType();
1368   }
1369 
1370   if (arrayDepth) {
1371     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1372 
1373     SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
1374     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1375     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1376   }
1377 
1378   // Destroy the array.  We don't ever need an EH cleanup because we
1379   // assume that we're in an EH cleanup ourselves, so a throwing
1380   // destructor causes an immediate terminate.
1381   CGF.emitArrayDestroy(begin, end, type, destroyer,
1382                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1383 }
1384 
1385 namespace {
1386   /// RegularPartialArrayDestroy - a cleanup which performs a partial
1387   /// array destroy where the end pointer is regularly determined and
1388   /// does not need to be loaded from a local.
1389   class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1390     llvm::Value *ArrayBegin;
1391     llvm::Value *ArrayEnd;
1392     QualType ElementType;
1393     CodeGenFunction::Destroyer *Destroyer;
1394   public:
1395     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1396                                QualType elementType,
1397                                CodeGenFunction::Destroyer *destroyer)
1398       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1399         ElementType(elementType), Destroyer(destroyer) {}
1400 
1401     void Emit(CodeGenFunction &CGF, Flags flags) {
1402       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1403                               ElementType, Destroyer);
1404     }
1405   };
1406 
1407   /// IrregularPartialArrayDestroy - a cleanup which performs a
1408   /// partial array destroy where the end pointer is irregularly
1409   /// determined and must be loaded from a local.
1410   class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
1411     llvm::Value *ArrayBegin;
1412     llvm::Value *ArrayEndPointer;
1413     QualType ElementType;
1414     CodeGenFunction::Destroyer *Destroyer;
1415   public:
1416     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1417                                  llvm::Value *arrayEndPointer,
1418                                  QualType elementType,
1419                                  CodeGenFunction::Destroyer *destroyer)
1420       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1421         ElementType(elementType), Destroyer(destroyer) {}
1422 
1423     void Emit(CodeGenFunction &CGF, Flags flags) {
1424       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1425       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1426                               ElementType, Destroyer);
1427     }
1428   };
1429 }
1430 
1431 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1432 /// already-constructed elements of the given array.  The cleanup
1433 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1434 ///
1435 /// \param elementType - the immediate element type of the array;
1436 ///   possibly still an array type
1437 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1438                                                  llvm::Value *arrayEndPointer,
1439                                                        QualType elementType,
1440                                                        Destroyer *destroyer) {
1441   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1442                                                     arrayBegin, arrayEndPointer,
1443                                                     elementType, destroyer);
1444 }
1445 
1446 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1447 /// already-constructed elements of the given array.  The cleanup
1448 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1449 ///
1450 /// \param elementType - the immediate element type of the array;
1451 ///   possibly still an array type
1452 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1453                                                      llvm::Value *arrayEnd,
1454                                                      QualType elementType,
1455                                                      Destroyer *destroyer) {
1456   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1457                                                   arrayBegin, arrayEnd,
1458                                                   elementType, destroyer);
1459 }
1460 
1461 namespace {
1462   /// A cleanup to perform a release of an object at the end of a
1463   /// function.  This is used to balance out the incoming +1 of a
1464   /// ns_consumed argument when we can't reasonably do that just by
1465   /// not doing the initial retain for a __block argument.
1466   struct ConsumeARCParameter : EHScopeStack::Cleanup {
1467     ConsumeARCParameter(llvm::Value *param) : Param(param) {}
1468 
1469     llvm::Value *Param;
1470 
1471     void Emit(CodeGenFunction &CGF, Flags flags) {
1472       CGF.EmitARCRelease(Param, /*precise*/ false);
1473     }
1474   };
1475 }
1476 
1477 /// Emit an alloca (or GlobalValue depending on target)
1478 /// for the specified parameter and set up LocalDeclMap.
1479 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1480                                    unsigned ArgNo) {
1481   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1482   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1483          "Invalid argument to EmitParmDecl");
1484 
1485   Arg->setName(D.getName());
1486 
1487   // Use better IR generation for certain implicit parameters.
1488   if (isa<ImplicitParamDecl>(D)) {
1489     // The only implicit argument a block has is its literal.
1490     if (BlockInfo) {
1491       LocalDeclMap[&D] = Arg;
1492 
1493       if (CGDebugInfo *DI = getDebugInfo()) {
1494         if (CGM.getCodeGenOpts().getDebugInfo()
1495               >= CodeGenOptions::LimitedDebugInfo) {
1496           DI->setLocation(D.getLocation());
1497           DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
1498         }
1499       }
1500 
1501       return;
1502     }
1503   }
1504 
1505   QualType Ty = D.getType();
1506 
1507   llvm::Value *DeclPtr;
1508   // If this is an aggregate or variable sized value, reuse the input pointer.
1509   if (!Ty->isConstantSizeType() ||
1510       CodeGenFunction::hasAggregateLLVMType(Ty)) {
1511     DeclPtr = Arg;
1512   } else {
1513     // Otherwise, create a temporary to hold the value.
1514     llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1515                                                D.getName() + ".addr");
1516     Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1517     DeclPtr = Alloc;
1518 
1519     bool doStore = true;
1520 
1521     Qualifiers qs = Ty.getQualifiers();
1522 
1523     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1524       // We honor __attribute__((ns_consumed)) for types with lifetime.
1525       // For __strong, it's handled by just skipping the initial retain;
1526       // otherwise we have to balance out the initial +1 with an extra
1527       // cleanup to do the release at the end of the function.
1528       bool isConsumed = D.hasAttr<NSConsumedAttr>();
1529 
1530       // 'self' is always formally __strong, but if this is not an
1531       // init method then we don't want to retain it.
1532       if (D.isARCPseudoStrong()) {
1533         const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1534         assert(&D == method->getSelfDecl());
1535         assert(lt == Qualifiers::OCL_Strong);
1536         assert(qs.hasConst());
1537         assert(method->getMethodFamily() != OMF_init);
1538         (void) method;
1539         lt = Qualifiers::OCL_ExplicitNone;
1540       }
1541 
1542       if (lt == Qualifiers::OCL_Strong) {
1543         if (!isConsumed)
1544           // Don't use objc_retainBlock for block pointers, because we
1545           // don't want to Block_copy something just because we got it
1546           // as a parameter.
1547           Arg = EmitARCRetainNonBlock(Arg);
1548       } else {
1549         // Push the cleanup for a consumed parameter.
1550         if (isConsumed)
1551           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
1552 
1553         if (lt == Qualifiers::OCL_Weak) {
1554           EmitARCInitWeak(DeclPtr, Arg);
1555           doStore = false; // The weak init is a store, no need to do two.
1556         }
1557       }
1558 
1559       // Enter the cleanup scope.
1560       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1561     }
1562 
1563     // Store the initial value into the alloca.
1564     if (doStore) {
1565       LValue lv = MakeAddrLValue(DeclPtr, Ty,
1566                                  getContext().getDeclAlign(&D));
1567       EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1568     }
1569   }
1570 
1571   llvm::Value *&DMEntry = LocalDeclMap[&D];
1572   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1573   DMEntry = DeclPtr;
1574 
1575   // Emit debug info for param declaration.
1576   if (CGDebugInfo *DI = getDebugInfo()) {
1577     if (CGM.getCodeGenOpts().getDebugInfo()
1578           >= CodeGenOptions::LimitedDebugInfo) {
1579       DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1580     }
1581   }
1582 
1583   if (D.hasAttr<AnnotateAttr>())
1584       EmitVarAnnotations(&D, DeclPtr);
1585 }
1586