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