1 //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
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 "ABIInfo.h"
17 #include "CGCXXABI.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "TargetInfo.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/CodeGen/CGFunctionInfo.h"
26 #include "clang/Frontend/CodeGenOptions.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/InlineAsm.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 using namespace clang;
35 using namespace CodeGen;
36 
37 /***/
38 
39 static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
40   switch (CC) {
41   default: return llvm::CallingConv::C;
42   case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
43   case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
44   case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
45   case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
46   case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
47   case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
48   case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
49   case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
50   // TODO: add support for CC_X86Pascal to llvm
51   }
52 }
53 
54 /// Derives the 'this' type for codegen purposes, i.e. ignoring method
55 /// qualification.
56 /// FIXME: address space qualification?
57 static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
58   QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
59   return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
60 }
61 
62 /// Returns the canonical formal type of the given C++ method.
63 static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
64   return MD->getType()->getCanonicalTypeUnqualified()
65            .getAs<FunctionProtoType>();
66 }
67 
68 /// Returns the "extra-canonicalized" return type, which discards
69 /// qualifiers on the return type.  Codegen doesn't care about them,
70 /// and it makes ABI code a little easier to be able to assume that
71 /// all parameter and return types are top-level unqualified.
72 static CanQualType GetReturnType(QualType RetTy) {
73   return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
74 }
75 
76 /// Arrange the argument and result information for a value of the given
77 /// unprototyped freestanding function type.
78 const CGFunctionInfo &
79 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
80   // When translating an unprototyped function type, always use a
81   // variadic type.
82   return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
83                                  false, None, FTNP->getExtInfo(),
84                                  RequiredArgs(0));
85 }
86 
87 /// Arrange the LLVM function layout for a value of the given function
88 /// type, on top of any implicit parameters already stored.  Use the
89 /// given ExtInfo instead of the ExtInfo from the function type.
90 static const CGFunctionInfo &arrangeLLVMFunctionInfo(CodeGenTypes &CGT,
91                                                      bool IsInstanceMethod,
92                                        SmallVectorImpl<CanQualType> &prefix,
93                                              CanQual<FunctionProtoType> FTP,
94                                               FunctionType::ExtInfo extInfo) {
95   RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
96   // FIXME: Kill copy.
97   for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
98     prefix.push_back(FTP->getParamType(i));
99   CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
100   return CGT.arrangeLLVMFunctionInfo(resultType, IsInstanceMethod, prefix,
101                                      extInfo, required);
102 }
103 
104 /// Arrange the argument and result information for a free function (i.e.
105 /// not a C++ or ObjC instance method) of the given type.
106 static const CGFunctionInfo &arrangeFreeFunctionType(CodeGenTypes &CGT,
107                                       SmallVectorImpl<CanQualType> &prefix,
108                                             CanQual<FunctionProtoType> FTP) {
109   return arrangeLLVMFunctionInfo(CGT, false, prefix, FTP, FTP->getExtInfo());
110 }
111 
112 /// Arrange the argument and result information for a free function (i.e.
113 /// not a C++ or ObjC instance method) of the given type.
114 static const CGFunctionInfo &arrangeCXXMethodType(CodeGenTypes &CGT,
115                                       SmallVectorImpl<CanQualType> &prefix,
116                                             CanQual<FunctionProtoType> FTP) {
117   FunctionType::ExtInfo extInfo = FTP->getExtInfo();
118   return arrangeLLVMFunctionInfo(CGT, true, prefix, FTP, extInfo);
119 }
120 
121 /// Arrange the argument and result information for a value of the
122 /// given freestanding function type.
123 const CGFunctionInfo &
124 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
125   SmallVector<CanQualType, 16> argTypes;
126   return ::arrangeFreeFunctionType(*this, argTypes, FTP);
127 }
128 
129 static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
130   // Set the appropriate calling convention for the Function.
131   if (D->hasAttr<StdCallAttr>())
132     return CC_X86StdCall;
133 
134   if (D->hasAttr<FastCallAttr>())
135     return CC_X86FastCall;
136 
137   if (D->hasAttr<ThisCallAttr>())
138     return CC_X86ThisCall;
139 
140   if (D->hasAttr<PascalAttr>())
141     return CC_X86Pascal;
142 
143   if (PcsAttr *PCS = D->getAttr<PcsAttr>())
144     return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
145 
146   if (D->hasAttr<PnaclCallAttr>())
147     return CC_PnaclCall;
148 
149   if (D->hasAttr<IntelOclBiccAttr>())
150     return CC_IntelOclBicc;
151 
152   if (D->hasAttr<MSABIAttr>())
153     return IsWindows ? CC_C : CC_X86_64Win64;
154 
155   if (D->hasAttr<SysVABIAttr>())
156     return IsWindows ? CC_X86_64SysV : CC_C;
157 
158   return CC_C;
159 }
160 
161 /// Arrange the argument and result information for a call to an
162 /// unknown C++ non-static member function of the given abstract type.
163 /// (Zero value of RD means we don't have any meaningful "this" argument type,
164 ///  so fall back to a generic pointer type).
165 /// The member function must be an ordinary function, i.e. not a
166 /// constructor or destructor.
167 const CGFunctionInfo &
168 CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
169                                    const FunctionProtoType *FTP) {
170   SmallVector<CanQualType, 16> argTypes;
171 
172   // Add the 'this' pointer.
173   if (RD)
174     argTypes.push_back(GetThisType(Context, RD));
175   else
176     argTypes.push_back(Context.VoidPtrTy);
177 
178   return ::arrangeCXXMethodType(*this, argTypes,
179               FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
180 }
181 
182 /// Arrange the argument and result information for a declaration or
183 /// definition of the given C++ non-static member function.  The
184 /// member function must be an ordinary function, i.e. not a
185 /// constructor or destructor.
186 const CGFunctionInfo &
187 CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
188   assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
189   assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
190 
191   CanQual<FunctionProtoType> prototype = GetFormalType(MD);
192 
193   if (MD->isInstance()) {
194     // The abstract case is perfectly fine.
195     const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
196     return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
197   }
198 
199   return arrangeFreeFunctionType(prototype);
200 }
201 
202 /// Arrange the argument and result information for a declaration
203 /// or definition to the given constructor variant.
204 const CGFunctionInfo &
205 CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
206                                                CXXCtorType ctorKind) {
207   SmallVector<CanQualType, 16> argTypes;
208   argTypes.push_back(GetThisType(Context, D->getParent()));
209 
210   GlobalDecl GD(D, ctorKind);
211   CanQualType resultType =
212     TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
213 
214   CanQual<FunctionProtoType> FTP = GetFormalType(D);
215 
216   // Add the formal parameters.
217   for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
218     argTypes.push_back(FTP->getParamType(i));
219 
220   TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
221 
222   RequiredArgs required =
223       (D->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
224 
225   FunctionType::ExtInfo extInfo = FTP->getExtInfo();
226   return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo, required);
227 }
228 
229 /// Arrange a call to a C++ method, passing the given arguments.
230 const CGFunctionInfo &
231 CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
232                                         const CXXConstructorDecl *D,
233                                         CXXCtorType CtorKind,
234                                         unsigned ExtraArgs) {
235   // FIXME: Kill copy.
236   SmallVector<CanQualType, 16> ArgTypes;
237   for (CallArgList::const_iterator i = args.begin(), e = args.end(); i != e;
238        ++i)
239     ArgTypes.push_back(Context.getCanonicalParamType(i->Ty));
240 
241   CanQual<FunctionProtoType> FPT = GetFormalType(D);
242   RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
243   GlobalDecl GD(D, CtorKind);
244   CanQualType ResultType =
245       TheCXXABI.HasThisReturn(GD) ? ArgTypes.front() : Context.VoidTy;
246 
247   FunctionType::ExtInfo Info = FPT->getExtInfo();
248   return arrangeLLVMFunctionInfo(ResultType, true, ArgTypes, Info, Required);
249 }
250 
251 /// Arrange the argument and result information for a declaration,
252 /// definition, or call to the given destructor variant.  It so
253 /// happens that all three cases produce the same information.
254 const CGFunctionInfo &
255 CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
256                                    CXXDtorType dtorKind) {
257   SmallVector<CanQualType, 2> argTypes;
258   argTypes.push_back(GetThisType(Context, D->getParent()));
259 
260   GlobalDecl GD(D, dtorKind);
261   CanQualType resultType =
262     TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
263 
264   TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
265 
266   CanQual<FunctionProtoType> FTP = GetFormalType(D);
267   assert(FTP->getNumParams() == 0 && "dtor with formal parameters");
268   assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
269 
270   FunctionType::ExtInfo extInfo = FTP->getExtInfo();
271   return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo,
272                                  RequiredArgs::All);
273 }
274 
275 /// Arrange the argument and result information for the declaration or
276 /// definition of the given function.
277 const CGFunctionInfo &
278 CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
279   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
280     if (MD->isInstance())
281       return arrangeCXXMethodDeclaration(MD);
282 
283   CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
284 
285   assert(isa<FunctionType>(FTy));
286 
287   // When declaring a function without a prototype, always use a
288   // non-variadic type.
289   if (isa<FunctionNoProtoType>(FTy)) {
290     CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
291     return arrangeLLVMFunctionInfo(noProto->getReturnType(), false, None,
292                                    noProto->getExtInfo(), RequiredArgs::All);
293   }
294 
295   assert(isa<FunctionProtoType>(FTy));
296   return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
297 }
298 
299 /// Arrange the argument and result information for the declaration or
300 /// definition of an Objective-C method.
301 const CGFunctionInfo &
302 CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
303   // It happens that this is the same as a call with no optional
304   // arguments, except also using the formal 'self' type.
305   return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
306 }
307 
308 /// Arrange the argument and result information for the function type
309 /// through which to perform a send to the given Objective-C method,
310 /// using the given receiver type.  The receiver type is not always
311 /// the 'self' type of the method or even an Objective-C pointer type.
312 /// This is *not* the right method for actually performing such a
313 /// message send, due to the possibility of optional arguments.
314 const CGFunctionInfo &
315 CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
316                                               QualType receiverType) {
317   SmallVector<CanQualType, 16> argTys;
318   argTys.push_back(Context.getCanonicalParamType(receiverType));
319   argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
320   // FIXME: Kill copy?
321   for (const auto *I : MD->params()) {
322     argTys.push_back(Context.getCanonicalParamType(I->getType()));
323   }
324 
325   FunctionType::ExtInfo einfo;
326   bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
327   einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
328 
329   if (getContext().getLangOpts().ObjCAutoRefCount &&
330       MD->hasAttr<NSReturnsRetainedAttr>())
331     einfo = einfo.withProducesResult(true);
332 
333   RequiredArgs required =
334     (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
335 
336   return arrangeLLVMFunctionInfo(GetReturnType(MD->getReturnType()), false,
337                                  argTys, einfo, required);
338 }
339 
340 const CGFunctionInfo &
341 CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
342   // FIXME: Do we need to handle ObjCMethodDecl?
343   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
344 
345   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
346     return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
347 
348   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
349     return arrangeCXXDestructor(DD, GD.getDtorType());
350 
351   return arrangeFunctionDeclaration(FD);
352 }
353 
354 /// Arrange a call as unto a free function, except possibly with an
355 /// additional number of formal parameters considered required.
356 static const CGFunctionInfo &
357 arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
358                             CodeGenModule &CGM,
359                             const CallArgList &args,
360                             const FunctionType *fnType,
361                             unsigned numExtraRequiredArgs) {
362   assert(args.size() >= numExtraRequiredArgs);
363 
364   // In most cases, there are no optional arguments.
365   RequiredArgs required = RequiredArgs::All;
366 
367   // If we have a variadic prototype, the required arguments are the
368   // extra prefix plus the arguments in the prototype.
369   if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
370     if (proto->isVariadic())
371       required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
372 
373   // If we don't have a prototype at all, but we're supposed to
374   // explicitly use the variadic convention for unprototyped calls,
375   // treat all of the arguments as required but preserve the nominal
376   // possibility of variadics.
377   } else if (CGM.getTargetCodeGenInfo()
378                 .isNoProtoCallVariadic(args,
379                                        cast<FunctionNoProtoType>(fnType))) {
380     required = RequiredArgs(args.size());
381   }
382 
383   return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
384                                      fnType->getExtInfo(), required);
385 }
386 
387 /// Figure out the rules for calling a function with the given formal
388 /// type using the given arguments.  The arguments are necessary
389 /// because the function might be unprototyped, in which case it's
390 /// target-dependent in crazy ways.
391 const CGFunctionInfo &
392 CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
393                                       const FunctionType *fnType) {
394   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
395 }
396 
397 /// A block function call is essentially a free-function call with an
398 /// extra implicit argument.
399 const CGFunctionInfo &
400 CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
401                                        const FunctionType *fnType) {
402   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
403 }
404 
405 const CGFunctionInfo &
406 CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
407                                       const CallArgList &args,
408                                       FunctionType::ExtInfo info,
409                                       RequiredArgs required) {
410   // FIXME: Kill copy.
411   SmallVector<CanQualType, 16> argTypes;
412   for (CallArgList::const_iterator i = args.begin(), e = args.end();
413        i != e; ++i)
414     argTypes.push_back(Context.getCanonicalParamType(i->Ty));
415   return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
416                                  info, required);
417 }
418 
419 /// Arrange a call to a C++ method, passing the given arguments.
420 const CGFunctionInfo &
421 CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
422                                    const FunctionProtoType *FPT,
423                                    RequiredArgs required) {
424   // FIXME: Kill copy.
425   SmallVector<CanQualType, 16> argTypes;
426   for (CallArgList::const_iterator i = args.begin(), e = args.end();
427        i != e; ++i)
428     argTypes.push_back(Context.getCanonicalParamType(i->Ty));
429 
430   FunctionType::ExtInfo info = FPT->getExtInfo();
431   return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
432                                  argTypes, info, required);
433 }
434 
435 const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
436     QualType resultType, const FunctionArgList &args,
437     const FunctionType::ExtInfo &info, bool isVariadic) {
438   // FIXME: Kill copy.
439   SmallVector<CanQualType, 16> argTypes;
440   for (FunctionArgList::const_iterator i = args.begin(), e = args.end();
441        i != e; ++i)
442     argTypes.push_back(Context.getCanonicalParamType((*i)->getType()));
443 
444   RequiredArgs required =
445     (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
446   return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
447                                  required);
448 }
449 
450 const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
451   return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
452                                  FunctionType::ExtInfo(), RequiredArgs::All);
453 }
454 
455 /// Arrange the argument and result information for an abstract value
456 /// of a given function type.  This is the method which all of the
457 /// above functions ultimately defer to.
458 const CGFunctionInfo &
459 CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
460                                       bool IsInstanceMethod,
461                                       ArrayRef<CanQualType> argTypes,
462                                       FunctionType::ExtInfo info,
463                                       RequiredArgs required) {
464 #ifndef NDEBUG
465   for (ArrayRef<CanQualType>::const_iterator
466          I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
467     assert(I->isCanonicalAsParam());
468 #endif
469 
470   unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
471 
472   // Lookup or create unique function info.
473   llvm::FoldingSetNodeID ID;
474   CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
475                           argTypes);
476 
477   void *insertPos = 0;
478   CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
479   if (FI)
480     return *FI;
481 
482   // Construct the function info.  We co-allocate the ArgInfos.
483   FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
484                               required);
485   FunctionInfos.InsertNode(FI, insertPos);
486 
487   bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
488   assert(inserted && "Recursively being processed?");
489 
490   // Compute ABI information.
491   getABIInfo().computeInfo(*FI);
492 
493   // Loop over all of the computed argument and return value info.  If any of
494   // them are direct or extend without a specified coerce type, specify the
495   // default now.
496   ABIArgInfo &retInfo = FI->getReturnInfo();
497   if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == 0)
498     retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
499 
500   for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end();
501        I != E; ++I)
502     if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0)
503       I->info.setCoerceToType(ConvertType(I->type));
504 
505   bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
506   assert(erased && "Not in set?");
507 
508   return *FI;
509 }
510 
511 CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
512                                        bool IsInstanceMethod,
513                                        const FunctionType::ExtInfo &info,
514                                        CanQualType resultType,
515                                        ArrayRef<CanQualType> argTypes,
516                                        RequiredArgs required) {
517   void *buffer = operator new(sizeof(CGFunctionInfo) +
518                               sizeof(ArgInfo) * (argTypes.size() + 1));
519   CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
520   FI->CallingConvention = llvmCC;
521   FI->EffectiveCallingConvention = llvmCC;
522   FI->ASTCallingConvention = info.getCC();
523   FI->InstanceMethod = IsInstanceMethod;
524   FI->NoReturn = info.getNoReturn();
525   FI->ReturnsRetained = info.getProducesResult();
526   FI->Required = required;
527   FI->HasRegParm = info.getHasRegParm();
528   FI->RegParm = info.getRegParm();
529   FI->ArgStruct = 0;
530   FI->NumArgs = argTypes.size();
531   FI->getArgsBuffer()[0].type = resultType;
532   for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
533     FI->getArgsBuffer()[i + 1].type = argTypes[i];
534   return FI;
535 }
536 
537 /***/
538 
539 void CodeGenTypes::GetExpandedTypes(QualType type,
540                      SmallVectorImpl<llvm::Type*> &expandedTypes) {
541   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
542     uint64_t NumElts = AT->getSize().getZExtValue();
543     for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
544       GetExpandedTypes(AT->getElementType(), expandedTypes);
545   } else if (const RecordType *RT = type->getAs<RecordType>()) {
546     const RecordDecl *RD = RT->getDecl();
547     assert(!RD->hasFlexibleArrayMember() &&
548            "Cannot expand structure with flexible array.");
549     if (RD->isUnion()) {
550       // Unions can be here only in degenerative cases - all the fields are same
551       // after flattening. Thus we have to use the "largest" field.
552       const FieldDecl *LargestFD = 0;
553       CharUnits UnionSize = CharUnits::Zero();
554 
555       for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
556            i != e; ++i) {
557         const FieldDecl *FD = *i;
558         assert(!FD->isBitField() &&
559                "Cannot expand structure with bit-field members.");
560         CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
561         if (UnionSize < FieldSize) {
562           UnionSize = FieldSize;
563           LargestFD = FD;
564         }
565       }
566       if (LargestFD)
567         GetExpandedTypes(LargestFD->getType(), expandedTypes);
568     } else {
569       for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
570            i != e; ++i) {
571         assert(!i->isBitField() &&
572                "Cannot expand structure with bit-field members.");
573         GetExpandedTypes(i->getType(), expandedTypes);
574       }
575     }
576   } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
577     llvm::Type *EltTy = ConvertType(CT->getElementType());
578     expandedTypes.push_back(EltTy);
579     expandedTypes.push_back(EltTy);
580   } else
581     expandedTypes.push_back(ConvertType(type));
582 }
583 
584 llvm::Function::arg_iterator
585 CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
586                                     llvm::Function::arg_iterator AI) {
587   assert(LV.isSimple() &&
588          "Unexpected non-simple lvalue during struct expansion.");
589 
590   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
591     unsigned NumElts = AT->getSize().getZExtValue();
592     QualType EltTy = AT->getElementType();
593     for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
594       llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
595       LValue LV = MakeAddrLValue(EltAddr, EltTy);
596       AI = ExpandTypeFromArgs(EltTy, LV, AI);
597     }
598   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
599     RecordDecl *RD = RT->getDecl();
600     if (RD->isUnion()) {
601       // Unions can be here only in degenerative cases - all the fields are same
602       // after flattening. Thus we have to use the "largest" field.
603       const FieldDecl *LargestFD = 0;
604       CharUnits UnionSize = CharUnits::Zero();
605 
606       for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
607            i != e; ++i) {
608         const FieldDecl *FD = *i;
609         assert(!FD->isBitField() &&
610                "Cannot expand structure with bit-field members.");
611         CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
612         if (UnionSize < FieldSize) {
613           UnionSize = FieldSize;
614           LargestFD = FD;
615         }
616       }
617       if (LargestFD) {
618         // FIXME: What are the right qualifiers here?
619         LValue SubLV = EmitLValueForField(LV, LargestFD);
620         AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
621       }
622     } else {
623       for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
624            i != e; ++i) {
625         FieldDecl *FD = *i;
626         QualType FT = FD->getType();
627 
628         // FIXME: What are the right qualifiers here?
629         LValue SubLV = EmitLValueForField(LV, FD);
630         AI = ExpandTypeFromArgs(FT, SubLV, AI);
631       }
632     }
633   } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
634     QualType EltTy = CT->getElementType();
635     llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
636     EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
637     llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
638     EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
639   } else {
640     EmitStoreThroughLValue(RValue::get(AI), LV);
641     ++AI;
642   }
643 
644   return AI;
645 }
646 
647 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
648 /// accessing some number of bytes out of it, try to gep into the struct to get
649 /// at its inner goodness.  Dive as deep as possible without entering an element
650 /// with an in-memory size smaller than DstSize.
651 static llvm::Value *
652 EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
653                                    llvm::StructType *SrcSTy,
654                                    uint64_t DstSize, CodeGenFunction &CGF) {
655   // We can't dive into a zero-element struct.
656   if (SrcSTy->getNumElements() == 0) return SrcPtr;
657 
658   llvm::Type *FirstElt = SrcSTy->getElementType(0);
659 
660   // If the first elt is at least as large as what we're looking for, or if the
661   // first element is the same size as the whole struct, we can enter it.
662   uint64_t FirstEltSize =
663     CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
664   if (FirstEltSize < DstSize &&
665       FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
666     return SrcPtr;
667 
668   // GEP into the first element.
669   SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
670 
671   // If the first element is a struct, recurse.
672   llvm::Type *SrcTy =
673     cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
674   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
675     return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
676 
677   return SrcPtr;
678 }
679 
680 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
681 /// are either integers or pointers.  This does a truncation of the value if it
682 /// is too large or a zero extension if it is too small.
683 ///
684 /// This behaves as if the value were coerced through memory, so on big-endian
685 /// targets the high bits are preserved in a truncation, while little-endian
686 /// targets preserve the low bits.
687 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
688                                              llvm::Type *Ty,
689                                              CodeGenFunction &CGF) {
690   if (Val->getType() == Ty)
691     return Val;
692 
693   if (isa<llvm::PointerType>(Val->getType())) {
694     // If this is Pointer->Pointer avoid conversion to and from int.
695     if (isa<llvm::PointerType>(Ty))
696       return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
697 
698     // Convert the pointer to an integer so we can play with its width.
699     Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
700   }
701 
702   llvm::Type *DestIntTy = Ty;
703   if (isa<llvm::PointerType>(DestIntTy))
704     DestIntTy = CGF.IntPtrTy;
705 
706   if (Val->getType() != DestIntTy) {
707     const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
708     if (DL.isBigEndian()) {
709       // Preserve the high bits on big-endian targets.
710       // That is what memory coercion does.
711       uint64_t SrcSize = DL.getTypeAllocSizeInBits(Val->getType());
712       uint64_t DstSize = DL.getTypeAllocSizeInBits(DestIntTy);
713       if (SrcSize > DstSize) {
714         Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
715         Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
716       } else {
717         Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
718         Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
719       }
720     } else {
721       // Little-endian targets preserve the low bits. No shifts required.
722       Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
723     }
724   }
725 
726   if (isa<llvm::PointerType>(Ty))
727     Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
728   return Val;
729 }
730 
731 
732 
733 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
734 /// a pointer to an object of type \arg Ty.
735 ///
736 /// This safely handles the case when the src type is smaller than the
737 /// destination type; in this situation the values of bits which not
738 /// present in the src are undefined.
739 static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
740                                       llvm::Type *Ty,
741                                       CodeGenFunction &CGF) {
742   llvm::Type *SrcTy =
743     cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
744 
745   // If SrcTy and Ty are the same, just do a load.
746   if (SrcTy == Ty)
747     return CGF.Builder.CreateLoad(SrcPtr);
748 
749   uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
750 
751   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
752     SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
753     SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
754   }
755 
756   uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
757 
758   // If the source and destination are integer or pointer types, just do an
759   // extension or truncation to the desired type.
760   if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
761       (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
762     llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
763     return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
764   }
765 
766   // If load is legal, just bitcast the src pointer.
767   if (SrcSize >= DstSize) {
768     // Generally SrcSize is never greater than DstSize, since this means we are
769     // losing bits. However, this can happen in cases where the structure has
770     // additional padding, for example due to a user specified alignment.
771     //
772     // FIXME: Assert that we aren't truncating non-padding bits when have access
773     // to that information.
774     llvm::Value *Casted =
775       CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
776     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
777     // FIXME: Use better alignment / avoid requiring aligned load.
778     Load->setAlignment(1);
779     return Load;
780   }
781 
782   // Otherwise do coercion through memory. This is stupid, but
783   // simple.
784   llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
785   llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
786   llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
787   llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
788   // FIXME: Use better alignment.
789   CGF.Builder.CreateMemCpy(Casted, SrcCasted,
790       llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
791       1, false);
792   return CGF.Builder.CreateLoad(Tmp);
793 }
794 
795 // Function to store a first-class aggregate into memory.  We prefer to
796 // store the elements rather than the aggregate to be more friendly to
797 // fast-isel.
798 // FIXME: Do we need to recurse here?
799 static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
800                           llvm::Value *DestPtr, bool DestIsVolatile,
801                           bool LowAlignment) {
802   // Prefer scalar stores to first-class aggregate stores.
803   if (llvm::StructType *STy =
804         dyn_cast<llvm::StructType>(Val->getType())) {
805     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
806       llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
807       llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
808       llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
809                                                     DestIsVolatile);
810       if (LowAlignment)
811         SI->setAlignment(1);
812     }
813   } else {
814     llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
815     if (LowAlignment)
816       SI->setAlignment(1);
817   }
818 }
819 
820 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
821 /// where the source and destination may have different types.
822 ///
823 /// This safely handles the case when the src type is larger than the
824 /// destination type; the upper bits of the src will be lost.
825 static void CreateCoercedStore(llvm::Value *Src,
826                                llvm::Value *DstPtr,
827                                bool DstIsVolatile,
828                                CodeGenFunction &CGF) {
829   llvm::Type *SrcTy = Src->getType();
830   llvm::Type *DstTy =
831     cast<llvm::PointerType>(DstPtr->getType())->getElementType();
832   if (SrcTy == DstTy) {
833     CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
834     return;
835   }
836 
837   uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
838 
839   if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
840     DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
841     DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
842   }
843 
844   // If the source and destination are integer or pointer types, just do an
845   // extension or truncation to the desired type.
846   if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
847       (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
848     Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
849     CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
850     return;
851   }
852 
853   uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
854 
855   // If store is legal, just bitcast the src pointer.
856   if (SrcSize <= DstSize) {
857     llvm::Value *Casted =
858       CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
859     // FIXME: Use better alignment / avoid requiring aligned store.
860     BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
861   } else {
862     // Otherwise do coercion through memory. This is stupid, but
863     // simple.
864 
865     // Generally SrcSize is never greater than DstSize, since this means we are
866     // losing bits. However, this can happen in cases where the structure has
867     // additional padding, for example due to a user specified alignment.
868     //
869     // FIXME: Assert that we aren't truncating non-padding bits when have access
870     // to that information.
871     llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
872     CGF.Builder.CreateStore(Src, Tmp);
873     llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
874     llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
875     llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
876     // FIXME: Use better alignment.
877     CGF.Builder.CreateMemCpy(DstCasted, Casted,
878         llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
879         1, false);
880   }
881 }
882 
883 /***/
884 
885 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
886   return FI.getReturnInfo().isIndirect();
887 }
888 
889 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
890   if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
891     switch (BT->getKind()) {
892     default:
893       return false;
894     case BuiltinType::Float:
895       return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
896     case BuiltinType::Double:
897       return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
898     case BuiltinType::LongDouble:
899       return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
900     }
901   }
902 
903   return false;
904 }
905 
906 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
907   if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
908     if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
909       if (BT->getKind() == BuiltinType::LongDouble)
910         return getTarget().useObjCFP2RetForComplexLongDouble();
911     }
912   }
913 
914   return false;
915 }
916 
917 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
918   const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
919   return GetFunctionType(FI);
920 }
921 
922 llvm::FunctionType *
923 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
924 
925   bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
926   assert(Inserted && "Recursively being processed?");
927 
928   SmallVector<llvm::Type*, 8> argTypes;
929   llvm::Type *resultType = 0;
930 
931   const ABIArgInfo &retAI = FI.getReturnInfo();
932   switch (retAI.getKind()) {
933   case ABIArgInfo::Expand:
934     llvm_unreachable("Invalid ABI kind for return argument");
935 
936   case ABIArgInfo::Extend:
937   case ABIArgInfo::Direct:
938     resultType = retAI.getCoerceToType();
939     break;
940 
941   case ABIArgInfo::InAlloca:
942     if (retAI.getInAllocaSRet()) {
943       // sret things on win32 aren't void, they return the sret pointer.
944       QualType ret = FI.getReturnType();
945       llvm::Type *ty = ConvertType(ret);
946       unsigned addressSpace = Context.getTargetAddressSpace(ret);
947       resultType = llvm::PointerType::get(ty, addressSpace);
948     } else {
949       resultType = llvm::Type::getVoidTy(getLLVMContext());
950     }
951     break;
952 
953   case ABIArgInfo::Indirect: {
954     assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
955     resultType = llvm::Type::getVoidTy(getLLVMContext());
956 
957     QualType ret = FI.getReturnType();
958     llvm::Type *ty = ConvertType(ret);
959     unsigned addressSpace = Context.getTargetAddressSpace(ret);
960     argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
961     break;
962   }
963 
964   case ABIArgInfo::Ignore:
965     resultType = llvm::Type::getVoidTy(getLLVMContext());
966     break;
967   }
968 
969   // Add in all of the required arguments.
970   CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
971   if (FI.isVariadic()) {
972     ie = it + FI.getRequiredArgs().getNumRequiredArgs();
973   } else {
974     ie = FI.arg_end();
975   }
976   for (; it != ie; ++it) {
977     const ABIArgInfo &argAI = it->info;
978 
979     // Insert a padding type to ensure proper alignment.
980     if (llvm::Type *PaddingType = argAI.getPaddingType())
981       argTypes.push_back(PaddingType);
982 
983     switch (argAI.getKind()) {
984     case ABIArgInfo::Ignore:
985     case ABIArgInfo::InAlloca:
986       break;
987 
988     case ABIArgInfo::Indirect: {
989       // indirect arguments are always on the stack, which is addr space #0.
990       llvm::Type *LTy = ConvertTypeForMem(it->type);
991       argTypes.push_back(LTy->getPointerTo());
992       break;
993     }
994 
995     case ABIArgInfo::Extend:
996     case ABIArgInfo::Direct: {
997       // If the coerce-to type is a first class aggregate, flatten it.  Either
998       // way is semantically identical, but fast-isel and the optimizer
999       // generally likes scalar values better than FCAs.
1000       llvm::Type *argType = argAI.getCoerceToType();
1001       if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
1002         for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1003           argTypes.push_back(st->getElementType(i));
1004       } else {
1005         argTypes.push_back(argType);
1006       }
1007       break;
1008     }
1009 
1010     case ABIArgInfo::Expand:
1011       GetExpandedTypes(it->type, argTypes);
1012       break;
1013     }
1014   }
1015 
1016   // Add the inalloca struct as the last parameter type.
1017   if (llvm::StructType *ArgStruct = FI.getArgStruct())
1018     argTypes.push_back(ArgStruct->getPointerTo());
1019 
1020   bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1021   assert(Erased && "Not in set?");
1022 
1023   return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
1024 }
1025 
1026 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
1027   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1028   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1029 
1030   if (!isFuncTypeConvertible(FPT))
1031     return llvm::StructType::get(getLLVMContext());
1032 
1033   const CGFunctionInfo *Info;
1034   if (isa<CXXDestructorDecl>(MD))
1035     Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
1036   else
1037     Info = &arrangeCXXMethodDeclaration(MD);
1038   return GetFunctionType(*Info);
1039 }
1040 
1041 void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
1042                                            const Decl *TargetDecl,
1043                                            AttributeListType &PAL,
1044                                            unsigned &CallingConv,
1045                                            bool AttrOnCallSite) {
1046   llvm::AttrBuilder FuncAttrs;
1047   llvm::AttrBuilder RetAttrs;
1048 
1049   CallingConv = FI.getEffectiveCallingConvention();
1050 
1051   if (FI.isNoReturn())
1052     FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1053 
1054   // FIXME: handle sseregparm someday...
1055   if (TargetDecl) {
1056     if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
1057       FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
1058     if (TargetDecl->hasAttr<NoThrowAttr>())
1059       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1060     if (TargetDecl->hasAttr<NoReturnAttr>())
1061       FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1062     if (TargetDecl->hasAttr<NoDuplicateAttr>())
1063       FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
1064 
1065     if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
1066       const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
1067       if (FPT && FPT->isNothrow(getContext()))
1068         FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1069       // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1070       // These attributes are not inherited by overloads.
1071       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1072       if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
1073         FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1074     }
1075 
1076     // 'const' and 'pure' attribute functions are also nounwind.
1077     if (TargetDecl->hasAttr<ConstAttr>()) {
1078       FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1079       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1080     } else if (TargetDecl->hasAttr<PureAttr>()) {
1081       FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1082       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1083     }
1084     if (TargetDecl->hasAttr<MallocAttr>())
1085       RetAttrs.addAttribute(llvm::Attribute::NoAlias);
1086   }
1087 
1088   if (CodeGenOpts.OptimizeSize)
1089     FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1090   if (CodeGenOpts.OptimizeSize == 2)
1091     FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1092   if (CodeGenOpts.DisableRedZone)
1093     FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1094   if (CodeGenOpts.NoImplicitFloat)
1095     FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1096 
1097   if (AttrOnCallSite) {
1098     // Attributes that should go on the call site only.
1099     if (!CodeGenOpts.SimplifyLibCalls)
1100       FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1101   } else {
1102     // Attributes that should go on the function, but not the call site.
1103     if (!CodeGenOpts.DisableFPElim) {
1104       FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1105     } else if (CodeGenOpts.OmitLeafFramePointer) {
1106       FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1107       FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1108     } else {
1109       FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
1110       FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1111     }
1112 
1113     FuncAttrs.addAttribute("less-precise-fpmad",
1114                            llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
1115     FuncAttrs.addAttribute("no-infs-fp-math",
1116                            llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
1117     FuncAttrs.addAttribute("no-nans-fp-math",
1118                            llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
1119     FuncAttrs.addAttribute("unsafe-fp-math",
1120                            llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
1121     FuncAttrs.addAttribute("use-soft-float",
1122                            llvm::toStringRef(CodeGenOpts.SoftFloat));
1123     FuncAttrs.addAttribute("stack-protector-buffer-size",
1124                            llvm::utostr(CodeGenOpts.SSPBufferSize));
1125 
1126     if (!CodeGenOpts.StackRealignment)
1127       FuncAttrs.addAttribute("no-realign-stack");
1128   }
1129 
1130   QualType RetTy = FI.getReturnType();
1131   unsigned Index = 1;
1132   const ABIArgInfo &RetAI = FI.getReturnInfo();
1133   switch (RetAI.getKind()) {
1134   case ABIArgInfo::Extend:
1135     if (RetTy->hasSignedIntegerRepresentation())
1136       RetAttrs.addAttribute(llvm::Attribute::SExt);
1137     else if (RetTy->hasUnsignedIntegerRepresentation())
1138       RetAttrs.addAttribute(llvm::Attribute::ZExt);
1139     // FALL THROUGH
1140   case ABIArgInfo::Direct:
1141     if (RetAI.getInReg())
1142       RetAttrs.addAttribute(llvm::Attribute::InReg);
1143     break;
1144   case ABIArgInfo::Ignore:
1145     break;
1146 
1147   case ABIArgInfo::InAlloca: {
1148     // inalloca disables readnone and readonly
1149     FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1150       .removeAttribute(llvm::Attribute::ReadNone);
1151     break;
1152   }
1153 
1154   case ABIArgInfo::Indirect: {
1155     llvm::AttrBuilder SRETAttrs;
1156     SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1157     if (RetAI.getInReg())
1158       SRETAttrs.addAttribute(llvm::Attribute::InReg);
1159     PAL.push_back(llvm::
1160                   AttributeSet::get(getLLVMContext(), Index, SRETAttrs));
1161 
1162     ++Index;
1163     // sret disables readnone and readonly
1164     FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1165       .removeAttribute(llvm::Attribute::ReadNone);
1166     break;
1167   }
1168 
1169   case ABIArgInfo::Expand:
1170     llvm_unreachable("Invalid ABI kind for return argument");
1171   }
1172 
1173   if (RetAttrs.hasAttributes())
1174     PAL.push_back(llvm::
1175                   AttributeSet::get(getLLVMContext(),
1176                                     llvm::AttributeSet::ReturnIndex,
1177                                     RetAttrs));
1178 
1179   for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1180          ie = FI.arg_end(); it != ie; ++it) {
1181     QualType ParamType = it->type;
1182     const ABIArgInfo &AI = it->info;
1183     llvm::AttrBuilder Attrs;
1184 
1185     if (AI.getPaddingType()) {
1186       if (AI.getPaddingInReg())
1187         PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1188                                               llvm::Attribute::InReg));
1189       // Increment Index if there is padding.
1190       ++Index;
1191     }
1192 
1193     // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1194     // have the corresponding parameter variable.  It doesn't make
1195     // sense to do it here because parameters are so messed up.
1196     switch (AI.getKind()) {
1197     case ABIArgInfo::Extend:
1198       if (ParamType->isSignedIntegerOrEnumerationType())
1199         Attrs.addAttribute(llvm::Attribute::SExt);
1200       else if (ParamType->isUnsignedIntegerOrEnumerationType())
1201         Attrs.addAttribute(llvm::Attribute::ZExt);
1202       // FALL THROUGH
1203     case ABIArgInfo::Direct:
1204       if (AI.getInReg())
1205         Attrs.addAttribute(llvm::Attribute::InReg);
1206 
1207       // FIXME: handle sseregparm someday...
1208 
1209       if (llvm::StructType *STy =
1210           dyn_cast<llvm::StructType>(AI.getCoerceToType())) {
1211         unsigned Extra = STy->getNumElements()-1;  // 1 will be added below.
1212         if (Attrs.hasAttributes())
1213           for (unsigned I = 0; I < Extra; ++I)
1214             PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1215                                                   Attrs));
1216         Index += Extra;
1217       }
1218       break;
1219 
1220     case ABIArgInfo::Indirect:
1221       if (AI.getInReg())
1222         Attrs.addAttribute(llvm::Attribute::InReg);
1223 
1224       if (AI.getIndirectByVal())
1225         Attrs.addAttribute(llvm::Attribute::ByVal);
1226 
1227       Attrs.addAlignmentAttr(AI.getIndirectAlign());
1228 
1229       // byval disables readnone and readonly.
1230       FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1231         .removeAttribute(llvm::Attribute::ReadNone);
1232       break;
1233 
1234     case ABIArgInfo::Ignore:
1235       // Skip increment, no matching LLVM parameter.
1236       continue;
1237 
1238     case ABIArgInfo::InAlloca:
1239       // inalloca disables readnone and readonly.
1240       FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1241           .removeAttribute(llvm::Attribute::ReadNone);
1242       // Skip increment, no matching LLVM parameter.
1243       continue;
1244 
1245     case ABIArgInfo::Expand: {
1246       SmallVector<llvm::Type*, 8> types;
1247       // FIXME: This is rather inefficient. Do we ever actually need to do
1248       // anything here? The result should be just reconstructed on the other
1249       // side, so extension should be a non-issue.
1250       getTypes().GetExpandedTypes(ParamType, types);
1251       Index += types.size();
1252       continue;
1253     }
1254     }
1255 
1256     if (Attrs.hasAttributes())
1257       PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
1258     ++Index;
1259   }
1260 
1261   // Add the inalloca attribute to the trailing inalloca parameter if present.
1262   if (FI.usesInAlloca()) {
1263     llvm::AttrBuilder Attrs;
1264     Attrs.addAttribute(llvm::Attribute::InAlloca);
1265     PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
1266   }
1267 
1268   if (FuncAttrs.hasAttributes())
1269     PAL.push_back(llvm::
1270                   AttributeSet::get(getLLVMContext(),
1271                                     llvm::AttributeSet::FunctionIndex,
1272                                     FuncAttrs));
1273 }
1274 
1275 /// An argument came in as a promoted argument; demote it back to its
1276 /// declared type.
1277 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1278                                          const VarDecl *var,
1279                                          llvm::Value *value) {
1280   llvm::Type *varType = CGF.ConvertType(var->getType());
1281 
1282   // This can happen with promotions that actually don't change the
1283   // underlying type, like the enum promotions.
1284   if (value->getType() == varType) return value;
1285 
1286   assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1287          && "unexpected promotion type");
1288 
1289   if (isa<llvm::IntegerType>(varType))
1290     return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1291 
1292   return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1293 }
1294 
1295 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1296                                          llvm::Function *Fn,
1297                                          const FunctionArgList &Args) {
1298   // If this is an implicit-return-zero function, go ahead and
1299   // initialize the return value.  TODO: it might be nice to have
1300   // a more general mechanism for this that didn't require synthesized
1301   // return statements.
1302   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
1303     if (FD->hasImplicitReturnZero()) {
1304       QualType RetTy = FD->getReturnType().getUnqualifiedType();
1305       llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
1306       llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
1307       Builder.CreateStore(Zero, ReturnValue);
1308     }
1309   }
1310 
1311   // FIXME: We no longer need the types from FunctionArgList; lift up and
1312   // simplify.
1313 
1314   // Emit allocs for param decls.  Give the LLVM Argument nodes names.
1315   llvm::Function::arg_iterator AI = Fn->arg_begin();
1316 
1317   // If we're using inalloca, all the memory arguments are GEPs off of the last
1318   // parameter, which is a pointer to the complete memory area.
1319   llvm::Value *ArgStruct = 0;
1320   if (FI.usesInAlloca()) {
1321     llvm::Function::arg_iterator EI = Fn->arg_end();
1322     --EI;
1323     ArgStruct = EI;
1324     assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1325   }
1326 
1327   // Name the struct return argument.
1328   if (CGM.ReturnTypeUsesSRet(FI)) {
1329     AI->setName("agg.result");
1330     AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1331                                         AI->getArgNo() + 1,
1332                                         llvm::Attribute::NoAlias));
1333     ++AI;
1334   }
1335 
1336   // Track if we received the parameter as a pointer (indirect, byval, or
1337   // inalloca).  If already have a pointer, EmitParmDecl doesn't need to copy it
1338   // into a local alloca for us.
1339   enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
1340   typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
1341   SmallVector<ValueAndIsPtr, 16> ArgVals;
1342   ArgVals.reserve(Args.size());
1343 
1344   // Create a pointer value for every parameter declaration.  This usually
1345   // entails copying one or more LLVM IR arguments into an alloca.  Don't push
1346   // any cleanups or do anything that might unwind.  We do that separately, so
1347   // we can push the cleanups in the correct order for the ABI.
1348   assert(FI.arg_size() == Args.size() &&
1349          "Mismatch between function signature & arguments.");
1350   unsigned ArgNo = 1;
1351   CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
1352   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1353        i != e; ++i, ++info_it, ++ArgNo) {
1354     const VarDecl *Arg = *i;
1355     QualType Ty = info_it->type;
1356     const ABIArgInfo &ArgI = info_it->info;
1357 
1358     bool isPromoted =
1359       isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1360 
1361     // Skip the dummy padding argument.
1362     if (ArgI.getPaddingType())
1363       ++AI;
1364 
1365     switch (ArgI.getKind()) {
1366     case ABIArgInfo::InAlloca: {
1367       llvm::Value *V = Builder.CreateStructGEP(
1368           ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1369       ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
1370       continue;  // Don't increment AI!
1371     }
1372 
1373     case ABIArgInfo::Indirect: {
1374       llvm::Value *V = AI;
1375 
1376       if (!hasScalarEvaluationKind(Ty)) {
1377         // Aggregates and complex variables are accessed by reference.  All we
1378         // need to do is realign the value, if requested
1379         if (ArgI.getIndirectRealign()) {
1380           llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1381 
1382           // Copy from the incoming argument pointer to the temporary with the
1383           // appropriate alignment.
1384           //
1385           // FIXME: We should have a common utility for generating an aggregate
1386           // copy.
1387           llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
1388           CharUnits Size = getContext().getTypeSizeInChars(Ty);
1389           llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1390           llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1391           Builder.CreateMemCpy(Dst,
1392                                Src,
1393                                llvm::ConstantInt::get(IntPtrTy,
1394                                                       Size.getQuantity()),
1395                                ArgI.getIndirectAlign(),
1396                                false);
1397           V = AlignedTemp;
1398         }
1399         ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
1400       } else {
1401         // Load scalar value from indirect argument.
1402         CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
1403         V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1404                              Arg->getLocStart());
1405 
1406         if (isPromoted)
1407           V = emitArgumentDemotion(*this, Arg, V);
1408         ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1409       }
1410       break;
1411     }
1412 
1413     case ABIArgInfo::Extend:
1414     case ABIArgInfo::Direct: {
1415 
1416       // If we have the trivial case, handle it with no muss and fuss.
1417       if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
1418           ArgI.getCoerceToType() == ConvertType(Ty) &&
1419           ArgI.getDirectOffset() == 0) {
1420         assert(AI != Fn->arg_end() && "Argument mismatch!");
1421         llvm::Value *V = AI;
1422 
1423         if (Arg->getType().isRestrictQualified())
1424           AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1425                                               AI->getArgNo() + 1,
1426                                               llvm::Attribute::NoAlias));
1427 
1428         // Ensure the argument is the correct type.
1429         if (V->getType() != ArgI.getCoerceToType())
1430           V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1431 
1432         if (isPromoted)
1433           V = emitArgumentDemotion(*this, Arg, V);
1434 
1435         if (const CXXMethodDecl *MD =
1436             dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1437           if (MD->isVirtual() && Arg == CXXABIThisDecl)
1438             V = CGM.getCXXABI().
1439                 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
1440         }
1441 
1442         // Because of merging of function types from multiple decls it is
1443         // possible for the type of an argument to not match the corresponding
1444         // type in the function type. Since we are codegening the callee
1445         // in here, add a cast to the argument type.
1446         llvm::Type *LTy = ConvertType(Arg->getType());
1447         if (V->getType() != LTy)
1448           V = Builder.CreateBitCast(V, LTy);
1449 
1450         ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1451         break;
1452       }
1453 
1454       llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
1455 
1456       // The alignment we need to use is the max of the requested alignment for
1457       // the argument plus the alignment required by our access code below.
1458       unsigned AlignmentToUse =
1459         CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
1460       AlignmentToUse = std::max(AlignmentToUse,
1461                         (unsigned)getContext().getDeclAlign(Arg).getQuantity());
1462 
1463       Alloca->setAlignment(AlignmentToUse);
1464       llvm::Value *V = Alloca;
1465       llvm::Value *Ptr = V;    // Pointer to store into.
1466 
1467       // If the value is offset in memory, apply the offset now.
1468       if (unsigned Offs = ArgI.getDirectOffset()) {
1469         Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1470         Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
1471         Ptr = Builder.CreateBitCast(Ptr,
1472                           llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1473       }
1474 
1475       // If the coerce-to type is a first class aggregate, we flatten it and
1476       // pass the elements. Either way is semantically identical, but fast-isel
1477       // and the optimizer generally likes scalar values better than FCAs.
1478       llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
1479       if (STy && STy->getNumElements() > 1) {
1480         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
1481         llvm::Type *DstTy =
1482           cast<llvm::PointerType>(Ptr->getType())->getElementType();
1483         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
1484 
1485         if (SrcSize <= DstSize) {
1486           Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1487 
1488           for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1489             assert(AI != Fn->arg_end() && "Argument mismatch!");
1490             AI->setName(Arg->getName() + ".coerce" + Twine(i));
1491             llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1492             Builder.CreateStore(AI++, EltPtr);
1493           }
1494         } else {
1495           llvm::AllocaInst *TempAlloca =
1496             CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1497           TempAlloca->setAlignment(AlignmentToUse);
1498           llvm::Value *TempV = TempAlloca;
1499 
1500           for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1501             assert(AI != Fn->arg_end() && "Argument mismatch!");
1502             AI->setName(Arg->getName() + ".coerce" + Twine(i));
1503             llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1504             Builder.CreateStore(AI++, EltPtr);
1505           }
1506 
1507           Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
1508         }
1509       } else {
1510         // Simple case, just do a coerced store of the argument into the alloca.
1511         assert(AI != Fn->arg_end() && "Argument mismatch!");
1512         AI->setName(Arg->getName() + ".coerce");
1513         CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
1514       }
1515 
1516 
1517       // Match to what EmitParmDecl is expecting for this type.
1518       if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
1519         V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
1520         if (isPromoted)
1521           V = emitArgumentDemotion(*this, Arg, V);
1522         ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1523       } else {
1524         ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
1525       }
1526       continue;  // Skip ++AI increment, already done.
1527     }
1528 
1529     case ABIArgInfo::Expand: {
1530       // If this structure was expanded into multiple arguments then
1531       // we need to create a temporary and reconstruct it from the
1532       // arguments.
1533       llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
1534       CharUnits Align = getContext().getDeclAlign(Arg);
1535       Alloca->setAlignment(Align.getQuantity());
1536       LValue LV = MakeAddrLValue(Alloca, Ty, Align);
1537       llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
1538       ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
1539 
1540       // Name the arguments used in expansion and increment AI.
1541       unsigned Index = 0;
1542       for (; AI != End; ++AI, ++Index)
1543         AI->setName(Arg->getName() + "." + Twine(Index));
1544       continue;
1545     }
1546 
1547     case ABIArgInfo::Ignore:
1548       // Initialize the local variable appropriately.
1549       if (!hasScalarEvaluationKind(Ty)) {
1550         ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1551       } else {
1552         llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1553         ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1554       }
1555 
1556       // Skip increment, no matching LLVM parameter.
1557       continue;
1558     }
1559 
1560     ++AI;
1561   }
1562 
1563   if (FI.usesInAlloca())
1564     ++AI;
1565   assert(AI == Fn->arg_end() && "Argument mismatch!");
1566 
1567   if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1568     for (int I = Args.size() - 1; I >= 0; --I)
1569       EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1570                    I + 1);
1571   } else {
1572     for (unsigned I = 0, E = Args.size(); I != E; ++I)
1573       EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1574                    I + 1);
1575   }
1576 }
1577 
1578 static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1579   while (insn->use_empty()) {
1580     llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1581     if (!bitcast) return;
1582 
1583     // This is "safe" because we would have used a ConstantExpr otherwise.
1584     insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1585     bitcast->eraseFromParent();
1586   }
1587 }
1588 
1589 /// Try to emit a fused autorelease of a return result.
1590 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1591                                                     llvm::Value *result) {
1592   // We must be immediately followed the cast.
1593   llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1594   if (BB->empty()) return 0;
1595   if (&BB->back() != result) return 0;
1596 
1597   llvm::Type *resultType = result->getType();
1598 
1599   // result is in a BasicBlock and is therefore an Instruction.
1600   llvm::Instruction *generator = cast<llvm::Instruction>(result);
1601 
1602   SmallVector<llvm::Instruction*,4> insnsToKill;
1603 
1604   // Look for:
1605   //  %generator = bitcast %type1* %generator2 to %type2*
1606   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1607     // We would have emitted this as a constant if the operand weren't
1608     // an Instruction.
1609     generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1610 
1611     // Require the generator to be immediately followed by the cast.
1612     if (generator->getNextNode() != bitcast)
1613       return 0;
1614 
1615     insnsToKill.push_back(bitcast);
1616   }
1617 
1618   // Look for:
1619   //   %generator = call i8* @objc_retain(i8* %originalResult)
1620   // or
1621   //   %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1622   llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1623   if (!call) return 0;
1624 
1625   bool doRetainAutorelease;
1626 
1627   if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1628     doRetainAutorelease = true;
1629   } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1630                                           .objc_retainAutoreleasedReturnValue) {
1631     doRetainAutorelease = false;
1632 
1633     // If we emitted an assembly marker for this call (and the
1634     // ARCEntrypoints field should have been set if so), go looking
1635     // for that call.  If we can't find it, we can't do this
1636     // optimization.  But it should always be the immediately previous
1637     // instruction, unless we needed bitcasts around the call.
1638     if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1639       llvm::Instruction *prev = call->getPrevNode();
1640       assert(prev);
1641       if (isa<llvm::BitCastInst>(prev)) {
1642         prev = prev->getPrevNode();
1643         assert(prev);
1644       }
1645       assert(isa<llvm::CallInst>(prev));
1646       assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1647                CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1648       insnsToKill.push_back(prev);
1649     }
1650   } else {
1651     return 0;
1652   }
1653 
1654   result = call->getArgOperand(0);
1655   insnsToKill.push_back(call);
1656 
1657   // Keep killing bitcasts, for sanity.  Note that we no longer care
1658   // about precise ordering as long as there's exactly one use.
1659   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1660     if (!bitcast->hasOneUse()) break;
1661     insnsToKill.push_back(bitcast);
1662     result = bitcast->getOperand(0);
1663   }
1664 
1665   // Delete all the unnecessary instructions, from latest to earliest.
1666   for (SmallVectorImpl<llvm::Instruction*>::iterator
1667          i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1668     (*i)->eraseFromParent();
1669 
1670   // Do the fused retain/autorelease if we were asked to.
1671   if (doRetainAutorelease)
1672     result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1673 
1674   // Cast back to the result type.
1675   return CGF.Builder.CreateBitCast(result, resultType);
1676 }
1677 
1678 /// If this is a +1 of the value of an immutable 'self', remove it.
1679 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1680                                           llvm::Value *result) {
1681   // This is only applicable to a method with an immutable 'self'.
1682   const ObjCMethodDecl *method =
1683     dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
1684   if (!method) return 0;
1685   const VarDecl *self = method->getSelfDecl();
1686   if (!self->getType().isConstQualified()) return 0;
1687 
1688   // Look for a retain call.
1689   llvm::CallInst *retainCall =
1690     dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1691   if (!retainCall ||
1692       retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
1693     return 0;
1694 
1695   // Look for an ordinary load of 'self'.
1696   llvm::Value *retainedValue = retainCall->getArgOperand(0);
1697   llvm::LoadInst *load =
1698     dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1699   if (!load || load->isAtomic() || load->isVolatile() ||
1700       load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
1701     return 0;
1702 
1703   // Okay!  Burn it all down.  This relies for correctness on the
1704   // assumption that the retain is emitted as part of the return and
1705   // that thereafter everything is used "linearly".
1706   llvm::Type *resultType = result->getType();
1707   eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1708   assert(retainCall->use_empty());
1709   retainCall->eraseFromParent();
1710   eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1711 
1712   return CGF.Builder.CreateBitCast(load, resultType);
1713 }
1714 
1715 /// Emit an ARC autorelease of the result of a function.
1716 ///
1717 /// \return the value to actually return from the function
1718 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1719                                             llvm::Value *result) {
1720   // If we're returning 'self', kill the initial retain.  This is a
1721   // heuristic attempt to "encourage correctness" in the really unfortunate
1722   // case where we have a return of self during a dealloc and we desperately
1723   // need to avoid the possible autorelease.
1724   if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1725     return self;
1726 
1727   // At -O0, try to emit a fused retain/autorelease.
1728   if (CGF.shouldUseFusedARCCalls())
1729     if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1730       return fused;
1731 
1732   return CGF.EmitARCAutoreleaseReturnValue(result);
1733 }
1734 
1735 /// Heuristically search for a dominating store to the return-value slot.
1736 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1737   // If there are multiple uses of the return-value slot, just check
1738   // for something immediately preceding the IP.  Sometimes this can
1739   // happen with how we generate implicit-returns; it can also happen
1740   // with noreturn cleanups.
1741   if (!CGF.ReturnValue->hasOneUse()) {
1742     llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1743     if (IP->empty()) return 0;
1744     llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
1745     if (!store) return 0;
1746     if (store->getPointerOperand() != CGF.ReturnValue) return 0;
1747     assert(!store->isAtomic() && !store->isVolatile()); // see below
1748     return store;
1749   }
1750 
1751   llvm::StoreInst *store =
1752     dyn_cast<llvm::StoreInst>(CGF.ReturnValue->use_back());
1753   if (!store) return 0;
1754 
1755   // These aren't actually possible for non-coerced returns, and we
1756   // only care about non-coerced returns on this code path.
1757   assert(!store->isAtomic() && !store->isVolatile());
1758 
1759   // Now do a first-and-dirty dominance check: just walk up the
1760   // single-predecessors chain from the current insertion point.
1761   llvm::BasicBlock *StoreBB = store->getParent();
1762   llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1763   while (IP != StoreBB) {
1764     if (!(IP = IP->getSinglePredecessor()))
1765       return 0;
1766   }
1767 
1768   // Okay, the store's basic block dominates the insertion point; we
1769   // can do our thing.
1770   return store;
1771 }
1772 
1773 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
1774                                          bool EmitRetDbgLoc,
1775                                          SourceLocation EndLoc) {
1776   // Functions with no result always return void.
1777   if (ReturnValue == 0) {
1778     Builder.CreateRetVoid();
1779     return;
1780   }
1781 
1782   llvm::DebugLoc RetDbgLoc;
1783   llvm::Value *RV = 0;
1784   QualType RetTy = FI.getReturnType();
1785   const ABIArgInfo &RetAI = FI.getReturnInfo();
1786 
1787   switch (RetAI.getKind()) {
1788   case ABIArgInfo::InAlloca:
1789     // Aggregrates get evaluated directly into the destination.  Sometimes we
1790     // need to return the sret value in a register, though.
1791     assert(hasAggregateEvaluationKind(RetTy));
1792     if (RetAI.getInAllocaSRet()) {
1793       llvm::Function::arg_iterator EI = CurFn->arg_end();
1794       --EI;
1795       llvm::Value *ArgStruct = EI;
1796       llvm::Value *SRet =
1797           Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
1798       RV = Builder.CreateLoad(SRet, "sret");
1799     }
1800     break;
1801 
1802   case ABIArgInfo::Indirect: {
1803     switch (getEvaluationKind(RetTy)) {
1804     case TEK_Complex: {
1805       ComplexPairTy RT =
1806         EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
1807                           EndLoc);
1808       EmitStoreOfComplex(RT,
1809                        MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1810                          /*isInit*/ true);
1811       break;
1812     }
1813     case TEK_Aggregate:
1814       // Do nothing; aggregrates get evaluated directly into the destination.
1815       break;
1816     case TEK_Scalar:
1817       EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
1818                         MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1819                         /*isInit*/ true);
1820       break;
1821     }
1822     break;
1823   }
1824 
1825   case ABIArgInfo::Extend:
1826   case ABIArgInfo::Direct:
1827     if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1828         RetAI.getDirectOffset() == 0) {
1829       // The internal return value temp always will have pointer-to-return-type
1830       // type, just do a load.
1831 
1832       // If there is a dominating store to ReturnValue, we can elide
1833       // the load, zap the store, and usually zap the alloca.
1834       if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
1835         // Reuse the debug location from the store unless there is
1836         // cleanup code to be emitted between the store and return
1837         // instruction.
1838         if (EmitRetDbgLoc && !AutoreleaseResult)
1839           RetDbgLoc = SI->getDebugLoc();
1840         // Get the stored value and nuke the now-dead store.
1841         RV = SI->getValueOperand();
1842         SI->eraseFromParent();
1843 
1844         // If that was the only use of the return value, nuke it as well now.
1845         if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1846           cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1847           ReturnValue = 0;
1848         }
1849 
1850       // Otherwise, we have to do a simple load.
1851       } else {
1852         RV = Builder.CreateLoad(ReturnValue);
1853       }
1854     } else {
1855       llvm::Value *V = ReturnValue;
1856       // If the value is offset in memory, apply the offset now.
1857       if (unsigned Offs = RetAI.getDirectOffset()) {
1858         V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1859         V = Builder.CreateConstGEP1_32(V, Offs);
1860         V = Builder.CreateBitCast(V,
1861                          llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1862       }
1863 
1864       RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
1865     }
1866 
1867     // In ARC, end functions that return a retainable type with a call
1868     // to objc_autoreleaseReturnValue.
1869     if (AutoreleaseResult) {
1870       assert(getLangOpts().ObjCAutoRefCount &&
1871              !FI.isReturnsRetained() &&
1872              RetTy->isObjCRetainableType());
1873       RV = emitAutoreleaseOfResult(*this, RV);
1874     }
1875 
1876     break;
1877 
1878   case ABIArgInfo::Ignore:
1879     break;
1880 
1881   case ABIArgInfo::Expand:
1882     llvm_unreachable("Invalid ABI kind for return argument");
1883   }
1884 
1885   llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
1886   if (!RetDbgLoc.isUnknown())
1887     Ret->setDebugLoc(RetDbgLoc);
1888 }
1889 
1890 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
1891   const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
1892   return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
1893 }
1894 
1895 static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
1896   // FIXME: Generate IR in one pass, rather than going back and fixing up these
1897   // placeholders.
1898   llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
1899   llvm::Value *Placeholder =
1900       llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
1901   Placeholder = CGF.Builder.CreateLoad(Placeholder);
1902   return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
1903                                Ty.getQualifiers(),
1904                                AggValueSlot::IsNotDestructed,
1905                                AggValueSlot::DoesNotNeedGCBarriers,
1906                                AggValueSlot::IsNotAliased);
1907 }
1908 
1909 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
1910                                           const VarDecl *param,
1911                                           SourceLocation loc) {
1912   // StartFunction converted the ABI-lowered parameter(s) into a
1913   // local alloca.  We need to turn that into an r-value suitable
1914   // for EmitCall.
1915   llvm::Value *local = GetAddrOfLocalVar(param);
1916 
1917   QualType type = param->getType();
1918 
1919   // For the most part, we just need to load the alloca, except:
1920   // 1) aggregate r-values are actually pointers to temporaries, and
1921   // 2) references to non-scalars are pointers directly to the aggregate.
1922   // I don't know why references to scalars are different here.
1923   if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
1924     if (!hasScalarEvaluationKind(ref->getPointeeType()))
1925       return args.add(RValue::getAggregate(local), type);
1926 
1927     // Locals which are references to scalars are represented
1928     // with allocas holding the pointer.
1929     return args.add(RValue::get(Builder.CreateLoad(local)), type);
1930   }
1931 
1932   if (isInAllocaArgument(CGM.getCXXABI(), type)) {
1933     AggValueSlot Slot = createPlaceholderSlot(*this, type);
1934     Slot.setExternallyDestructed();
1935 
1936     // FIXME: Either emit a copy constructor call, or figure out how to do
1937     // guaranteed tail calls with perfect forwarding in LLVM.
1938     CGM.ErrorUnsupported(param, "non-trivial argument copy for thunk");
1939     EmitNullInitialization(Slot.getAddr(), type);
1940 
1941     RValue RV = Slot.asRValue();
1942     args.add(RV, type);
1943     return;
1944   }
1945 
1946   args.add(convertTempToRValue(local, type, loc), type);
1947 }
1948 
1949 static bool isProvablyNull(llvm::Value *addr) {
1950   return isa<llvm::ConstantPointerNull>(addr);
1951 }
1952 
1953 static bool isProvablyNonNull(llvm::Value *addr) {
1954   return isa<llvm::AllocaInst>(addr);
1955 }
1956 
1957 /// Emit the actual writing-back of a writeback.
1958 static void emitWriteback(CodeGenFunction &CGF,
1959                           const CallArgList::Writeback &writeback) {
1960   const LValue &srcLV = writeback.Source;
1961   llvm::Value *srcAddr = srcLV.getAddress();
1962   assert(!isProvablyNull(srcAddr) &&
1963          "shouldn't have writeback for provably null argument");
1964 
1965   llvm::BasicBlock *contBB = 0;
1966 
1967   // If the argument wasn't provably non-null, we need to null check
1968   // before doing the store.
1969   bool provablyNonNull = isProvablyNonNull(srcAddr);
1970   if (!provablyNonNull) {
1971     llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1972     contBB = CGF.createBasicBlock("icr.done");
1973 
1974     llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1975     CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1976     CGF.EmitBlock(writebackBB);
1977   }
1978 
1979   // Load the value to writeback.
1980   llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1981 
1982   // Cast it back, in case we're writing an id to a Foo* or something.
1983   value = CGF.Builder.CreateBitCast(value,
1984                cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1985                             "icr.writeback-cast");
1986 
1987   // Perform the writeback.
1988 
1989   // If we have a "to use" value, it's something we need to emit a use
1990   // of.  This has to be carefully threaded in: if it's done after the
1991   // release it's potentially undefined behavior (and the optimizer
1992   // will ignore it), and if it happens before the retain then the
1993   // optimizer could move the release there.
1994   if (writeback.ToUse) {
1995     assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
1996 
1997     // Retain the new value.  No need to block-copy here:  the block's
1998     // being passed up the stack.
1999     value = CGF.EmitARCRetainNonBlock(value);
2000 
2001     // Emit the intrinsic use here.
2002     CGF.EmitARCIntrinsicUse(writeback.ToUse);
2003 
2004     // Load the old value (primitively).
2005     llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
2006 
2007     // Put the new value in place (primitively).
2008     CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2009 
2010     // Release the old value.
2011     CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2012 
2013   // Otherwise, we can just do a normal lvalue store.
2014   } else {
2015     CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2016   }
2017 
2018   // Jump to the continuation block.
2019   if (!provablyNonNull)
2020     CGF.EmitBlock(contBB);
2021 }
2022 
2023 static void emitWritebacks(CodeGenFunction &CGF,
2024                            const CallArgList &args) {
2025   for (CallArgList::writeback_iterator
2026          i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
2027     emitWriteback(CGF, *i);
2028 }
2029 
2030 static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2031                                             const CallArgList &CallArgs) {
2032   assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
2033   ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2034     CallArgs.getCleanupsToDeactivate();
2035   // Iterate in reverse to increase the likelihood of popping the cleanup.
2036   for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2037          I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2038     CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2039     I->IsActiveIP->eraseFromParent();
2040   }
2041 }
2042 
2043 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2044   if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2045     if (uop->getOpcode() == UO_AddrOf)
2046       return uop->getSubExpr();
2047   return 0;
2048 }
2049 
2050 /// Emit an argument that's being passed call-by-writeback.  That is,
2051 /// we are passing the address of
2052 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2053                              const ObjCIndirectCopyRestoreExpr *CRE) {
2054   LValue srcLV;
2055 
2056   // Make an optimistic effort to emit the address as an l-value.
2057   // This can fail if the the argument expression is more complicated.
2058   if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2059     srcLV = CGF.EmitLValue(lvExpr);
2060 
2061   // Otherwise, just emit it as a scalar.
2062   } else {
2063     llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2064 
2065     QualType srcAddrType =
2066       CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2067     srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2068   }
2069   llvm::Value *srcAddr = srcLV.getAddress();
2070 
2071   // The dest and src types don't necessarily match in LLVM terms
2072   // because of the crazy ObjC compatibility rules.
2073 
2074   llvm::PointerType *destType =
2075     cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2076 
2077   // If the address is a constant null, just pass the appropriate null.
2078   if (isProvablyNull(srcAddr)) {
2079     args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2080              CRE->getType());
2081     return;
2082   }
2083 
2084   // Create the temporary.
2085   llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2086                                            "icr.temp");
2087   // Loading an l-value can introduce a cleanup if the l-value is __weak,
2088   // and that cleanup will be conditional if we can't prove that the l-value
2089   // isn't null, so we need to register a dominating point so that the cleanups
2090   // system will make valid IR.
2091   CodeGenFunction::ConditionalEvaluation condEval(CGF);
2092 
2093   // Zero-initialize it if we're not doing a copy-initialization.
2094   bool shouldCopy = CRE->shouldCopy();
2095   if (!shouldCopy) {
2096     llvm::Value *null =
2097       llvm::ConstantPointerNull::get(
2098         cast<llvm::PointerType>(destType->getElementType()));
2099     CGF.Builder.CreateStore(null, temp);
2100   }
2101 
2102   llvm::BasicBlock *contBB = 0;
2103   llvm::BasicBlock *originBB = 0;
2104 
2105   // If the address is *not* known to be non-null, we need to switch.
2106   llvm::Value *finalArgument;
2107 
2108   bool provablyNonNull = isProvablyNonNull(srcAddr);
2109   if (provablyNonNull) {
2110     finalArgument = temp;
2111   } else {
2112     llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2113 
2114     finalArgument = CGF.Builder.CreateSelect(isNull,
2115                                    llvm::ConstantPointerNull::get(destType),
2116                                              temp, "icr.argument");
2117 
2118     // If we need to copy, then the load has to be conditional, which
2119     // means we need control flow.
2120     if (shouldCopy) {
2121       originBB = CGF.Builder.GetInsertBlock();
2122       contBB = CGF.createBasicBlock("icr.cont");
2123       llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2124       CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2125       CGF.EmitBlock(copyBB);
2126       condEval.begin(CGF);
2127     }
2128   }
2129 
2130   llvm::Value *valueToUse = 0;
2131 
2132   // Perform a copy if necessary.
2133   if (shouldCopy) {
2134     RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
2135     assert(srcRV.isScalar());
2136 
2137     llvm::Value *src = srcRV.getScalarVal();
2138     src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2139                                     "icr.cast");
2140 
2141     // Use an ordinary store, not a store-to-lvalue.
2142     CGF.Builder.CreateStore(src, temp);
2143 
2144     // If optimization is enabled, and the value was held in a
2145     // __strong variable, we need to tell the optimizer that this
2146     // value has to stay alive until we're doing the store back.
2147     // This is because the temporary is effectively unretained,
2148     // and so otherwise we can violate the high-level semantics.
2149     if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2150         srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2151       valueToUse = src;
2152     }
2153   }
2154 
2155   // Finish the control flow if we needed it.
2156   if (shouldCopy && !provablyNonNull) {
2157     llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
2158     CGF.EmitBlock(contBB);
2159 
2160     // Make a phi for the value to intrinsically use.
2161     if (valueToUse) {
2162       llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2163                                                       "icr.to-use");
2164       phiToUse->addIncoming(valueToUse, copyBB);
2165       phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2166                             originBB);
2167       valueToUse = phiToUse;
2168     }
2169 
2170     condEval.end(CGF);
2171   }
2172 
2173   args.addWriteback(srcLV, temp, valueToUse);
2174   args.add(RValue::get(finalArgument), CRE->getType());
2175 }
2176 
2177 void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2178   assert(!StackBase && !StackCleanup.isValid());
2179 
2180   // Save the stack.
2181   llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2182   StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2183 
2184   // Control gets really tied up in landing pads, so we have to spill the
2185   // stacksave to an alloca to avoid violating SSA form.
2186   // TODO: This is dead if we never emit the cleanup.  We should create the
2187   // alloca and store lazily on the first cleanup emission.
2188   StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2189   CGF.Builder.CreateStore(StackBase, StackBaseMem);
2190   CGF.pushStackRestore(EHCleanup, StackBaseMem);
2191   StackCleanup = CGF.EHStack.getInnermostEHScope();
2192   assert(StackCleanup.isValid());
2193 }
2194 
2195 void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2196   if (StackBase) {
2197     CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2198     llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2199     // We could load StackBase from StackBaseMem, but in the non-exceptional
2200     // case we can skip it.
2201     CGF.Builder.CreateCall(F, StackBase);
2202   }
2203 }
2204 
2205 void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2206                                    ArrayRef<QualType> ArgTypes,
2207                                    CallExpr::const_arg_iterator ArgBeg,
2208                                    CallExpr::const_arg_iterator ArgEnd,
2209                                    bool ForceColumnInfo) {
2210   CGDebugInfo *DI = getDebugInfo();
2211   SourceLocation CallLoc;
2212   if (DI) CallLoc = DI->getLocation();
2213 
2214   // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2215   // because arguments are destroyed left to right in the callee.
2216   if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2217     // Insert a stack save if we're going to need any inalloca args.
2218     bool HasInAllocaArgs = false;
2219     for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2220          I != E && !HasInAllocaArgs; ++I)
2221       HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2222     if (HasInAllocaArgs) {
2223       assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2224       Args.allocateArgumentMemory(*this);
2225     }
2226 
2227     // Evaluate each argument.
2228     size_t CallArgsStart = Args.size();
2229     for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2230       CallExpr::const_arg_iterator Arg = ArgBeg + I;
2231       EmitCallArg(Args, *Arg, ArgTypes[I]);
2232       // Restore the debug location.
2233       if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2234     }
2235 
2236     // Un-reverse the arguments we just evaluated so they match up with the LLVM
2237     // IR function.
2238     std::reverse(Args.begin() + CallArgsStart, Args.end());
2239     return;
2240   }
2241 
2242   for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2243     CallExpr::const_arg_iterator Arg = ArgBeg + I;
2244     assert(Arg != ArgEnd);
2245     EmitCallArg(Args, *Arg, ArgTypes[I]);
2246     // Restore the debug location.
2247     if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2248   }
2249 }
2250 
2251 namespace {
2252 
2253 struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2254   DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2255       : Addr(Addr), Ty(Ty) {}
2256 
2257   llvm::Value *Addr;
2258   QualType Ty;
2259 
2260   void Emit(CodeGenFunction &CGF, Flags flags) {
2261     const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2262     assert(!Dtor->isTrivial());
2263     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2264                               /*Delegating=*/false, Addr);
2265   }
2266 };
2267 
2268 }
2269 
2270 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2271                                   QualType type) {
2272   if (const ObjCIndirectCopyRestoreExpr *CRE
2273         = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
2274     assert(getLangOpts().ObjCAutoRefCount);
2275     assert(getContext().hasSameType(E->getType(), type));
2276     return emitWritebackArg(*this, args, CRE);
2277   }
2278 
2279   assert(type->isReferenceType() == E->isGLValue() &&
2280          "reference binding to unmaterialized r-value!");
2281 
2282   if (E->isGLValue()) {
2283     assert(E->getObjectKind() == OK_Ordinary);
2284     return args.add(EmitReferenceBindingToExpr(E), type);
2285   }
2286 
2287   bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2288 
2289   // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2290   // However, we still have to push an EH-only cleanup in case we unwind before
2291   // we make it to the call.
2292   if (HasAggregateEvalKind && args.isUsingInAlloca()) {
2293     assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2294     AggValueSlot Slot = createPlaceholderSlot(*this, type);
2295     Slot.setExternallyDestructed();
2296     EmitAggExpr(E, Slot);
2297     RValue RV = Slot.asRValue();
2298     args.add(RV, type);
2299 
2300     const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2301     if (RD->hasNonTrivialDestructor()) {
2302       // Create a no-op GEP between the placeholder and the cleanup so we can
2303       // RAUW it successfully.  It also serves as a marker of the first
2304       // instruction where the cleanup is active.
2305       pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
2306       // This unreachable is a temporary marker which will be removed later.
2307       llvm::Instruction *IsActive = Builder.CreateUnreachable();
2308       args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
2309     }
2310     return;
2311   }
2312 
2313   if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
2314       cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2315     LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2316     assert(L.isSimple());
2317     if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2318       args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2319     } else {
2320       // We can't represent a misaligned lvalue in the CallArgList, so copy
2321       // to an aligned temporary now.
2322       llvm::Value *tmp = CreateMemTemp(type);
2323       EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2324                         L.getAlignment());
2325       args.add(RValue::getAggregate(tmp), type);
2326     }
2327     return;
2328   }
2329 
2330   args.add(EmitAnyExprToTemp(E), type);
2331 }
2332 
2333 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2334 // optimizer it can aggressively ignore unwind edges.
2335 void
2336 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2337   if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2338       !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2339     Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2340                       CGM.getNoObjCARCExceptionsMetadata());
2341 }
2342 
2343 /// Emits a call to the given no-arguments nounwind runtime function.
2344 llvm::CallInst *
2345 CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2346                                          const llvm::Twine &name) {
2347   return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2348 }
2349 
2350 /// Emits a call to the given nounwind runtime function.
2351 llvm::CallInst *
2352 CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2353                                          ArrayRef<llvm::Value*> args,
2354                                          const llvm::Twine &name) {
2355   llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2356   call->setDoesNotThrow();
2357   return call;
2358 }
2359 
2360 /// Emits a simple call (never an invoke) to the given no-arguments
2361 /// runtime function.
2362 llvm::CallInst *
2363 CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2364                                  const llvm::Twine &name) {
2365   return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2366 }
2367 
2368 /// Emits a simple call (never an invoke) to the given runtime
2369 /// function.
2370 llvm::CallInst *
2371 CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2372                                  ArrayRef<llvm::Value*> args,
2373                                  const llvm::Twine &name) {
2374   llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2375   call->setCallingConv(getRuntimeCC());
2376   return call;
2377 }
2378 
2379 /// Emits a call or invoke to the given noreturn runtime function.
2380 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2381                                                ArrayRef<llvm::Value*> args) {
2382   if (getInvokeDest()) {
2383     llvm::InvokeInst *invoke =
2384       Builder.CreateInvoke(callee,
2385                            getUnreachableBlock(),
2386                            getInvokeDest(),
2387                            args);
2388     invoke->setDoesNotReturn();
2389     invoke->setCallingConv(getRuntimeCC());
2390   } else {
2391     llvm::CallInst *call = Builder.CreateCall(callee, args);
2392     call->setDoesNotReturn();
2393     call->setCallingConv(getRuntimeCC());
2394     Builder.CreateUnreachable();
2395   }
2396   PGO.setCurrentRegionUnreachable();
2397 }
2398 
2399 /// Emits a call or invoke instruction to the given nullary runtime
2400 /// function.
2401 llvm::CallSite
2402 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2403                                          const Twine &name) {
2404   return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2405 }
2406 
2407 /// Emits a call or invoke instruction to the given runtime function.
2408 llvm::CallSite
2409 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2410                                          ArrayRef<llvm::Value*> args,
2411                                          const Twine &name) {
2412   llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2413   callSite.setCallingConv(getRuntimeCC());
2414   return callSite;
2415 }
2416 
2417 llvm::CallSite
2418 CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2419                                   const Twine &Name) {
2420   return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2421 }
2422 
2423 /// Emits a call or invoke instruction to the given function, depending
2424 /// on the current state of the EH stack.
2425 llvm::CallSite
2426 CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2427                                   ArrayRef<llvm::Value *> Args,
2428                                   const Twine &Name) {
2429   llvm::BasicBlock *InvokeDest = getInvokeDest();
2430 
2431   llvm::Instruction *Inst;
2432   if (!InvokeDest)
2433     Inst = Builder.CreateCall(Callee, Args, Name);
2434   else {
2435     llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2436     Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2437     EmitBlock(ContBB);
2438   }
2439 
2440   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2441   // optimizer it can aggressively ignore unwind edges.
2442   if (CGM.getLangOpts().ObjCAutoRefCount)
2443     AddObjCARCExceptionMetadata(Inst);
2444 
2445   return Inst;
2446 }
2447 
2448 static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2449                             llvm::FunctionType *FTy) {
2450   if (ArgNo < FTy->getNumParams())
2451     assert(Elt->getType() == FTy->getParamType(ArgNo));
2452   else
2453     assert(FTy->isVarArg());
2454   ++ArgNo;
2455 }
2456 
2457 void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
2458                                        SmallVectorImpl<llvm::Value *> &Args,
2459                                        llvm::FunctionType *IRFuncTy) {
2460   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2461     unsigned NumElts = AT->getSize().getZExtValue();
2462     QualType EltTy = AT->getElementType();
2463     llvm::Value *Addr = RV.getAggregateAddr();
2464     for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2465       llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
2466       RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
2467       ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
2468     }
2469   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
2470     RecordDecl *RD = RT->getDecl();
2471     assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
2472     LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
2473 
2474     if (RD->isUnion()) {
2475       const FieldDecl *LargestFD = 0;
2476       CharUnits UnionSize = CharUnits::Zero();
2477 
2478       for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2479            i != e; ++i) {
2480         const FieldDecl *FD = *i;
2481         assert(!FD->isBitField() &&
2482                "Cannot expand structure with bit-field members.");
2483         CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2484         if (UnionSize < FieldSize) {
2485           UnionSize = FieldSize;
2486           LargestFD = FD;
2487         }
2488       }
2489       if (LargestFD) {
2490         RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
2491         ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2492       }
2493     } else {
2494       for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2495            i != e; ++i) {
2496         FieldDecl *FD = *i;
2497 
2498         RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
2499         ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2500       }
2501     }
2502   } else if (Ty->isAnyComplexType()) {
2503     ComplexPairTy CV = RV.getComplexVal();
2504     Args.push_back(CV.first);
2505     Args.push_back(CV.second);
2506   } else {
2507     assert(RV.isScalar() &&
2508            "Unexpected non-scalar rvalue during struct expansion.");
2509 
2510     // Insert a bitcast as needed.
2511     llvm::Value *V = RV.getScalarVal();
2512     if (Args.size() < IRFuncTy->getNumParams() &&
2513         V->getType() != IRFuncTy->getParamType(Args.size()))
2514       V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2515 
2516     Args.push_back(V);
2517   }
2518 }
2519 
2520 /// \brief Store a non-aggregate value to an address to initialize it.  For
2521 /// initialization, a non-atomic store will be used.
2522 static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2523                                         LValue Dst) {
2524   if (Src.isScalar())
2525     CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2526   else
2527     CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2528 }
2529 
2530 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2531                                                   llvm::Value *New) {
2532   DeferredReplacements.push_back(std::make_pair(Old, New));
2533 }
2534 
2535 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
2536                                  llvm::Value *Callee,
2537                                  ReturnValueSlot ReturnValue,
2538                                  const CallArgList &CallArgs,
2539                                  const Decl *TargetDecl,
2540                                  llvm::Instruction **callOrInvoke) {
2541   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
2542   SmallVector<llvm::Value*, 16> Args;
2543 
2544   // Handle struct-return functions by passing a pointer to the
2545   // location that we would like to return into.
2546   QualType RetTy = CallInfo.getReturnType();
2547   const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
2548 
2549   // IRArgNo - Keep track of the argument number in the callee we're looking at.
2550   unsigned IRArgNo = 0;
2551   llvm::FunctionType *IRFuncTy =
2552     cast<llvm::FunctionType>(
2553                   cast<llvm::PointerType>(Callee->getType())->getElementType());
2554 
2555   // If we're using inalloca, insert the allocation after the stack save.
2556   // FIXME: Do this earlier rather than hacking it in here!
2557   llvm::Value *ArgMemory = 0;
2558   if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
2559     llvm::AllocaInst *AI = new llvm::AllocaInst(
2560         ArgStruct, "argmem", CallArgs.getStackBase()->getNextNode());
2561     AI->setUsedWithInAlloca(true);
2562     assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2563     ArgMemory = AI;
2564   }
2565 
2566   // If the call returns a temporary with struct return, create a temporary
2567   // alloca to hold the result, unless one is given to us.
2568   llvm::Value *SRetPtr = 0;
2569   if (CGM.ReturnTypeUsesSRet(CallInfo) || RetAI.isInAlloca()) {
2570     SRetPtr = ReturnValue.getValue();
2571     if (!SRetPtr)
2572       SRetPtr = CreateMemTemp(RetTy);
2573     if (CGM.ReturnTypeUsesSRet(CallInfo)) {
2574       Args.push_back(SRetPtr);
2575       checkArgMatches(SRetPtr, IRArgNo, IRFuncTy);
2576     } else {
2577       llvm::Value *Addr =
2578           Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2579       Builder.CreateStore(SRetPtr, Addr);
2580     }
2581   }
2582 
2583   assert(CallInfo.arg_size() == CallArgs.size() &&
2584          "Mismatch between function signature & arguments.");
2585   CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
2586   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
2587        I != E; ++I, ++info_it) {
2588     const ABIArgInfo &ArgInfo = info_it->info;
2589     RValue RV = I->RV;
2590 
2591     CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
2592 
2593     // Insert a padding argument to ensure proper alignment.
2594     if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2595       Args.push_back(llvm::UndefValue::get(PaddingType));
2596       ++IRArgNo;
2597     }
2598 
2599     switch (ArgInfo.getKind()) {
2600     case ABIArgInfo::InAlloca: {
2601       assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2602       if (RV.isAggregate()) {
2603         // Replace the placeholder with the appropriate argument slot GEP.
2604         llvm::Instruction *Placeholder =
2605             cast<llvm::Instruction>(RV.getAggregateAddr());
2606         CGBuilderTy::InsertPoint IP = Builder.saveIP();
2607         Builder.SetInsertPoint(Placeholder);
2608         llvm::Value *Addr = Builder.CreateStructGEP(
2609             ArgMemory, ArgInfo.getInAllocaFieldIndex());
2610         Builder.restoreIP(IP);
2611         deferPlaceholderReplacement(Placeholder, Addr);
2612       } else {
2613         // Store the RValue into the argument struct.
2614         llvm::Value *Addr =
2615             Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
2616         LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
2617         EmitInitStoreOfNonAggregate(*this, RV, argLV);
2618       }
2619       break; // Don't increment IRArgNo!
2620     }
2621 
2622     case ABIArgInfo::Indirect: {
2623       if (RV.isScalar() || RV.isComplex()) {
2624         // Make a temporary alloca to pass the argument.
2625         llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2626         if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2627           AI->setAlignment(ArgInfo.getIndirectAlign());
2628         Args.push_back(AI);
2629 
2630         LValue argLV = MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
2631         EmitInitStoreOfNonAggregate(*this, RV, argLV);
2632 
2633         // Validate argument match.
2634         checkArgMatches(AI, IRArgNo, IRFuncTy);
2635       } else {
2636         // We want to avoid creating an unnecessary temporary+copy here;
2637         // however, we need one in three cases:
2638         // 1. If the argument is not byval, and we are required to copy the
2639         //    source.  (This case doesn't occur on any common architecture.)
2640         // 2. If the argument is byval, RV is not sufficiently aligned, and
2641         //    we cannot force it to be sufficiently aligned.
2642         // 3. If the argument is byval, but RV is located in an address space
2643         //    different than that of the argument (0).
2644         llvm::Value *Addr = RV.getAggregateAddr();
2645         unsigned Align = ArgInfo.getIndirectAlign();
2646         const llvm::DataLayout *TD = &CGM.getDataLayout();
2647         const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2648         const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2649           IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
2650         if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
2651             (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
2652              llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2653              (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
2654           // Create an aligned temporary, and copy to it.
2655           llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2656           if (Align > AI->getAlignment())
2657             AI->setAlignment(Align);
2658           Args.push_back(AI);
2659           EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
2660 
2661           // Validate argument match.
2662           checkArgMatches(AI, IRArgNo, IRFuncTy);
2663         } else {
2664           // Skip the extra memcpy call.
2665           Args.push_back(Addr);
2666 
2667           // Validate argument match.
2668           checkArgMatches(Addr, IRArgNo, IRFuncTy);
2669         }
2670       }
2671       break;
2672     }
2673 
2674     case ABIArgInfo::Ignore:
2675       break;
2676 
2677     case ABIArgInfo::Extend:
2678     case ABIArgInfo::Direct: {
2679       if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
2680           ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2681           ArgInfo.getDirectOffset() == 0) {
2682         llvm::Value *V;
2683         if (RV.isScalar())
2684           V = RV.getScalarVal();
2685         else
2686           V = Builder.CreateLoad(RV.getAggregateAddr());
2687 
2688         // If the argument doesn't match, perform a bitcast to coerce it.  This
2689         // can happen due to trivial type mismatches.
2690         if (IRArgNo < IRFuncTy->getNumParams() &&
2691             V->getType() != IRFuncTy->getParamType(IRArgNo))
2692           V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
2693         Args.push_back(V);
2694 
2695         checkArgMatches(V, IRArgNo, IRFuncTy);
2696         break;
2697       }
2698 
2699       // FIXME: Avoid the conversion through memory if possible.
2700       llvm::Value *SrcPtr;
2701       if (RV.isScalar() || RV.isComplex()) {
2702         SrcPtr = CreateMemTemp(I->Ty, "coerce");
2703         LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
2704         EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
2705       } else
2706         SrcPtr = RV.getAggregateAddr();
2707 
2708       // If the value is offset in memory, apply the offset now.
2709       if (unsigned Offs = ArgInfo.getDirectOffset()) {
2710         SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2711         SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
2712         SrcPtr = Builder.CreateBitCast(SrcPtr,
2713                        llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2714 
2715       }
2716 
2717       // If the coerce-to type is a first class aggregate, we flatten it and
2718       // pass the elements. Either way is semantically identical, but fast-isel
2719       // and the optimizer generally likes scalar values better than FCAs.
2720       if (llvm::StructType *STy =
2721             dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
2722         llvm::Type *SrcTy =
2723           cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2724         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2725         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2726 
2727         // If the source type is smaller than the destination type of the
2728         // coerce-to logic, copy the source value into a temp alloca the size
2729         // of the destination type to allow loading all of it. The bits past
2730         // the source value are left undef.
2731         if (SrcSize < DstSize) {
2732           llvm::AllocaInst *TempAlloca
2733             = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2734           Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2735           SrcPtr = TempAlloca;
2736         } else {
2737           SrcPtr = Builder.CreateBitCast(SrcPtr,
2738                                          llvm::PointerType::getUnqual(STy));
2739         }
2740 
2741         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2742           llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
2743           llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2744           // We don't know what we're loading from.
2745           LI->setAlignment(1);
2746           Args.push_back(LI);
2747 
2748           // Validate argument match.
2749           checkArgMatches(LI, IRArgNo, IRFuncTy);
2750         }
2751       } else {
2752         // In the simple case, just pass the coerced loaded value.
2753         Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2754                                          *this));
2755 
2756         // Validate argument match.
2757         checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
2758       }
2759 
2760       break;
2761     }
2762 
2763     case ABIArgInfo::Expand:
2764       ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
2765       IRArgNo = Args.size();
2766       break;
2767     }
2768   }
2769 
2770   if (ArgMemory) {
2771     llvm::Value *Arg = ArgMemory;
2772     llvm::Type *LastParamTy =
2773         IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
2774     if (Arg->getType() != LastParamTy) {
2775 #ifndef NDEBUG
2776       // Assert that these structs have equivalent element types.
2777       llvm::StructType *FullTy = CallInfo.getArgStruct();
2778       llvm::StructType *Prefix = cast<llvm::StructType>(
2779           cast<llvm::PointerType>(LastParamTy)->getElementType());
2780 
2781       // For variadic functions, the caller might supply a larger struct than
2782       // the callee expects, and that's OK.
2783       assert(Prefix->getNumElements() == FullTy->getNumElements() ||
2784              (CallInfo.isVariadic() &&
2785               Prefix->getNumElements() <= FullTy->getNumElements()));
2786 
2787       for (llvm::StructType::element_iterator PI = Prefix->element_begin(),
2788                                               PE = Prefix->element_end(),
2789                                               FI = FullTy->element_begin();
2790            PI != PE; ++PI, ++FI)
2791         assert(*PI == *FI);
2792 #endif
2793       Arg = Builder.CreateBitCast(Arg, LastParamTy);
2794     }
2795     Args.push_back(Arg);
2796   }
2797 
2798   if (!CallArgs.getCleanupsToDeactivate().empty())
2799     deactivateArgCleanupsBeforeCall(*this, CallArgs);
2800 
2801   // If the callee is a bitcast of a function to a varargs pointer to function
2802   // type, check to see if we can remove the bitcast.  This handles some cases
2803   // with unprototyped functions.
2804   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2805     if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
2806       llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2807       llvm::FunctionType *CurFT =
2808         cast<llvm::FunctionType>(CurPT->getElementType());
2809       llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
2810 
2811       if (CE->getOpcode() == llvm::Instruction::BitCast &&
2812           ActualFT->getReturnType() == CurFT->getReturnType() &&
2813           ActualFT->getNumParams() == CurFT->getNumParams() &&
2814           ActualFT->getNumParams() == Args.size() &&
2815           (CurFT->isVarArg() || !ActualFT->isVarArg())) {
2816         bool ArgsMatch = true;
2817         for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2818           if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2819             ArgsMatch = false;
2820             break;
2821           }
2822 
2823         // Strip the cast if we can get away with it.  This is a nice cleanup,
2824         // but also allows us to inline the function at -O0 if it is marked
2825         // always_inline.
2826         if (ArgsMatch)
2827           Callee = CalleeF;
2828       }
2829     }
2830 
2831   unsigned CallingConv;
2832   CodeGen::AttributeListType AttributeList;
2833   CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2834                              CallingConv, true);
2835   llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
2836                                                      AttributeList);
2837 
2838   llvm::BasicBlock *InvokeDest = 0;
2839   if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2840                           llvm::Attribute::NoUnwind))
2841     InvokeDest = getInvokeDest();
2842 
2843   llvm::CallSite CS;
2844   if (!InvokeDest) {
2845     CS = Builder.CreateCall(Callee, Args);
2846   } else {
2847     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
2848     CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
2849     EmitBlock(Cont);
2850   }
2851   if (callOrInvoke)
2852     *callOrInvoke = CS.getInstruction();
2853 
2854   CS.setAttributes(Attrs);
2855   CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
2856 
2857   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2858   // optimizer it can aggressively ignore unwind edges.
2859   if (CGM.getLangOpts().ObjCAutoRefCount)
2860     AddObjCARCExceptionMetadata(CS.getInstruction());
2861 
2862   // If the call doesn't return, finish the basic block and clear the
2863   // insertion point; this allows the rest of IRgen to discard
2864   // unreachable code.
2865   if (CS.doesNotReturn()) {
2866     Builder.CreateUnreachable();
2867     Builder.ClearInsertionPoint();
2868 
2869     // FIXME: For now, emit a dummy basic block because expr emitters in
2870     // generally are not ready to handle emitting expressions at unreachable
2871     // points.
2872     EnsureInsertPoint();
2873 
2874     // Return a reasonable RValue.
2875     return GetUndefRValue(RetTy);
2876   }
2877 
2878   llvm::Instruction *CI = CS.getInstruction();
2879   if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
2880     CI->setName("call");
2881 
2882   // Emit any writebacks immediately.  Arguably this should happen
2883   // after any return-value munging.
2884   if (CallArgs.hasWritebacks())
2885     emitWritebacks(*this, CallArgs);
2886 
2887   // The stack cleanup for inalloca arguments has to run out of the normal
2888   // lexical order, so deactivate it and run it manually here.
2889   CallArgs.freeArgumentMemory(*this);
2890 
2891   switch (RetAI.getKind()) {
2892   case ABIArgInfo::InAlloca:
2893   case ABIArgInfo::Indirect:
2894     return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
2895 
2896   case ABIArgInfo::Ignore:
2897     // If we are ignoring an argument that had a result, make sure to
2898     // construct the appropriate return value for our caller.
2899     return GetUndefRValue(RetTy);
2900 
2901   case ABIArgInfo::Extend:
2902   case ABIArgInfo::Direct: {
2903     llvm::Type *RetIRTy = ConvertType(RetTy);
2904     if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
2905       switch (getEvaluationKind(RetTy)) {
2906       case TEK_Complex: {
2907         llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2908         llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2909         return RValue::getComplex(std::make_pair(Real, Imag));
2910       }
2911       case TEK_Aggregate: {
2912         llvm::Value *DestPtr = ReturnValue.getValue();
2913         bool DestIsVolatile = ReturnValue.isVolatile();
2914 
2915         if (!DestPtr) {
2916           DestPtr = CreateMemTemp(RetTy, "agg.tmp");
2917           DestIsVolatile = false;
2918         }
2919         BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
2920         return RValue::getAggregate(DestPtr);
2921       }
2922       case TEK_Scalar: {
2923         // If the argument doesn't match, perform a bitcast to coerce it.  This
2924         // can happen due to trivial type mismatches.
2925         llvm::Value *V = CI;
2926         if (V->getType() != RetIRTy)
2927           V = Builder.CreateBitCast(V, RetIRTy);
2928         return RValue::get(V);
2929       }
2930       }
2931       llvm_unreachable("bad evaluation kind");
2932     }
2933 
2934     llvm::Value *DestPtr = ReturnValue.getValue();
2935     bool DestIsVolatile = ReturnValue.isVolatile();
2936 
2937     if (!DestPtr) {
2938       DestPtr = CreateMemTemp(RetTy, "coerce");
2939       DestIsVolatile = false;
2940     }
2941 
2942     // If the value is offset in memory, apply the offset now.
2943     llvm::Value *StorePtr = DestPtr;
2944     if (unsigned Offs = RetAI.getDirectOffset()) {
2945       StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
2946       StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
2947       StorePtr = Builder.CreateBitCast(StorePtr,
2948                          llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2949     }
2950     CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
2951 
2952     return convertTempToRValue(DestPtr, RetTy, SourceLocation());
2953   }
2954 
2955   case ABIArgInfo::Expand:
2956     llvm_unreachable("Invalid ABI kind for return argument");
2957   }
2958 
2959   llvm_unreachable("Unhandled ABIArgInfo::Kind");
2960 }
2961 
2962 /* VarArg handling */
2963 
2964 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2965   return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
2966 }
2967