1 //===--- CGCall.cpp - Encapsulate calling convention details ----*- C++ -*-===//
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 // These classes wrap the information about a call or function
11 // definition used to handle ABI compliancy.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "CGCall.h"
16 #include "CGCXXABI.h"
17 #include "ABIInfo.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/Attributes.h"
26 #include "llvm/Support/CallSite.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/InlineAsm.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 using namespace clang;
31 using namespace CodeGen;
32 
33 /***/
34 
35 static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
36   switch (CC) {
37   default: return llvm::CallingConv::C;
38   case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
39   case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
40   case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
41   case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
42   case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
43   // TODO: add support for CC_X86Pascal to llvm
44   }
45 }
46 
47 /// Derives the 'this' type for codegen purposes, i.e. ignoring method
48 /// qualification.
49 /// FIXME: address space qualification?
50 static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
51   QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
52   return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
53 }
54 
55 /// Returns the canonical formal type of the given C++ method.
56 static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
57   return MD->getType()->getCanonicalTypeUnqualified()
58            .getAs<FunctionProtoType>();
59 }
60 
61 /// Returns the "extra-canonicalized" return type, which discards
62 /// qualifiers on the return type.  Codegen doesn't care about them,
63 /// and it makes ABI code a little easier to be able to assume that
64 /// all parameter and return types are top-level unqualified.
65 static CanQualType GetReturnType(QualType RetTy) {
66   return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
67 }
68 
69 const CGFunctionInfo &
70 CodeGenTypes::getFunctionInfo(CanQual<FunctionNoProtoType> FTNP) {
71   return getFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
72                          SmallVector<CanQualType, 16>(),
73                          FTNP->getExtInfo());
74 }
75 
76 /// \param Args - contains any initial parameters besides those
77 ///   in the formal type
78 static const CGFunctionInfo &getFunctionInfo(CodeGenTypes &CGT,
79                                   SmallVectorImpl<CanQualType> &ArgTys,
80                                              CanQual<FunctionProtoType> FTP) {
81   // FIXME: Kill copy.
82   for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
83     ArgTys.push_back(FTP->getArgType(i));
84   CanQualType ResTy = FTP->getResultType().getUnqualifiedType();
85   return CGT.getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
86 }
87 
88 const CGFunctionInfo &
89 CodeGenTypes::getFunctionInfo(CanQual<FunctionProtoType> FTP) {
90   SmallVector<CanQualType, 16> ArgTys;
91   return ::getFunctionInfo(*this, ArgTys, FTP);
92 }
93 
94 static CallingConv getCallingConventionForDecl(const Decl *D) {
95   // Set the appropriate calling convention for the Function.
96   if (D->hasAttr<StdCallAttr>())
97     return CC_X86StdCall;
98 
99   if (D->hasAttr<FastCallAttr>())
100     return CC_X86FastCall;
101 
102   if (D->hasAttr<ThisCallAttr>())
103     return CC_X86ThisCall;
104 
105   if (D->hasAttr<PascalAttr>())
106     return CC_X86Pascal;
107 
108   if (PcsAttr *PCS = D->getAttr<PcsAttr>())
109     return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
110 
111   return CC_C;
112 }
113 
114 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXRecordDecl *RD,
115                                                  const FunctionProtoType *FTP) {
116   SmallVector<CanQualType, 16> ArgTys;
117 
118   // Add the 'this' pointer.
119   ArgTys.push_back(GetThisType(Context, RD));
120 
121   return ::getFunctionInfo(*this, ArgTys,
122               FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
123 }
124 
125 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) {
126   SmallVector<CanQualType, 16> ArgTys;
127 
128   assert(!isa<CXXConstructorDecl>(MD) && "wrong method for contructors!");
129   assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
130 
131   // Add the 'this' pointer unless this is a static method.
132   if (MD->isInstance())
133     ArgTys.push_back(GetThisType(Context, MD->getParent()));
134 
135   return ::getFunctionInfo(*this, ArgTys, GetFormalType(MD));
136 }
137 
138 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXConstructorDecl *D,
139                                                     CXXCtorType Type) {
140   SmallVector<CanQualType, 16> ArgTys;
141   ArgTys.push_back(GetThisType(Context, D->getParent()));
142   CanQualType ResTy = Context.VoidTy;
143 
144   TheCXXABI.BuildConstructorSignature(D, Type, ResTy, ArgTys);
145 
146   CanQual<FunctionProtoType> FTP = GetFormalType(D);
147 
148   // Add the formal parameters.
149   for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
150     ArgTys.push_back(FTP->getArgType(i));
151 
152   return getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
153 }
154 
155 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXDestructorDecl *D,
156                                                     CXXDtorType Type) {
157   SmallVector<CanQualType, 2> ArgTys;
158   ArgTys.push_back(GetThisType(Context, D->getParent()));
159   CanQualType ResTy = Context.VoidTy;
160 
161   TheCXXABI.BuildDestructorSignature(D, Type, ResTy, ArgTys);
162 
163   CanQual<FunctionProtoType> FTP = GetFormalType(D);
164   assert(FTP->getNumArgs() == 0 && "dtor with formal parameters");
165 
166   return getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
167 }
168 
169 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) {
170   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
171     if (MD->isInstance())
172       return getFunctionInfo(MD);
173 
174   CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
175   assert(isa<FunctionType>(FTy));
176   if (isa<FunctionNoProtoType>(FTy))
177     return getFunctionInfo(FTy.getAs<FunctionNoProtoType>());
178   assert(isa<FunctionProtoType>(FTy));
179   return getFunctionInfo(FTy.getAs<FunctionProtoType>());
180 }
181 
182 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) {
183   SmallVector<CanQualType, 16> ArgTys;
184   ArgTys.push_back(Context.getCanonicalParamType(MD->getSelfDecl()->getType()));
185   ArgTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
186   // FIXME: Kill copy?
187   for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(),
188          e = MD->param_end(); i != e; ++i) {
189     ArgTys.push_back(Context.getCanonicalParamType((*i)->getType()));
190   }
191 
192   FunctionType::ExtInfo einfo;
193   einfo = einfo.withCallingConv(getCallingConventionForDecl(MD));
194 
195   if (getContext().getLangOptions().ObjCAutoRefCount &&
196       MD->hasAttr<NSReturnsRetainedAttr>())
197     einfo = einfo.withProducesResult(true);
198 
199   return getFunctionInfo(GetReturnType(MD->getResultType()), ArgTys, einfo);
200 }
201 
202 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(GlobalDecl GD) {
203   // FIXME: Do we need to handle ObjCMethodDecl?
204   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
205 
206   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
207     return getFunctionInfo(CD, GD.getCtorType());
208 
209   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
210     return getFunctionInfo(DD, GD.getDtorType());
211 
212   return getFunctionInfo(FD);
213 }
214 
215 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
216                                                     const CallArgList &Args,
217                                             const FunctionType::ExtInfo &Info) {
218   // FIXME: Kill copy.
219   SmallVector<CanQualType, 16> ArgTys;
220   for (CallArgList::const_iterator i = Args.begin(), e = Args.end();
221        i != e; ++i)
222     ArgTys.push_back(Context.getCanonicalParamType(i->Ty));
223   return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
224 }
225 
226 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
227                                                     const FunctionArgList &Args,
228                                             const FunctionType::ExtInfo &Info) {
229   // FIXME: Kill copy.
230   SmallVector<CanQualType, 16> ArgTys;
231   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
232        i != e; ++i)
233     ArgTys.push_back(Context.getCanonicalParamType((*i)->getType()));
234   return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
235 }
236 
237 const CGFunctionInfo &CodeGenTypes::getNullaryFunctionInfo() {
238   SmallVector<CanQualType, 1> args;
239   return getFunctionInfo(getContext().VoidTy, args, FunctionType::ExtInfo());
240 }
241 
242 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(CanQualType ResTy,
243                            const SmallVectorImpl<CanQualType> &ArgTys,
244                                             const FunctionType::ExtInfo &Info) {
245 #ifndef NDEBUG
246   for (SmallVectorImpl<CanQualType>::const_iterator
247          I = ArgTys.begin(), E = ArgTys.end(); I != E; ++I)
248     assert(I->isCanonicalAsParam());
249 #endif
250 
251   unsigned CC = ClangCallConvToLLVMCallConv(Info.getCC());
252 
253   // Lookup or create unique function info.
254   llvm::FoldingSetNodeID ID;
255   CGFunctionInfo::Profile(ID, Info, ResTy, ArgTys.begin(), ArgTys.end());
256 
257   void *InsertPos = 0;
258   CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
259   if (FI)
260     return *FI;
261 
262   // Construct the function info.
263   FI = new CGFunctionInfo(CC, Info.getNoReturn(), Info.getProducesResult(),
264                           Info.getHasRegParm(), Info.getRegParm(), ResTy,
265                           ArgTys.data(), ArgTys.size());
266   FunctionInfos.InsertNode(FI, InsertPos);
267 
268   bool Inserted = FunctionsBeingProcessed.insert(FI); (void)Inserted;
269   assert(Inserted && "Recursively being processed?");
270 
271   // Compute ABI information.
272   getABIInfo().computeInfo(*FI);
273 
274   // Loop over all of the computed argument and return value info.  If any of
275   // them are direct or extend without a specified coerce type, specify the
276   // default now.
277   ABIArgInfo &RetInfo = FI->getReturnInfo();
278   if (RetInfo.canHaveCoerceToType() && RetInfo.getCoerceToType() == 0)
279     RetInfo.setCoerceToType(ConvertType(FI->getReturnType()));
280 
281   for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end();
282        I != E; ++I)
283     if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0)
284       I->info.setCoerceToType(ConvertType(I->type));
285 
286   bool Erased = FunctionsBeingProcessed.erase(FI); (void)Erased;
287   assert(Erased && "Not in set?");
288 
289   return *FI;
290 }
291 
292 CGFunctionInfo::CGFunctionInfo(unsigned _CallingConvention,
293                                bool _NoReturn, bool returnsRetained,
294                                bool _HasRegParm, unsigned _RegParm,
295                                CanQualType ResTy,
296                                const CanQualType *ArgTys,
297                                unsigned NumArgTys)
298   : CallingConvention(_CallingConvention),
299     EffectiveCallingConvention(_CallingConvention),
300     NoReturn(_NoReturn), ReturnsRetained(returnsRetained),
301     HasRegParm(_HasRegParm), RegParm(_RegParm)
302 {
303   NumArgs = NumArgTys;
304 
305   // FIXME: Coallocate with the CGFunctionInfo object.
306   Args = new ArgInfo[1 + NumArgTys];
307   Args[0].type = ResTy;
308   for (unsigned i = 0; i != NumArgTys; ++i)
309     Args[1 + i].type = ArgTys[i];
310 }
311 
312 /***/
313 
314 void CodeGenTypes::GetExpandedTypes(QualType type,
315                      SmallVectorImpl<llvm::Type*> &expandedTypes) {
316   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
317     uint64_t NumElts = AT->getSize().getZExtValue();
318     for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
319       GetExpandedTypes(AT->getElementType(), expandedTypes);
320   } else if (const RecordType *RT = type->getAsStructureType()) {
321     const RecordDecl *RD = RT->getDecl();
322     assert(!RD->hasFlexibleArrayMember() &&
323            "Cannot expand structure with flexible array.");
324     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
325          i != e; ++i) {
326       const FieldDecl *FD = *i;
327       assert(!FD->isBitField() &&
328              "Cannot expand structure with bit-field members.");
329       GetExpandedTypes(FD->getType(), expandedTypes);
330     }
331   } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
332     llvm::Type *EltTy = ConvertType(CT->getElementType());
333     expandedTypes.push_back(EltTy);
334     expandedTypes.push_back(EltTy);
335   } else
336     expandedTypes.push_back(ConvertType(type));
337 }
338 
339 llvm::Function::arg_iterator
340 CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
341                                     llvm::Function::arg_iterator AI) {
342   assert(LV.isSimple() &&
343          "Unexpected non-simple lvalue during struct expansion.");
344   llvm::Value *Addr = LV.getAddress();
345 
346   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
347     unsigned NumElts = AT->getSize().getZExtValue();
348     QualType EltTy = AT->getElementType();
349     for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
350       llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
351       LValue LV = MakeAddrLValue(EltAddr, EltTy);
352       AI = ExpandTypeFromArgs(EltTy, LV, AI);
353     }
354   } else if (const RecordType *RT = Ty->getAsStructureType()) {
355     RecordDecl *RD = RT->getDecl();
356     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
357          i != e; ++i) {
358       FieldDecl *FD = *i;
359       QualType FT = FD->getType();
360 
361       // FIXME: What are the right qualifiers here?
362       LValue LV = EmitLValueForField(Addr, FD, 0);
363       AI = ExpandTypeFromArgs(FT, LV, AI);
364     }
365   } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
366     QualType EltTy = CT->getElementType();
367     llvm::Value *RealAddr = Builder.CreateStructGEP(Addr, 0, "real");
368     EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
369     llvm::Value *ImagAddr = Builder.CreateStructGEP(Addr, 1, "imag");
370     EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
371   } else {
372     EmitStoreThroughLValue(RValue::get(AI), LV);
373     ++AI;
374   }
375 
376   return AI;
377 }
378 
379 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
380 /// accessing some number of bytes out of it, try to gep into the struct to get
381 /// at its inner goodness.  Dive as deep as possible without entering an element
382 /// with an in-memory size smaller than DstSize.
383 static llvm::Value *
384 EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
385                                    llvm::StructType *SrcSTy,
386                                    uint64_t DstSize, CodeGenFunction &CGF) {
387   // We can't dive into a zero-element struct.
388   if (SrcSTy->getNumElements() == 0) return SrcPtr;
389 
390   llvm::Type *FirstElt = SrcSTy->getElementType(0);
391 
392   // If the first elt is at least as large as what we're looking for, or if the
393   // first element is the same size as the whole struct, we can enter it.
394   uint64_t FirstEltSize =
395     CGF.CGM.getTargetData().getTypeAllocSize(FirstElt);
396   if (FirstEltSize < DstSize &&
397       FirstEltSize < CGF.CGM.getTargetData().getTypeAllocSize(SrcSTy))
398     return SrcPtr;
399 
400   // GEP into the first element.
401   SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
402 
403   // If the first element is a struct, recurse.
404   llvm::Type *SrcTy =
405     cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
406   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
407     return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
408 
409   return SrcPtr;
410 }
411 
412 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
413 /// are either integers or pointers.  This does a truncation of the value if it
414 /// is too large or a zero extension if it is too small.
415 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
416                                              llvm::Type *Ty,
417                                              CodeGenFunction &CGF) {
418   if (Val->getType() == Ty)
419     return Val;
420 
421   if (isa<llvm::PointerType>(Val->getType())) {
422     // If this is Pointer->Pointer avoid conversion to and from int.
423     if (isa<llvm::PointerType>(Ty))
424       return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
425 
426     // Convert the pointer to an integer so we can play with its width.
427     Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
428   }
429 
430   llvm::Type *DestIntTy = Ty;
431   if (isa<llvm::PointerType>(DestIntTy))
432     DestIntTy = CGF.IntPtrTy;
433 
434   if (Val->getType() != DestIntTy)
435     Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
436 
437   if (isa<llvm::PointerType>(Ty))
438     Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
439   return Val;
440 }
441 
442 
443 
444 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
445 /// a pointer to an object of type \arg Ty.
446 ///
447 /// This safely handles the case when the src type is smaller than the
448 /// destination type; in this situation the values of bits which not
449 /// present in the src are undefined.
450 static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
451                                       llvm::Type *Ty,
452                                       CodeGenFunction &CGF) {
453   llvm::Type *SrcTy =
454     cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
455 
456   // If SrcTy and Ty are the same, just do a load.
457   if (SrcTy == Ty)
458     return CGF.Builder.CreateLoad(SrcPtr);
459 
460   uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty);
461 
462   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
463     SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
464     SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
465   }
466 
467   uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
468 
469   // If the source and destination are integer or pointer types, just do an
470   // extension or truncation to the desired type.
471   if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
472       (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
473     llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
474     return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
475   }
476 
477   // If load is legal, just bitcast the src pointer.
478   if (SrcSize >= DstSize) {
479     // Generally SrcSize is never greater than DstSize, since this means we are
480     // losing bits. However, this can happen in cases where the structure has
481     // additional padding, for example due to a user specified alignment.
482     //
483     // FIXME: Assert that we aren't truncating non-padding bits when have access
484     // to that information.
485     llvm::Value *Casted =
486       CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
487     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
488     // FIXME: Use better alignment / avoid requiring aligned load.
489     Load->setAlignment(1);
490     return Load;
491   }
492 
493   // Otherwise do coercion through memory. This is stupid, but
494   // simple.
495   llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
496   llvm::Value *Casted =
497     CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
498   llvm::StoreInst *Store =
499     CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
500   // FIXME: Use better alignment / avoid requiring aligned store.
501   Store->setAlignment(1);
502   return CGF.Builder.CreateLoad(Tmp);
503 }
504 
505 // Function to store a first-class aggregate into memory.  We prefer to
506 // store the elements rather than the aggregate to be more friendly to
507 // fast-isel.
508 // FIXME: Do we need to recurse here?
509 static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
510                           llvm::Value *DestPtr, bool DestIsVolatile,
511                           bool LowAlignment) {
512   // Prefer scalar stores to first-class aggregate stores.
513   if (llvm::StructType *STy =
514         dyn_cast<llvm::StructType>(Val->getType())) {
515     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
516       llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
517       llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
518       llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
519                                                     DestIsVolatile);
520       if (LowAlignment)
521         SI->setAlignment(1);
522     }
523   } else {
524     CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
525   }
526 }
527 
528 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
529 /// where the source and destination may have different types.
530 ///
531 /// This safely handles the case when the src type is larger than the
532 /// destination type; the upper bits of the src will be lost.
533 static void CreateCoercedStore(llvm::Value *Src,
534                                llvm::Value *DstPtr,
535                                bool DstIsVolatile,
536                                CodeGenFunction &CGF) {
537   llvm::Type *SrcTy = Src->getType();
538   llvm::Type *DstTy =
539     cast<llvm::PointerType>(DstPtr->getType())->getElementType();
540   if (SrcTy == DstTy) {
541     CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
542     return;
543   }
544 
545   uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
546 
547   if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
548     DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
549     DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
550   }
551 
552   // If the source and destination are integer or pointer types, just do an
553   // extension or truncation to the desired type.
554   if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
555       (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
556     Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
557     CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
558     return;
559   }
560 
561   uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy);
562 
563   // If store is legal, just bitcast the src pointer.
564   if (SrcSize <= DstSize) {
565     llvm::Value *Casted =
566       CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
567     // FIXME: Use better alignment / avoid requiring aligned store.
568     BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
569   } else {
570     // Otherwise do coercion through memory. This is stupid, but
571     // simple.
572 
573     // Generally SrcSize is never greater than DstSize, since this means we are
574     // losing bits. However, this can happen in cases where the structure has
575     // additional padding, for example due to a user specified alignment.
576     //
577     // FIXME: Assert that we aren't truncating non-padding bits when have access
578     // to that information.
579     llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
580     CGF.Builder.CreateStore(Src, Tmp);
581     llvm::Value *Casted =
582       CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
583     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
584     // FIXME: Use better alignment / avoid requiring aligned load.
585     Load->setAlignment(1);
586     CGF.Builder.CreateStore(Load, DstPtr, DstIsVolatile);
587   }
588 }
589 
590 /***/
591 
592 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
593   return FI.getReturnInfo().isIndirect();
594 }
595 
596 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
597   if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
598     switch (BT->getKind()) {
599     default:
600       return false;
601     case BuiltinType::Float:
602       return getContext().getTargetInfo().useObjCFPRetForRealType(TargetInfo::Float);
603     case BuiltinType::Double:
604       return getContext().getTargetInfo().useObjCFPRetForRealType(TargetInfo::Double);
605     case BuiltinType::LongDouble:
606       return getContext().getTargetInfo().useObjCFPRetForRealType(
607         TargetInfo::LongDouble);
608     }
609   }
610 
611   return false;
612 }
613 
614 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
615   if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
616     if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
617       if (BT->getKind() == BuiltinType::LongDouble)
618         return getContext().getTargetInfo().useObjCFP2RetForComplexLongDouble();
619     }
620   }
621 
622   return false;
623 }
624 
625 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
626   const CGFunctionInfo &FI = getFunctionInfo(GD);
627 
628   // For definition purposes, don't consider a K&R function variadic.
629   bool Variadic = false;
630   if (const FunctionProtoType *FPT =
631         cast<FunctionDecl>(GD.getDecl())->getType()->getAs<FunctionProtoType>())
632     Variadic = FPT->isVariadic();
633 
634   return GetFunctionType(FI, Variadic);
635 }
636 
637 llvm::FunctionType *
638 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool isVariadic) {
639 
640   bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
641   assert(Inserted && "Recursively being processed?");
642 
643   SmallVector<llvm::Type*, 8> argTypes;
644   llvm::Type *resultType = 0;
645 
646   const ABIArgInfo &retAI = FI.getReturnInfo();
647   switch (retAI.getKind()) {
648   case ABIArgInfo::Expand:
649     llvm_unreachable("Invalid ABI kind for return argument");
650 
651   case ABIArgInfo::Extend:
652   case ABIArgInfo::Direct:
653     resultType = retAI.getCoerceToType();
654     break;
655 
656   case ABIArgInfo::Indirect: {
657     assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
658     resultType = llvm::Type::getVoidTy(getLLVMContext());
659 
660     QualType ret = FI.getReturnType();
661     llvm::Type *ty = ConvertType(ret);
662     unsigned addressSpace = Context.getTargetAddressSpace(ret);
663     argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
664     break;
665   }
666 
667   case ABIArgInfo::Ignore:
668     resultType = llvm::Type::getVoidTy(getLLVMContext());
669     break;
670   }
671 
672   for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
673          ie = FI.arg_end(); it != ie; ++it) {
674     const ABIArgInfo &argAI = it->info;
675 
676     switch (argAI.getKind()) {
677     case ABIArgInfo::Ignore:
678       break;
679 
680     case ABIArgInfo::Indirect: {
681       // indirect arguments are always on the stack, which is addr space #0.
682       llvm::Type *LTy = ConvertTypeForMem(it->type);
683       argTypes.push_back(LTy->getPointerTo());
684       break;
685     }
686 
687     case ABIArgInfo::Extend:
688     case ABIArgInfo::Direct: {
689       // If the coerce-to type is a first class aggregate, flatten it.  Either
690       // way is semantically identical, but fast-isel and the optimizer
691       // generally likes scalar values better than FCAs.
692       llvm::Type *argType = argAI.getCoerceToType();
693       if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
694         for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
695           argTypes.push_back(st->getElementType(i));
696       } else {
697         argTypes.push_back(argType);
698       }
699       break;
700     }
701 
702     case ABIArgInfo::Expand:
703       GetExpandedTypes(it->type, argTypes);
704       break;
705     }
706   }
707 
708   bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
709   assert(Erased && "Not in set?");
710 
711   return llvm::FunctionType::get(resultType, argTypes, isVariadic);
712 }
713 
714 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
715   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
716   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
717 
718   if (!isFuncTypeConvertible(FPT))
719     return llvm::StructType::get(getLLVMContext());
720 
721   const CGFunctionInfo *Info;
722   if (isa<CXXDestructorDecl>(MD))
723     Info = &getFunctionInfo(cast<CXXDestructorDecl>(MD), GD.getDtorType());
724   else
725     Info = &getFunctionInfo(MD);
726   return GetFunctionType(*Info, FPT->isVariadic());
727 }
728 
729 void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
730                                            const Decl *TargetDecl,
731                                            AttributeListType &PAL,
732                                            unsigned &CallingConv) {
733   unsigned FuncAttrs = 0;
734   unsigned RetAttrs = 0;
735 
736   CallingConv = FI.getEffectiveCallingConvention();
737 
738   if (FI.isNoReturn())
739     FuncAttrs |= llvm::Attribute::NoReturn;
740 
741   // FIXME: handle sseregparm someday...
742   if (TargetDecl) {
743     if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
744       FuncAttrs |= llvm::Attribute::ReturnsTwice;
745     if (TargetDecl->hasAttr<NoThrowAttr>())
746       FuncAttrs |= llvm::Attribute::NoUnwind;
747     else if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
748       const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
749       if (FPT && FPT->isNothrow(getContext()))
750         FuncAttrs |= llvm::Attribute::NoUnwind;
751     }
752 
753     if (TargetDecl->hasAttr<NoReturnAttr>())
754       FuncAttrs |= llvm::Attribute::NoReturn;
755 
756     if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
757       FuncAttrs |= llvm::Attribute::ReturnsTwice;
758 
759     // 'const' and 'pure' attribute functions are also nounwind.
760     if (TargetDecl->hasAttr<ConstAttr>()) {
761       FuncAttrs |= llvm::Attribute::ReadNone;
762       FuncAttrs |= llvm::Attribute::NoUnwind;
763     } else if (TargetDecl->hasAttr<PureAttr>()) {
764       FuncAttrs |= llvm::Attribute::ReadOnly;
765       FuncAttrs |= llvm::Attribute::NoUnwind;
766     }
767     if (TargetDecl->hasAttr<MallocAttr>())
768       RetAttrs |= llvm::Attribute::NoAlias;
769   }
770 
771   if (CodeGenOpts.OptimizeSize)
772     FuncAttrs |= llvm::Attribute::OptimizeForSize;
773   if (CodeGenOpts.DisableRedZone)
774     FuncAttrs |= llvm::Attribute::NoRedZone;
775   if (CodeGenOpts.NoImplicitFloat)
776     FuncAttrs |= llvm::Attribute::NoImplicitFloat;
777 
778   QualType RetTy = FI.getReturnType();
779   unsigned Index = 1;
780   const ABIArgInfo &RetAI = FI.getReturnInfo();
781   switch (RetAI.getKind()) {
782   case ABIArgInfo::Extend:
783    if (RetTy->hasSignedIntegerRepresentation())
784      RetAttrs |= llvm::Attribute::SExt;
785    else if (RetTy->hasUnsignedIntegerRepresentation())
786      RetAttrs |= llvm::Attribute::ZExt;
787     break;
788   case ABIArgInfo::Direct:
789   case ABIArgInfo::Ignore:
790     break;
791 
792   case ABIArgInfo::Indirect:
793     PAL.push_back(llvm::AttributeWithIndex::get(Index,
794                                                 llvm::Attribute::StructRet));
795     ++Index;
796     // sret disables readnone and readonly
797     FuncAttrs &= ~(llvm::Attribute::ReadOnly |
798                    llvm::Attribute::ReadNone);
799     break;
800 
801   case ABIArgInfo::Expand:
802     llvm_unreachable("Invalid ABI kind for return argument");
803   }
804 
805   if (RetAttrs)
806     PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
807 
808   // FIXME: RegParm should be reduced in case of global register variable.
809   signed RegParm;
810   if (FI.getHasRegParm())
811     RegParm = FI.getRegParm();
812   else
813     RegParm = CodeGenOpts.NumRegisterParameters;
814 
815   unsigned PointerWidth = getContext().getTargetInfo().getPointerWidth(0);
816   for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
817          ie = FI.arg_end(); it != ie; ++it) {
818     QualType ParamType = it->type;
819     const ABIArgInfo &AI = it->info;
820     unsigned Attributes = 0;
821 
822     // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
823     // have the corresponding parameter variable.  It doesn't make
824     // sense to do it here because parameters are so messed up.
825     switch (AI.getKind()) {
826     case ABIArgInfo::Extend:
827       if (ParamType->isSignedIntegerOrEnumerationType())
828         Attributes |= llvm::Attribute::SExt;
829       else if (ParamType->isUnsignedIntegerOrEnumerationType())
830         Attributes |= llvm::Attribute::ZExt;
831       // FALL THROUGH
832     case ABIArgInfo::Direct:
833       if (RegParm > 0 &&
834           (ParamType->isIntegerType() || ParamType->isPointerType() ||
835            ParamType->isReferenceType())) {
836         RegParm -=
837         (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth;
838         if (RegParm >= 0)
839           Attributes |= llvm::Attribute::InReg;
840       }
841       // FIXME: handle sseregparm someday...
842 
843       if (llvm::StructType *STy =
844             dyn_cast<llvm::StructType>(AI.getCoerceToType()))
845         Index += STy->getNumElements()-1;  // 1 will be added below.
846       break;
847 
848     case ABIArgInfo::Indirect:
849       if (AI.getIndirectByVal())
850         Attributes |= llvm::Attribute::ByVal;
851 
852       Attributes |=
853         llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
854       // byval disables readnone and readonly.
855       FuncAttrs &= ~(llvm::Attribute::ReadOnly |
856                      llvm::Attribute::ReadNone);
857       break;
858 
859     case ABIArgInfo::Ignore:
860       // Skip increment, no matching LLVM parameter.
861       continue;
862 
863     case ABIArgInfo::Expand: {
864       SmallVector<llvm::Type*, 8> types;
865       // FIXME: This is rather inefficient. Do we ever actually need to do
866       // anything here? The result should be just reconstructed on the other
867       // side, so extension should be a non-issue.
868       getTypes().GetExpandedTypes(ParamType, types);
869       Index += types.size();
870       continue;
871     }
872     }
873 
874     if (Attributes)
875       PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
876     ++Index;
877   }
878   if (FuncAttrs)
879     PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
880 }
881 
882 /// An argument came in as a promoted argument; demote it back to its
883 /// declared type.
884 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
885                                          const VarDecl *var,
886                                          llvm::Value *value) {
887   llvm::Type *varType = CGF.ConvertType(var->getType());
888 
889   // This can happen with promotions that actually don't change the
890   // underlying type, like the enum promotions.
891   if (value->getType() == varType) return value;
892 
893   assert((varType->isIntegerTy() || varType->isFloatingPointTy())
894          && "unexpected promotion type");
895 
896   if (isa<llvm::IntegerType>(varType))
897     return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
898 
899   return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
900 }
901 
902 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
903                                          llvm::Function *Fn,
904                                          const FunctionArgList &Args) {
905   // If this is an implicit-return-zero function, go ahead and
906   // initialize the return value.  TODO: it might be nice to have
907   // a more general mechanism for this that didn't require synthesized
908   // return statements.
909   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
910     if (FD->hasImplicitReturnZero()) {
911       QualType RetTy = FD->getResultType().getUnqualifiedType();
912       llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
913       llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
914       Builder.CreateStore(Zero, ReturnValue);
915     }
916   }
917 
918   // FIXME: We no longer need the types from FunctionArgList; lift up and
919   // simplify.
920 
921   // Emit allocs for param decls.  Give the LLVM Argument nodes names.
922   llvm::Function::arg_iterator AI = Fn->arg_begin();
923 
924   // Name the struct return argument.
925   if (CGM.ReturnTypeUsesSRet(FI)) {
926     AI->setName("agg.result");
927     AI->addAttr(llvm::Attribute::NoAlias);
928     ++AI;
929   }
930 
931   assert(FI.arg_size() == Args.size() &&
932          "Mismatch between function signature & arguments.");
933   unsigned ArgNo = 1;
934   CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
935   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
936        i != e; ++i, ++info_it, ++ArgNo) {
937     const VarDecl *Arg = *i;
938     QualType Ty = info_it->type;
939     const ABIArgInfo &ArgI = info_it->info;
940 
941     bool isPromoted =
942       isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
943 
944     switch (ArgI.getKind()) {
945     case ABIArgInfo::Indirect: {
946       llvm::Value *V = AI;
947 
948       if (hasAggregateLLVMType(Ty)) {
949         // Aggregates and complex variables are accessed by reference.  All we
950         // need to do is realign the value, if requested
951         if (ArgI.getIndirectRealign()) {
952           llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
953 
954           // Copy from the incoming argument pointer to the temporary with the
955           // appropriate alignment.
956           //
957           // FIXME: We should have a common utility for generating an aggregate
958           // copy.
959           llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
960           CharUnits Size = getContext().getTypeSizeInChars(Ty);
961           llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
962           llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
963           Builder.CreateMemCpy(Dst,
964                                Src,
965                                llvm::ConstantInt::get(IntPtrTy,
966                                                       Size.getQuantity()),
967                                ArgI.getIndirectAlign(),
968                                false);
969           V = AlignedTemp;
970         }
971       } else {
972         // Load scalar value from indirect argument.
973         CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
974         V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty);
975 
976         if (isPromoted)
977           V = emitArgumentDemotion(*this, Arg, V);
978       }
979       EmitParmDecl(*Arg, V, ArgNo);
980       break;
981     }
982 
983     case ABIArgInfo::Extend:
984     case ABIArgInfo::Direct: {
985       // If we have the trivial case, handle it with no muss and fuss.
986       if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
987           ArgI.getCoerceToType() == ConvertType(Ty) &&
988           ArgI.getDirectOffset() == 0) {
989         assert(AI != Fn->arg_end() && "Argument mismatch!");
990         llvm::Value *V = AI;
991 
992         if (Arg->getType().isRestrictQualified())
993           AI->addAttr(llvm::Attribute::NoAlias);
994 
995         // Ensure the argument is the correct type.
996         if (V->getType() != ArgI.getCoerceToType())
997           V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
998 
999         if (isPromoted)
1000           V = emitArgumentDemotion(*this, Arg, V);
1001 
1002         EmitParmDecl(*Arg, V, ArgNo);
1003         break;
1004       }
1005 
1006       llvm::AllocaInst *Alloca = CreateMemTemp(Ty, "coerce");
1007 
1008       // The alignment we need to use is the max of the requested alignment for
1009       // the argument plus the alignment required by our access code below.
1010       unsigned AlignmentToUse =
1011         CGM.getTargetData().getABITypeAlignment(ArgI.getCoerceToType());
1012       AlignmentToUse = std::max(AlignmentToUse,
1013                         (unsigned)getContext().getDeclAlign(Arg).getQuantity());
1014 
1015       Alloca->setAlignment(AlignmentToUse);
1016       llvm::Value *V = Alloca;
1017       llvm::Value *Ptr = V;    // Pointer to store into.
1018 
1019       // If the value is offset in memory, apply the offset now.
1020       if (unsigned Offs = ArgI.getDirectOffset()) {
1021         Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1022         Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
1023         Ptr = Builder.CreateBitCast(Ptr,
1024                           llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1025       }
1026 
1027       // If the coerce-to type is a first class aggregate, we flatten it and
1028       // pass the elements. Either way is semantically identical, but fast-isel
1029       // and the optimizer generally likes scalar values better than FCAs.
1030       if (llvm::StructType *STy =
1031             dyn_cast<llvm::StructType>(ArgI.getCoerceToType())) {
1032         Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1033 
1034         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1035           assert(AI != Fn->arg_end() && "Argument mismatch!");
1036           AI->setName(Arg->getName() + ".coerce" + Twine(i));
1037           llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1038           Builder.CreateStore(AI++, EltPtr);
1039         }
1040       } else {
1041         // Simple case, just do a coerced store of the argument into the alloca.
1042         assert(AI != Fn->arg_end() && "Argument mismatch!");
1043         AI->setName(Arg->getName() + ".coerce");
1044         CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
1045       }
1046 
1047 
1048       // Match to what EmitParmDecl is expecting for this type.
1049       if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
1050         V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty);
1051         if (isPromoted)
1052           V = emitArgumentDemotion(*this, Arg, V);
1053       }
1054       EmitParmDecl(*Arg, V, ArgNo);
1055       continue;  // Skip ++AI increment, already done.
1056     }
1057 
1058     case ABIArgInfo::Expand: {
1059       // If this structure was expanded into multiple arguments then
1060       // we need to create a temporary and reconstruct it from the
1061       // arguments.
1062       llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
1063       CharUnits Align = getContext().getDeclAlign(Arg);
1064       Alloca->setAlignment(Align.getQuantity());
1065       LValue LV = MakeAddrLValue(Alloca, Ty, Align);
1066       llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
1067       EmitParmDecl(*Arg, Alloca, ArgNo);
1068 
1069       // Name the arguments used in expansion and increment AI.
1070       unsigned Index = 0;
1071       for (; AI != End; ++AI, ++Index)
1072         AI->setName(Arg->getName() + "." + Twine(Index));
1073       continue;
1074     }
1075 
1076     case ABIArgInfo::Ignore:
1077       // Initialize the local variable appropriately.
1078       if (hasAggregateLLVMType(Ty))
1079         EmitParmDecl(*Arg, CreateMemTemp(Ty), ArgNo);
1080       else
1081         EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())),
1082                      ArgNo);
1083 
1084       // Skip increment, no matching LLVM parameter.
1085       continue;
1086     }
1087 
1088     ++AI;
1089   }
1090   assert(AI == Fn->arg_end() && "Argument mismatch!");
1091 }
1092 
1093 /// Try to emit a fused autorelease of a return result.
1094 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1095                                                     llvm::Value *result) {
1096   // We must be immediately followed the cast.
1097   llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1098   if (BB->empty()) return 0;
1099   if (&BB->back() != result) return 0;
1100 
1101   llvm::Type *resultType = result->getType();
1102 
1103   // result is in a BasicBlock and is therefore an Instruction.
1104   llvm::Instruction *generator = cast<llvm::Instruction>(result);
1105 
1106   SmallVector<llvm::Instruction*,4> insnsToKill;
1107 
1108   // Look for:
1109   //  %generator = bitcast %type1* %generator2 to %type2*
1110   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1111     // We would have emitted this as a constant if the operand weren't
1112     // an Instruction.
1113     generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1114 
1115     // Require the generator to be immediately followed by the cast.
1116     if (generator->getNextNode() != bitcast)
1117       return 0;
1118 
1119     insnsToKill.push_back(bitcast);
1120   }
1121 
1122   // Look for:
1123   //   %generator = call i8* @objc_retain(i8* %originalResult)
1124   // or
1125   //   %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1126   llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1127   if (!call) return 0;
1128 
1129   bool doRetainAutorelease;
1130 
1131   if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1132     doRetainAutorelease = true;
1133   } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1134                                           .objc_retainAutoreleasedReturnValue) {
1135     doRetainAutorelease = false;
1136 
1137     // Look for an inline asm immediately preceding the call and kill it, too.
1138     llvm::Instruction *prev = call->getPrevNode();
1139     if (llvm::CallInst *asmCall = dyn_cast_or_null<llvm::CallInst>(prev))
1140       if (asmCall->getCalledValue()
1141             == CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker)
1142         insnsToKill.push_back(prev);
1143   } else {
1144     return 0;
1145   }
1146 
1147   result = call->getArgOperand(0);
1148   insnsToKill.push_back(call);
1149 
1150   // Keep killing bitcasts, for sanity.  Note that we no longer care
1151   // about precise ordering as long as there's exactly one use.
1152   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1153     if (!bitcast->hasOneUse()) break;
1154     insnsToKill.push_back(bitcast);
1155     result = bitcast->getOperand(0);
1156   }
1157 
1158   // Delete all the unnecessary instructions, from latest to earliest.
1159   for (SmallVectorImpl<llvm::Instruction*>::iterator
1160          i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1161     (*i)->eraseFromParent();
1162 
1163   // Do the fused retain/autorelease if we were asked to.
1164   if (doRetainAutorelease)
1165     result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1166 
1167   // Cast back to the result type.
1168   return CGF.Builder.CreateBitCast(result, resultType);
1169 }
1170 
1171 /// Emit an ARC autorelease of the result of a function.
1172 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1173                                             llvm::Value *result) {
1174   // At -O0, try to emit a fused retain/autorelease.
1175   if (CGF.shouldUseFusedARCCalls())
1176     if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1177       return fused;
1178 
1179   return CGF.EmitARCAutoreleaseReturnValue(result);
1180 }
1181 
1182 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI) {
1183   // Functions with no result always return void.
1184   if (ReturnValue == 0) {
1185     Builder.CreateRetVoid();
1186     return;
1187   }
1188 
1189   llvm::DebugLoc RetDbgLoc;
1190   llvm::Value *RV = 0;
1191   QualType RetTy = FI.getReturnType();
1192   const ABIArgInfo &RetAI = FI.getReturnInfo();
1193 
1194   switch (RetAI.getKind()) {
1195   case ABIArgInfo::Indirect: {
1196     unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
1197     if (RetTy->isAnyComplexType()) {
1198       ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
1199       StoreComplexToAddr(RT, CurFn->arg_begin(), false);
1200     } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1201       // Do nothing; aggregrates get evaluated directly into the destination.
1202     } else {
1203       EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
1204                         false, Alignment, RetTy);
1205     }
1206     break;
1207   }
1208 
1209   case ABIArgInfo::Extend:
1210   case ABIArgInfo::Direct:
1211     if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1212         RetAI.getDirectOffset() == 0) {
1213       // The internal return value temp always will have pointer-to-return-type
1214       // type, just do a load.
1215 
1216       // If the instruction right before the insertion point is a store to the
1217       // return value, we can elide the load, zap the store, and usually zap the
1218       // alloca.
1219       llvm::BasicBlock *InsertBB = Builder.GetInsertBlock();
1220       llvm::StoreInst *SI = 0;
1221       if (InsertBB->empty() ||
1222           !(SI = dyn_cast<llvm::StoreInst>(&InsertBB->back())) ||
1223           SI->getPointerOperand() != ReturnValue || SI->isVolatile()) {
1224         RV = Builder.CreateLoad(ReturnValue);
1225       } else {
1226         // Get the stored value and nuke the now-dead store.
1227         RetDbgLoc = SI->getDebugLoc();
1228         RV = SI->getValueOperand();
1229         SI->eraseFromParent();
1230 
1231         // If that was the only use of the return value, nuke it as well now.
1232         if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1233           cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1234           ReturnValue = 0;
1235         }
1236       }
1237     } else {
1238       llvm::Value *V = ReturnValue;
1239       // If the value is offset in memory, apply the offset now.
1240       if (unsigned Offs = RetAI.getDirectOffset()) {
1241         V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1242         V = Builder.CreateConstGEP1_32(V, Offs);
1243         V = Builder.CreateBitCast(V,
1244                          llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1245       }
1246 
1247       RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
1248     }
1249 
1250     // In ARC, end functions that return a retainable type with a call
1251     // to objc_autoreleaseReturnValue.
1252     if (AutoreleaseResult) {
1253       assert(getLangOptions().ObjCAutoRefCount &&
1254              !FI.isReturnsRetained() &&
1255              RetTy->isObjCRetainableType());
1256       RV = emitAutoreleaseOfResult(*this, RV);
1257     }
1258 
1259     break;
1260 
1261   case ABIArgInfo::Ignore:
1262     break;
1263 
1264   case ABIArgInfo::Expand:
1265     llvm_unreachable("Invalid ABI kind for return argument");
1266   }
1267 
1268   llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
1269   if (!RetDbgLoc.isUnknown())
1270     Ret->setDebugLoc(RetDbgLoc);
1271 }
1272 
1273 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
1274                                           const VarDecl *param) {
1275   // StartFunction converted the ABI-lowered parameter(s) into a
1276   // local alloca.  We need to turn that into an r-value suitable
1277   // for EmitCall.
1278   llvm::Value *local = GetAddrOfLocalVar(param);
1279 
1280   QualType type = param->getType();
1281 
1282   // For the most part, we just need to load the alloca, except:
1283   // 1) aggregate r-values are actually pointers to temporaries, and
1284   // 2) references to aggregates are pointers directly to the aggregate.
1285   // I don't know why references to non-aggregates are different here.
1286   if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
1287     if (hasAggregateLLVMType(ref->getPointeeType()))
1288       return args.add(RValue::getAggregate(local), type);
1289 
1290     // Locals which are references to scalars are represented
1291     // with allocas holding the pointer.
1292     return args.add(RValue::get(Builder.CreateLoad(local)), type);
1293   }
1294 
1295   if (type->isAnyComplexType()) {
1296     ComplexPairTy complex = LoadComplexFromAddr(local, /*volatile*/ false);
1297     return args.add(RValue::getComplex(complex), type);
1298   }
1299 
1300   if (hasAggregateLLVMType(type))
1301     return args.add(RValue::getAggregate(local), type);
1302 
1303   unsigned alignment = getContext().getDeclAlign(param).getQuantity();
1304   llvm::Value *value = EmitLoadOfScalar(local, false, alignment, type);
1305   return args.add(RValue::get(value), type);
1306 }
1307 
1308 static bool isProvablyNull(llvm::Value *addr) {
1309   return isa<llvm::ConstantPointerNull>(addr);
1310 }
1311 
1312 static bool isProvablyNonNull(llvm::Value *addr) {
1313   return isa<llvm::AllocaInst>(addr);
1314 }
1315 
1316 /// Emit the actual writing-back of a writeback.
1317 static void emitWriteback(CodeGenFunction &CGF,
1318                           const CallArgList::Writeback &writeback) {
1319   llvm::Value *srcAddr = writeback.Address;
1320   assert(!isProvablyNull(srcAddr) &&
1321          "shouldn't have writeback for provably null argument");
1322 
1323   llvm::BasicBlock *contBB = 0;
1324 
1325   // If the argument wasn't provably non-null, we need to null check
1326   // before doing the store.
1327   bool provablyNonNull = isProvablyNonNull(srcAddr);
1328   if (!provablyNonNull) {
1329     llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1330     contBB = CGF.createBasicBlock("icr.done");
1331 
1332     llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1333     CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1334     CGF.EmitBlock(writebackBB);
1335   }
1336 
1337   // Load the value to writeback.
1338   llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1339 
1340   // Cast it back, in case we're writing an id to a Foo* or something.
1341   value = CGF.Builder.CreateBitCast(value,
1342                cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1343                             "icr.writeback-cast");
1344 
1345   // Perform the writeback.
1346   QualType srcAddrType = writeback.AddressType;
1347   CGF.EmitStoreThroughLValue(RValue::get(value),
1348                              CGF.MakeAddrLValue(srcAddr, srcAddrType));
1349 
1350   // Jump to the continuation block.
1351   if (!provablyNonNull)
1352     CGF.EmitBlock(contBB);
1353 }
1354 
1355 static void emitWritebacks(CodeGenFunction &CGF,
1356                            const CallArgList &args) {
1357   for (CallArgList::writeback_iterator
1358          i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1359     emitWriteback(CGF, *i);
1360 }
1361 
1362 /// Emit an argument that's being passed call-by-writeback.  That is,
1363 /// we are passing the address of
1364 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1365                              const ObjCIndirectCopyRestoreExpr *CRE) {
1366   llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1367 
1368   // The dest and src types don't necessarily match in LLVM terms
1369   // because of the crazy ObjC compatibility rules.
1370 
1371   llvm::PointerType *destType =
1372     cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1373 
1374   // If the address is a constant null, just pass the appropriate null.
1375   if (isProvablyNull(srcAddr)) {
1376     args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1377              CRE->getType());
1378     return;
1379   }
1380 
1381   QualType srcAddrType =
1382     CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1383 
1384   // Create the temporary.
1385   llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1386                                            "icr.temp");
1387 
1388   // Zero-initialize it if we're not doing a copy-initialization.
1389   bool shouldCopy = CRE->shouldCopy();
1390   if (!shouldCopy) {
1391     llvm::Value *null =
1392       llvm::ConstantPointerNull::get(
1393         cast<llvm::PointerType>(destType->getElementType()));
1394     CGF.Builder.CreateStore(null, temp);
1395   }
1396 
1397   llvm::BasicBlock *contBB = 0;
1398 
1399   // If the address is *not* known to be non-null, we need to switch.
1400   llvm::Value *finalArgument;
1401 
1402   bool provablyNonNull = isProvablyNonNull(srcAddr);
1403   if (provablyNonNull) {
1404     finalArgument = temp;
1405   } else {
1406     llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1407 
1408     finalArgument = CGF.Builder.CreateSelect(isNull,
1409                                    llvm::ConstantPointerNull::get(destType),
1410                                              temp, "icr.argument");
1411 
1412     // If we need to copy, then the load has to be conditional, which
1413     // means we need control flow.
1414     if (shouldCopy) {
1415       contBB = CGF.createBasicBlock("icr.cont");
1416       llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1417       CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1418       CGF.EmitBlock(copyBB);
1419     }
1420   }
1421 
1422   // Perform a copy if necessary.
1423   if (shouldCopy) {
1424     LValue srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
1425     RValue srcRV = CGF.EmitLoadOfLValue(srcLV);
1426     assert(srcRV.isScalar());
1427 
1428     llvm::Value *src = srcRV.getScalarVal();
1429     src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1430                                     "icr.cast");
1431 
1432     // Use an ordinary store, not a store-to-lvalue.
1433     CGF.Builder.CreateStore(src, temp);
1434   }
1435 
1436   // Finish the control flow if we needed it.
1437   if (shouldCopy && !provablyNonNull)
1438     CGF.EmitBlock(contBB);
1439 
1440   args.addWriteback(srcAddr, srcAddrType, temp);
1441   args.add(RValue::get(finalArgument), CRE->getType());
1442 }
1443 
1444 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
1445                                   QualType type) {
1446   if (const ObjCIndirectCopyRestoreExpr *CRE
1447         = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
1448     assert(getContext().getLangOptions().ObjCAutoRefCount);
1449     assert(getContext().hasSameType(E->getType(), type));
1450     return emitWritebackArg(*this, args, CRE);
1451   }
1452 
1453   assert(type->isReferenceType() == E->isGLValue() &&
1454          "reference binding to unmaterialized r-value!");
1455 
1456   if (E->isGLValue()) {
1457     assert(E->getObjectKind() == OK_Ordinary);
1458     return args.add(EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0),
1459                     type);
1460   }
1461 
1462   if (hasAggregateLLVMType(type) && !E->getType()->isAnyComplexType() &&
1463       isa<ImplicitCastExpr>(E) &&
1464       cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
1465     LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
1466     assert(L.isSimple());
1467     args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
1468     return;
1469   }
1470 
1471   args.add(EmitAnyExprToTemp(E), type);
1472 }
1473 
1474 /// Emits a call or invoke instruction to the given function, depending
1475 /// on the current state of the EH stack.
1476 llvm::CallSite
1477 CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
1478                                   ArrayRef<llvm::Value *> Args,
1479                                   const Twine &Name) {
1480   llvm::BasicBlock *InvokeDest = getInvokeDest();
1481   if (!InvokeDest)
1482     return Builder.CreateCall(Callee, Args, Name);
1483 
1484   llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
1485   llvm::InvokeInst *Invoke = Builder.CreateInvoke(Callee, ContBB, InvokeDest,
1486                                                   Args, Name);
1487   EmitBlock(ContBB);
1488   return Invoke;
1489 }
1490 
1491 llvm::CallSite
1492 CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
1493                                   const Twine &Name) {
1494   return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
1495 }
1496 
1497 static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
1498                             llvm::FunctionType *FTy) {
1499   if (ArgNo < FTy->getNumParams())
1500     assert(Elt->getType() == FTy->getParamType(ArgNo));
1501   else
1502     assert(FTy->isVarArg());
1503   ++ArgNo;
1504 }
1505 
1506 void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
1507                                        SmallVector<llvm::Value*,16> &Args,
1508                                        llvm::FunctionType *IRFuncTy) {
1509   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
1510     unsigned NumElts = AT->getSize().getZExtValue();
1511     QualType EltTy = AT->getElementType();
1512     llvm::Value *Addr = RV.getAggregateAddr();
1513     for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
1514       llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
1515       LValue LV = MakeAddrLValue(EltAddr, EltTy);
1516       RValue EltRV;
1517       if (EltTy->isAnyComplexType())
1518         // FIXME: Volatile?
1519         EltRV = RValue::getComplex(LoadComplexFromAddr(LV.getAddress(), false));
1520       else if (CodeGenFunction::hasAggregateLLVMType(EltTy))
1521         EltRV = LV.asAggregateRValue();
1522       else
1523         EltRV = EmitLoadOfLValue(LV);
1524       ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
1525     }
1526   } else if (const RecordType *RT = Ty->getAsStructureType()) {
1527     RecordDecl *RD = RT->getDecl();
1528     assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
1529     llvm::Value *Addr = RV.getAggregateAddr();
1530     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1531          i != e; ++i) {
1532       FieldDecl *FD = *i;
1533       QualType FT = FD->getType();
1534 
1535       // FIXME: What are the right qualifiers here?
1536       LValue LV = EmitLValueForField(Addr, FD, 0);
1537       RValue FldRV;
1538       if (FT->isAnyComplexType())
1539         // FIXME: Volatile?
1540         FldRV = RValue::getComplex(LoadComplexFromAddr(LV.getAddress(), false));
1541       else if (CodeGenFunction::hasAggregateLLVMType(FT))
1542         FldRV = LV.asAggregateRValue();
1543       else
1544         FldRV = EmitLoadOfLValue(LV);
1545       ExpandTypeToArgs(FT, FldRV, Args, IRFuncTy);
1546     }
1547   } else if (Ty->isAnyComplexType()) {
1548     ComplexPairTy CV = RV.getComplexVal();
1549     Args.push_back(CV.first);
1550     Args.push_back(CV.second);
1551   } else {
1552     assert(RV.isScalar() &&
1553            "Unexpected non-scalar rvalue during struct expansion.");
1554 
1555     // Insert a bitcast as needed.
1556     llvm::Value *V = RV.getScalarVal();
1557     if (Args.size() < IRFuncTy->getNumParams() &&
1558         V->getType() != IRFuncTy->getParamType(Args.size()))
1559       V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
1560 
1561     Args.push_back(V);
1562   }
1563 }
1564 
1565 
1566 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
1567                                  llvm::Value *Callee,
1568                                  ReturnValueSlot ReturnValue,
1569                                  const CallArgList &CallArgs,
1570                                  const Decl *TargetDecl,
1571                                  llvm::Instruction **callOrInvoke) {
1572   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
1573   SmallVector<llvm::Value*, 16> Args;
1574 
1575   // Handle struct-return functions by passing a pointer to the
1576   // location that we would like to return into.
1577   QualType RetTy = CallInfo.getReturnType();
1578   const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
1579 
1580   // IRArgNo - Keep track of the argument number in the callee we're looking at.
1581   unsigned IRArgNo = 0;
1582   llvm::FunctionType *IRFuncTy =
1583     cast<llvm::FunctionType>(
1584                   cast<llvm::PointerType>(Callee->getType())->getElementType());
1585 
1586   // If the call returns a temporary with struct return, create a temporary
1587   // alloca to hold the result, unless one is given to us.
1588   if (CGM.ReturnTypeUsesSRet(CallInfo)) {
1589     llvm::Value *Value = ReturnValue.getValue();
1590     if (!Value)
1591       Value = CreateMemTemp(RetTy);
1592     Args.push_back(Value);
1593     checkArgMatches(Value, IRArgNo, IRFuncTy);
1594   }
1595 
1596   assert(CallInfo.arg_size() == CallArgs.size() &&
1597          "Mismatch between function signature & arguments.");
1598   CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
1599   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
1600        I != E; ++I, ++info_it) {
1601     const ABIArgInfo &ArgInfo = info_it->info;
1602     RValue RV = I->RV;
1603 
1604     unsigned TypeAlign =
1605       getContext().getTypeAlignInChars(I->Ty).getQuantity();
1606     switch (ArgInfo.getKind()) {
1607     case ABIArgInfo::Indirect: {
1608       if (RV.isScalar() || RV.isComplex()) {
1609         // Make a temporary alloca to pass the argument.
1610         llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
1611         if (ArgInfo.getIndirectAlign() > AI->getAlignment())
1612           AI->setAlignment(ArgInfo.getIndirectAlign());
1613         Args.push_back(AI);
1614 
1615         if (RV.isScalar())
1616           EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false,
1617                             TypeAlign, I->Ty);
1618         else
1619           StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
1620 
1621         // Validate argument match.
1622         checkArgMatches(AI, IRArgNo, IRFuncTy);
1623       } else {
1624         // We want to avoid creating an unnecessary temporary+copy here;
1625         // however, we need one in two cases:
1626         // 1. If the argument is not byval, and we are required to copy the
1627         //    source.  (This case doesn't occur on any common architecture.)
1628         // 2. If the argument is byval, RV is not sufficiently aligned, and
1629         //    we cannot force it to be sufficiently aligned.
1630         llvm::Value *Addr = RV.getAggregateAddr();
1631         unsigned Align = ArgInfo.getIndirectAlign();
1632         const llvm::TargetData *TD = &CGM.getTargetData();
1633         if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
1634             (ArgInfo.getIndirectByVal() && TypeAlign < Align &&
1635              llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align)) {
1636           // Create an aligned temporary, and copy to it.
1637           llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
1638           if (Align > AI->getAlignment())
1639             AI->setAlignment(Align);
1640           Args.push_back(AI);
1641           EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
1642 
1643           // Validate argument match.
1644           checkArgMatches(AI, IRArgNo, IRFuncTy);
1645         } else {
1646           // Skip the extra memcpy call.
1647           Args.push_back(Addr);
1648 
1649           // Validate argument match.
1650           checkArgMatches(Addr, IRArgNo, IRFuncTy);
1651         }
1652       }
1653       break;
1654     }
1655 
1656     case ABIArgInfo::Ignore:
1657       break;
1658 
1659     case ABIArgInfo::Extend:
1660     case ABIArgInfo::Direct: {
1661       if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
1662           ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
1663           ArgInfo.getDirectOffset() == 0) {
1664         llvm::Value *V;
1665         if (RV.isScalar())
1666           V = RV.getScalarVal();
1667         else
1668           V = Builder.CreateLoad(RV.getAggregateAddr());
1669 
1670         // If the argument doesn't match, perform a bitcast to coerce it.  This
1671         // can happen due to trivial type mismatches.
1672         if (IRArgNo < IRFuncTy->getNumParams() &&
1673             V->getType() != IRFuncTy->getParamType(IRArgNo))
1674           V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
1675         Args.push_back(V);
1676 
1677         checkArgMatches(V, IRArgNo, IRFuncTy);
1678         break;
1679       }
1680 
1681       // FIXME: Avoid the conversion through memory if possible.
1682       llvm::Value *SrcPtr;
1683       if (RV.isScalar()) {
1684         SrcPtr = CreateMemTemp(I->Ty, "coerce");
1685         EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, TypeAlign, I->Ty);
1686       } else if (RV.isComplex()) {
1687         SrcPtr = CreateMemTemp(I->Ty, "coerce");
1688         StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
1689       } else
1690         SrcPtr = RV.getAggregateAddr();
1691 
1692       // If the value is offset in memory, apply the offset now.
1693       if (unsigned Offs = ArgInfo.getDirectOffset()) {
1694         SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
1695         SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
1696         SrcPtr = Builder.CreateBitCast(SrcPtr,
1697                        llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
1698 
1699       }
1700 
1701       // If the coerce-to type is a first class aggregate, we flatten it and
1702       // pass the elements. Either way is semantically identical, but fast-isel
1703       // and the optimizer generally likes scalar values better than FCAs.
1704       if (llvm::StructType *STy =
1705             dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
1706         SrcPtr = Builder.CreateBitCast(SrcPtr,
1707                                        llvm::PointerType::getUnqual(STy));
1708         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1709           llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
1710           llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
1711           // We don't know what we're loading from.
1712           LI->setAlignment(1);
1713           Args.push_back(LI);
1714 
1715           // Validate argument match.
1716           checkArgMatches(LI, IRArgNo, IRFuncTy);
1717         }
1718       } else {
1719         // In the simple case, just pass the coerced loaded value.
1720         Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
1721                                          *this));
1722 
1723         // Validate argument match.
1724         checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
1725       }
1726 
1727       break;
1728     }
1729 
1730     case ABIArgInfo::Expand:
1731       ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
1732       IRArgNo = Args.size();
1733       break;
1734     }
1735   }
1736 
1737   // If the callee is a bitcast of a function to a varargs pointer to function
1738   // type, check to see if we can remove the bitcast.  This handles some cases
1739   // with unprototyped functions.
1740   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
1741     if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
1742       llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
1743       llvm::FunctionType *CurFT =
1744         cast<llvm::FunctionType>(CurPT->getElementType());
1745       llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
1746 
1747       if (CE->getOpcode() == llvm::Instruction::BitCast &&
1748           ActualFT->getReturnType() == CurFT->getReturnType() &&
1749           ActualFT->getNumParams() == CurFT->getNumParams() &&
1750           ActualFT->getNumParams() == Args.size() &&
1751           (CurFT->isVarArg() || !ActualFT->isVarArg())) {
1752         bool ArgsMatch = true;
1753         for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
1754           if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
1755             ArgsMatch = false;
1756             break;
1757           }
1758 
1759         // Strip the cast if we can get away with it.  This is a nice cleanup,
1760         // but also allows us to inline the function at -O0 if it is marked
1761         // always_inline.
1762         if (ArgsMatch)
1763           Callee = CalleeF;
1764       }
1765     }
1766 
1767   unsigned CallingConv;
1768   CodeGen::AttributeListType AttributeList;
1769   CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList, CallingConv);
1770   llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
1771                                                    AttributeList.end());
1772 
1773   llvm::BasicBlock *InvokeDest = 0;
1774   if (!(Attrs.getFnAttributes() & llvm::Attribute::NoUnwind))
1775     InvokeDest = getInvokeDest();
1776 
1777   llvm::CallSite CS;
1778   if (!InvokeDest) {
1779     CS = Builder.CreateCall(Callee, Args);
1780   } else {
1781     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1782     CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
1783     EmitBlock(Cont);
1784   }
1785   if (callOrInvoke)
1786     *callOrInvoke = CS.getInstruction();
1787 
1788   CS.setAttributes(Attrs);
1789   CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1790 
1791   // If the call doesn't return, finish the basic block and clear the
1792   // insertion point; this allows the rest of IRgen to discard
1793   // unreachable code.
1794   if (CS.doesNotReturn()) {
1795     Builder.CreateUnreachable();
1796     Builder.ClearInsertionPoint();
1797 
1798     // FIXME: For now, emit a dummy basic block because expr emitters in
1799     // generally are not ready to handle emitting expressions at unreachable
1800     // points.
1801     EnsureInsertPoint();
1802 
1803     // Return a reasonable RValue.
1804     return GetUndefRValue(RetTy);
1805   }
1806 
1807   llvm::Instruction *CI = CS.getInstruction();
1808   if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
1809     CI->setName("call");
1810 
1811   // Emit any writebacks immediately.  Arguably this should happen
1812   // after any return-value munging.
1813   if (CallArgs.hasWritebacks())
1814     emitWritebacks(*this, CallArgs);
1815 
1816   switch (RetAI.getKind()) {
1817   case ABIArgInfo::Indirect: {
1818     unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
1819     if (RetTy->isAnyComplexType())
1820       return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
1821     if (CodeGenFunction::hasAggregateLLVMType(RetTy))
1822       return RValue::getAggregate(Args[0]);
1823     return RValue::get(EmitLoadOfScalar(Args[0], false, Alignment, RetTy));
1824   }
1825 
1826   case ABIArgInfo::Ignore:
1827     // If we are ignoring an argument that had a result, make sure to
1828     // construct the appropriate return value for our caller.
1829     return GetUndefRValue(RetTy);
1830 
1831   case ABIArgInfo::Extend:
1832   case ABIArgInfo::Direct: {
1833     llvm::Type *RetIRTy = ConvertType(RetTy);
1834     if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
1835       if (RetTy->isAnyComplexType()) {
1836         llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
1837         llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
1838         return RValue::getComplex(std::make_pair(Real, Imag));
1839       }
1840       if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1841         llvm::Value *DestPtr = ReturnValue.getValue();
1842         bool DestIsVolatile = ReturnValue.isVolatile();
1843 
1844         if (!DestPtr) {
1845           DestPtr = CreateMemTemp(RetTy, "agg.tmp");
1846           DestIsVolatile = false;
1847         }
1848         BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
1849         return RValue::getAggregate(DestPtr);
1850       }
1851 
1852       // If the argument doesn't match, perform a bitcast to coerce it.  This
1853       // can happen due to trivial type mismatches.
1854       llvm::Value *V = CI;
1855       if (V->getType() != RetIRTy)
1856         V = Builder.CreateBitCast(V, RetIRTy);
1857       return RValue::get(V);
1858     }
1859 
1860     llvm::Value *DestPtr = ReturnValue.getValue();
1861     bool DestIsVolatile = ReturnValue.isVolatile();
1862 
1863     if (!DestPtr) {
1864       DestPtr = CreateMemTemp(RetTy, "coerce");
1865       DestIsVolatile = false;
1866     }
1867 
1868     // If the value is offset in memory, apply the offset now.
1869     llvm::Value *StorePtr = DestPtr;
1870     if (unsigned Offs = RetAI.getDirectOffset()) {
1871       StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
1872       StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
1873       StorePtr = Builder.CreateBitCast(StorePtr,
1874                          llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1875     }
1876     CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
1877 
1878     unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
1879     if (RetTy->isAnyComplexType())
1880       return RValue::getComplex(LoadComplexFromAddr(DestPtr, false));
1881     if (CodeGenFunction::hasAggregateLLVMType(RetTy))
1882       return RValue::getAggregate(DestPtr);
1883     return RValue::get(EmitLoadOfScalar(DestPtr, false, Alignment, RetTy));
1884   }
1885 
1886   case ABIArgInfo::Expand:
1887     llvm_unreachable("Invalid ABI kind for return argument");
1888   }
1889 
1890   llvm_unreachable("Unhandled ABIArgInfo::Kind");
1891 }
1892 
1893 /* VarArg handling */
1894 
1895 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
1896   return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
1897 }
1898