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