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