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