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