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