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 "CGBlocks.h"
18 #include "CGCXXABI.h"
19 #include "CGCleanup.h"
20 #include "CodeGenFunction.h"
21 #include "CodeGenModule.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/Basic/TargetBuiltins.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/CodeGen/CGFunctionInfo.h"
29 #include "clang/CodeGen/SwiftCallingConv.h"
30 #include "clang/Frontend/CodeGenOptions.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/IR/Attributes.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/InlineAsm.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/Transforms/Utils/Local.h"
41 using namespace clang;
42 using namespace CodeGen;
43 
44 /***/
45 
46 unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
47   switch (CC) {
48   default: return llvm::CallingConv::C;
49   case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
50   case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
51   case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
52   case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
53   case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
54   case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
55   case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
56   case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
57   case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
58   // TODO: Add support for __pascal to LLVM.
59   case CC_X86Pascal: return llvm::CallingConv::C;
60   // TODO: Add support for __vectorcall to LLVM.
61   case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
62   case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
63   case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
64   case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
65   case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
66   case CC_Swift: return llvm::CallingConv::Swift;
67   }
68 }
69 
70 /// Derives the 'this' type for codegen purposes, i.e. ignoring method
71 /// qualification.
72 /// FIXME: address space qualification?
73 static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
74   QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
75   return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
76 }
77 
78 /// Returns the canonical formal type of the given C++ method.
79 static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
80   return MD->getType()->getCanonicalTypeUnqualified()
81            .getAs<FunctionProtoType>();
82 }
83 
84 /// Returns the "extra-canonicalized" return type, which discards
85 /// qualifiers on the return type.  Codegen doesn't care about them,
86 /// and it makes ABI code a little easier to be able to assume that
87 /// all parameter and return types are top-level unqualified.
88 static CanQualType GetReturnType(QualType RetTy) {
89   return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
90 }
91 
92 /// Arrange the argument and result information for a value of the given
93 /// unprototyped freestanding function type.
94 const CGFunctionInfo &
95 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
96   // When translating an unprototyped function type, always use a
97   // variadic type.
98   return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
99                                  /*instanceMethod=*/false,
100                                  /*chainCall=*/false, None,
101                                  FTNP->getExtInfo(), {}, RequiredArgs(0));
102 }
103 
104 static void addExtParameterInfosForCall(
105          llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
106                                         const FunctionProtoType *proto,
107                                         unsigned prefixArgs,
108                                         unsigned totalArgs) {
109   assert(proto->hasExtParameterInfos());
110   assert(paramInfos.size() <= prefixArgs);
111   assert(proto->getNumParams() + prefixArgs <= totalArgs);
112 
113   paramInfos.reserve(totalArgs);
114 
115   // Add default infos for any prefix args that don't already have infos.
116   paramInfos.resize(prefixArgs);
117 
118   // Add infos for the prototype.
119   for (const auto &ParamInfo : proto->getExtParameterInfos()) {
120     paramInfos.push_back(ParamInfo);
121     // pass_object_size params have no parameter info.
122     if (ParamInfo.hasPassObjectSize())
123       paramInfos.emplace_back();
124   }
125 
126   assert(paramInfos.size() <= totalArgs &&
127          "Did we forget to insert pass_object_size args?");
128   // Add default infos for the variadic and/or suffix arguments.
129   paramInfos.resize(totalArgs);
130 }
131 
132 /// Adds the formal paramaters in FPT to the given prefix. If any parameter in
133 /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
134 static void appendParameterTypes(const CodeGenTypes &CGT,
135                                  SmallVectorImpl<CanQualType> &prefix,
136               SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
137                                  CanQual<FunctionProtoType> FPT) {
138   // Fast path: don't touch param info if we don't need to.
139   if (!FPT->hasExtParameterInfos()) {
140     assert(paramInfos.empty() &&
141            "We have paramInfos, but the prototype doesn't?");
142     prefix.append(FPT->param_type_begin(), FPT->param_type_end());
143     return;
144   }
145 
146   unsigned PrefixSize = prefix.size();
147   // In the vast majority of cases, we'll have precisely FPT->getNumParams()
148   // parameters; the only thing that can change this is the presence of
149   // pass_object_size. So, we preallocate for the common case.
150   prefix.reserve(prefix.size() + FPT->getNumParams());
151 
152   auto ExtInfos = FPT->getExtParameterInfos();
153   assert(ExtInfos.size() == FPT->getNumParams());
154   for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
155     prefix.push_back(FPT->getParamType(I));
156     if (ExtInfos[I].hasPassObjectSize())
157       prefix.push_back(CGT.getContext().getSizeType());
158   }
159 
160   addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
161                               prefix.size());
162 }
163 
164 /// Arrange the LLVM function layout for a value of the given function
165 /// type, on top of any implicit parameters already stored.
166 static const CGFunctionInfo &
167 arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
168                         SmallVectorImpl<CanQualType> &prefix,
169                         CanQual<FunctionProtoType> FTP,
170                         const FunctionDecl *FD) {
171   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
172   RequiredArgs Required =
173       RequiredArgs::forPrototypePlus(FTP, prefix.size(), FD);
174   // FIXME: Kill copy.
175   appendParameterTypes(CGT, prefix, paramInfos, FTP);
176   CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
177 
178   return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
179                                      /*chainCall=*/false, prefix,
180                                      FTP->getExtInfo(), paramInfos,
181                                      Required);
182 }
183 
184 /// Arrange the argument and result information for a value of the
185 /// given freestanding function type.
186 const CGFunctionInfo &
187 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
188                                       const FunctionDecl *FD) {
189   SmallVector<CanQualType, 16> argTypes;
190   return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
191                                    FTP, FD);
192 }
193 
194 static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
195   // Set the appropriate calling convention for the Function.
196   if (D->hasAttr<StdCallAttr>())
197     return CC_X86StdCall;
198 
199   if (D->hasAttr<FastCallAttr>())
200     return CC_X86FastCall;
201 
202   if (D->hasAttr<RegCallAttr>())
203     return CC_X86RegCall;
204 
205   if (D->hasAttr<ThisCallAttr>())
206     return CC_X86ThisCall;
207 
208   if (D->hasAttr<VectorCallAttr>())
209     return CC_X86VectorCall;
210 
211   if (D->hasAttr<PascalAttr>())
212     return CC_X86Pascal;
213 
214   if (PcsAttr *PCS = D->getAttr<PcsAttr>())
215     return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
216 
217   if (D->hasAttr<IntelOclBiccAttr>())
218     return CC_IntelOclBicc;
219 
220   if (D->hasAttr<MSABIAttr>())
221     return IsWindows ? CC_C : CC_X86_64Win64;
222 
223   if (D->hasAttr<SysVABIAttr>())
224     return IsWindows ? CC_X86_64SysV : CC_C;
225 
226   if (D->hasAttr<PreserveMostAttr>())
227     return CC_PreserveMost;
228 
229   if (D->hasAttr<PreserveAllAttr>())
230     return CC_PreserveAll;
231 
232   return CC_C;
233 }
234 
235 /// Arrange the argument and result information for a call to an
236 /// unknown C++ non-static member function of the given abstract type.
237 /// (Zero value of RD means we don't have any meaningful "this" argument type,
238 ///  so fall back to a generic pointer type).
239 /// The member function must be an ordinary function, i.e. not a
240 /// constructor or destructor.
241 const CGFunctionInfo &
242 CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
243                                    const FunctionProtoType *FTP,
244                                    const CXXMethodDecl *MD) {
245   SmallVector<CanQualType, 16> argTypes;
246 
247   // Add the 'this' pointer.
248   if (RD)
249     argTypes.push_back(GetThisType(Context, RD));
250   else
251     argTypes.push_back(Context.VoidPtrTy);
252 
253   return ::arrangeLLVMFunctionInfo(
254       *this, true, argTypes,
255       FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
256 }
257 
258 /// Arrange the argument and result information for a declaration or
259 /// definition of the given C++ non-static member function.  The
260 /// member function must be an ordinary function, i.e. not a
261 /// constructor or destructor.
262 const CGFunctionInfo &
263 CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
264   assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
265   assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
266 
267   CanQual<FunctionProtoType> prototype = GetFormalType(MD);
268 
269   if (MD->isInstance()) {
270     // The abstract case is perfectly fine.
271     const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
272     return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
273   }
274 
275   return arrangeFreeFunctionType(prototype, MD);
276 }
277 
278 bool CodeGenTypes::inheritingCtorHasParams(
279     const InheritedConstructor &Inherited, CXXCtorType Type) {
280   // Parameters are unnecessary if we're constructing a base class subobject
281   // and the inherited constructor lives in a virtual base.
282   return Type == Ctor_Complete ||
283          !Inherited.getShadowDecl()->constructsVirtualBase() ||
284          !Target.getCXXABI().hasConstructorVariants();
285   }
286 
287 const CGFunctionInfo &
288 CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
289                                             StructorType Type) {
290 
291   SmallVector<CanQualType, 16> argTypes;
292   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
293   argTypes.push_back(GetThisType(Context, MD->getParent()));
294 
295   bool PassParams = true;
296 
297   GlobalDecl GD;
298   if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
299     GD = GlobalDecl(CD, toCXXCtorType(Type));
300 
301     // A base class inheriting constructor doesn't get forwarded arguments
302     // needed to construct a virtual base (or base class thereof).
303     if (auto Inherited = CD->getInheritedConstructor())
304       PassParams = inheritingCtorHasParams(Inherited, toCXXCtorType(Type));
305   } else {
306     auto *DD = dyn_cast<CXXDestructorDecl>(MD);
307     GD = GlobalDecl(DD, toCXXDtorType(Type));
308   }
309 
310   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
311 
312   // Add the formal parameters.
313   if (PassParams)
314     appendParameterTypes(*this, argTypes, paramInfos, FTP);
315 
316   CGCXXABI::AddedStructorArgs AddedArgs =
317       TheCXXABI.buildStructorSignature(MD, Type, argTypes);
318   if (!paramInfos.empty()) {
319     // Note: prefix implies after the first param.
320     if (AddedArgs.Prefix)
321       paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
322                         FunctionProtoType::ExtParameterInfo{});
323     if (AddedArgs.Suffix)
324       paramInfos.append(AddedArgs.Suffix,
325                         FunctionProtoType::ExtParameterInfo{});
326   }
327 
328   RequiredArgs required =
329       (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
330                                       : RequiredArgs::All);
331 
332   FunctionType::ExtInfo extInfo = FTP->getExtInfo();
333   CanQualType resultType = TheCXXABI.HasThisReturn(GD)
334                                ? argTypes.front()
335                                : TheCXXABI.hasMostDerivedReturn(GD)
336                                      ? CGM.getContext().VoidPtrTy
337                                      : Context.VoidTy;
338   return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
339                                  /*chainCall=*/false, argTypes, extInfo,
340                                  paramInfos, required);
341 }
342 
343 static SmallVector<CanQualType, 16>
344 getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
345   SmallVector<CanQualType, 16> argTypes;
346   for (auto &arg : args)
347     argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
348   return argTypes;
349 }
350 
351 static SmallVector<CanQualType, 16>
352 getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
353   SmallVector<CanQualType, 16> argTypes;
354   for (auto &arg : args)
355     argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
356   return argTypes;
357 }
358 
359 static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
360 getExtParameterInfosForCall(const FunctionProtoType *proto,
361                             unsigned prefixArgs, unsigned totalArgs) {
362   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
363   if (proto->hasExtParameterInfos()) {
364     addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
365   }
366   return result;
367 }
368 
369 /// Arrange a call to a C++ method, passing the given arguments.
370 ///
371 /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
372 /// parameter.
373 /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
374 /// args.
375 /// PassProtoArgs indicates whether `args` has args for the parameters in the
376 /// given CXXConstructorDecl.
377 const CGFunctionInfo &
378 CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
379                                         const CXXConstructorDecl *D,
380                                         CXXCtorType CtorKind,
381                                         unsigned ExtraPrefixArgs,
382                                         unsigned ExtraSuffixArgs,
383                                         bool PassProtoArgs) {
384   // FIXME: Kill copy.
385   SmallVector<CanQualType, 16> ArgTypes;
386   for (const auto &Arg : args)
387     ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
388 
389   // +1 for implicit this, which should always be args[0].
390   unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
391 
392   CanQual<FunctionProtoType> FPT = GetFormalType(D);
393   RequiredArgs Required =
394       RequiredArgs::forPrototypePlus(FPT, TotalPrefixArgs + ExtraSuffixArgs, D);
395   GlobalDecl GD(D, CtorKind);
396   CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
397                                ? ArgTypes.front()
398                                : TheCXXABI.hasMostDerivedReturn(GD)
399                                      ? CGM.getContext().VoidPtrTy
400                                      : Context.VoidTy;
401 
402   FunctionType::ExtInfo Info = FPT->getExtInfo();
403   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
404   // If the prototype args are elided, we should only have ABI-specific args,
405   // which never have param info.
406   if (PassProtoArgs && FPT->hasExtParameterInfos()) {
407     // ABI-specific suffix arguments are treated the same as variadic arguments.
408     addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
409                                 ArgTypes.size());
410   }
411   return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
412                                  /*chainCall=*/false, ArgTypes, Info,
413                                  ParamInfos, Required);
414 }
415 
416 /// Arrange the argument and result information for the declaration or
417 /// definition of the given function.
418 const CGFunctionInfo &
419 CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
420   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
421     if (MD->isInstance())
422       return arrangeCXXMethodDeclaration(MD);
423 
424   CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
425 
426   assert(isa<FunctionType>(FTy));
427 
428   // When declaring a function without a prototype, always use a
429   // non-variadic type.
430   if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
431     return arrangeLLVMFunctionInfo(
432         noProto->getReturnType(), /*instanceMethod=*/false,
433         /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
434   }
435 
436   return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>(), FD);
437 }
438 
439 /// Arrange the argument and result information for the declaration or
440 /// definition of an Objective-C method.
441 const CGFunctionInfo &
442 CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
443   // It happens that this is the same as a call with no optional
444   // arguments, except also using the formal 'self' type.
445   return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
446 }
447 
448 /// Arrange the argument and result information for the function type
449 /// through which to perform a send to the given Objective-C method,
450 /// using the given receiver type.  The receiver type is not always
451 /// the 'self' type of the method or even an Objective-C pointer type.
452 /// This is *not* the right method for actually performing such a
453 /// message send, due to the possibility of optional arguments.
454 const CGFunctionInfo &
455 CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
456                                               QualType receiverType) {
457   SmallVector<CanQualType, 16> argTys;
458   argTys.push_back(Context.getCanonicalParamType(receiverType));
459   argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
460   // FIXME: Kill copy?
461   for (const auto *I : MD->parameters()) {
462     argTys.push_back(Context.getCanonicalParamType(I->getType()));
463   }
464 
465   FunctionType::ExtInfo einfo;
466   bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
467   einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
468 
469   if (getContext().getLangOpts().ObjCAutoRefCount &&
470       MD->hasAttr<NSReturnsRetainedAttr>())
471     einfo = einfo.withProducesResult(true);
472 
473   RequiredArgs required =
474     (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
475 
476   return arrangeLLVMFunctionInfo(
477       GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
478       /*chainCall=*/false, argTys, einfo, {}, required);
479 }
480 
481 const CGFunctionInfo &
482 CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
483                                                  const CallArgList &args) {
484   auto argTypes = getArgTypesForCall(Context, args);
485   FunctionType::ExtInfo einfo;
486 
487   return arrangeLLVMFunctionInfo(
488       GetReturnType(returnType), /*instanceMethod=*/false,
489       /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
490 }
491 
492 const CGFunctionInfo &
493 CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
494   // FIXME: Do we need to handle ObjCMethodDecl?
495   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
496 
497   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
498     return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
499 
500   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
501     return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
502 
503   return arrangeFunctionDeclaration(FD);
504 }
505 
506 /// Arrange a thunk that takes 'this' as the first parameter followed by
507 /// varargs.  Return a void pointer, regardless of the actual return type.
508 /// The body of the thunk will end in a musttail call to a function of the
509 /// correct type, and the caller will bitcast the function to the correct
510 /// prototype.
511 const CGFunctionInfo &
512 CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
513   assert(MD->isVirtual() && "only virtual memptrs have thunks");
514   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
515   CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
516   return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
517                                  /*chainCall=*/false, ArgTys,
518                                  FTP->getExtInfo(), {}, RequiredArgs(1));
519 }
520 
521 const CGFunctionInfo &
522 CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
523                                    CXXCtorType CT) {
524   assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
525 
526   CanQual<FunctionProtoType> FTP = GetFormalType(CD);
527   SmallVector<CanQualType, 2> ArgTys;
528   const CXXRecordDecl *RD = CD->getParent();
529   ArgTys.push_back(GetThisType(Context, RD));
530   if (CT == Ctor_CopyingClosure)
531     ArgTys.push_back(*FTP->param_type_begin());
532   if (RD->getNumVBases() > 0)
533     ArgTys.push_back(Context.IntTy);
534   CallingConv CC = Context.getDefaultCallingConvention(
535       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
536   return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
537                                  /*chainCall=*/false, ArgTys,
538                                  FunctionType::ExtInfo(CC), {},
539                                  RequiredArgs::All);
540 }
541 
542 /// Arrange a call as unto a free function, except possibly with an
543 /// additional number of formal parameters considered required.
544 static const CGFunctionInfo &
545 arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
546                             CodeGenModule &CGM,
547                             const CallArgList &args,
548                             const FunctionType *fnType,
549                             unsigned numExtraRequiredArgs,
550                             bool chainCall) {
551   assert(args.size() >= numExtraRequiredArgs);
552 
553   llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
554 
555   // In most cases, there are no optional arguments.
556   RequiredArgs required = RequiredArgs::All;
557 
558   // If we have a variadic prototype, the required arguments are the
559   // extra prefix plus the arguments in the prototype.
560   if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
561     if (proto->isVariadic())
562       required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
563 
564     if (proto->hasExtParameterInfos())
565       addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
566                                   args.size());
567 
568   // If we don't have a prototype at all, but we're supposed to
569   // explicitly use the variadic convention for unprototyped calls,
570   // treat all of the arguments as required but preserve the nominal
571   // possibility of variadics.
572   } else if (CGM.getTargetCodeGenInfo()
573                 .isNoProtoCallVariadic(args,
574                                        cast<FunctionNoProtoType>(fnType))) {
575     required = RequiredArgs(args.size());
576   }
577 
578   // FIXME: Kill copy.
579   SmallVector<CanQualType, 16> argTypes;
580   for (const auto &arg : args)
581     argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
582   return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
583                                      /*instanceMethod=*/false, chainCall,
584                                      argTypes, fnType->getExtInfo(), paramInfos,
585                                      required);
586 }
587 
588 /// Figure out the rules for calling a function with the given formal
589 /// type using the given arguments.  The arguments are necessary
590 /// because the function might be unprototyped, in which case it's
591 /// target-dependent in crazy ways.
592 const CGFunctionInfo &
593 CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
594                                       const FunctionType *fnType,
595                                       bool chainCall) {
596   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
597                                      chainCall ? 1 : 0, chainCall);
598 }
599 
600 /// A block function is essentially a free function with an
601 /// extra implicit argument.
602 const CGFunctionInfo &
603 CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
604                                        const FunctionType *fnType) {
605   return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
606                                      /*chainCall=*/false);
607 }
608 
609 const CGFunctionInfo &
610 CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
611                                               const FunctionArgList &params) {
612   auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
613   auto argTypes = getArgTypesForDeclaration(Context, params);
614 
615   return arrangeLLVMFunctionInfo(
616       GetReturnType(proto->getReturnType()),
617       /*instanceMethod*/ false, /*chainCall*/ false, argTypes,
618       proto->getExtInfo(), paramInfos,
619       RequiredArgs::forPrototypePlus(proto, 1, nullptr));
620 }
621 
622 const CGFunctionInfo &
623 CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
624                                          const CallArgList &args) {
625   // FIXME: Kill copy.
626   SmallVector<CanQualType, 16> argTypes;
627   for (const auto &Arg : args)
628     argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
629   return arrangeLLVMFunctionInfo(
630       GetReturnType(resultType), /*instanceMethod=*/false,
631       /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
632       /*paramInfos=*/ {}, RequiredArgs::All);
633 }
634 
635 const CGFunctionInfo &
636 CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
637                                                 const FunctionArgList &args) {
638   auto argTypes = getArgTypesForDeclaration(Context, args);
639 
640   return arrangeLLVMFunctionInfo(
641       GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
642       argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
643 }
644 
645 const CGFunctionInfo &
646 CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
647                                               ArrayRef<CanQualType> argTypes) {
648   return arrangeLLVMFunctionInfo(
649       resultType, /*instanceMethod=*/false, /*chainCall=*/false,
650       argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
651 }
652 
653 /// Arrange a call to a C++ method, passing the given arguments.
654 ///
655 /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
656 /// does not count `this`.
657 const CGFunctionInfo &
658 CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
659                                    const FunctionProtoType *proto,
660                                    RequiredArgs required,
661                                    unsigned numPrefixArgs) {
662   assert(numPrefixArgs + 1 <= args.size() &&
663          "Emitting a call with less args than the required prefix?");
664   // Add one to account for `this`. It's a bit awkward here, but we don't count
665   // `this` in similar places elsewhere.
666   auto paramInfos =
667     getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
668 
669   // FIXME: Kill copy.
670   auto argTypes = getArgTypesForCall(Context, args);
671 
672   FunctionType::ExtInfo info = proto->getExtInfo();
673   return arrangeLLVMFunctionInfo(
674       GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
675       /*chainCall=*/false, argTypes, info, paramInfos, required);
676 }
677 
678 const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
679   return arrangeLLVMFunctionInfo(
680       getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
681       None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
682 }
683 
684 const CGFunctionInfo &
685 CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
686                           const CallArgList &args) {
687   assert(signature.arg_size() <= args.size());
688   if (signature.arg_size() == args.size())
689     return signature;
690 
691   SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
692   auto sigParamInfos = signature.getExtParameterInfos();
693   if (!sigParamInfos.empty()) {
694     paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
695     paramInfos.resize(args.size());
696   }
697 
698   auto argTypes = getArgTypesForCall(Context, args);
699 
700   assert(signature.getRequiredArgs().allowsOptionalArgs());
701   return arrangeLLVMFunctionInfo(signature.getReturnType(),
702                                  signature.isInstanceMethod(),
703                                  signature.isChainCall(),
704                                  argTypes,
705                                  signature.getExtInfo(),
706                                  paramInfos,
707                                  signature.getRequiredArgs());
708 }
709 
710 /// Arrange the argument and result information for an abstract value
711 /// of a given function type.  This is the method which all of the
712 /// above functions ultimately defer to.
713 const CGFunctionInfo &
714 CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
715                                       bool instanceMethod,
716                                       bool chainCall,
717                                       ArrayRef<CanQualType> argTypes,
718                                       FunctionType::ExtInfo info,
719                      ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
720                                       RequiredArgs required) {
721   assert(std::all_of(argTypes.begin(), argTypes.end(),
722                      [](CanQualType T) { return T.isCanonicalAsParam(); }));
723 
724   // Lookup or create unique function info.
725   llvm::FoldingSetNodeID ID;
726   CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
727                           required, resultType, argTypes);
728 
729   void *insertPos = nullptr;
730   CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
731   if (FI)
732     return *FI;
733 
734   unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
735 
736   // Construct the function info.  We co-allocate the ArgInfos.
737   FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
738                               paramInfos, resultType, argTypes, required);
739   FunctionInfos.InsertNode(FI, insertPos);
740 
741   bool inserted = FunctionsBeingProcessed.insert(FI).second;
742   (void)inserted;
743   assert(inserted && "Recursively being processed?");
744 
745   // Compute ABI information.
746   if (info.getCC() != CC_Swift) {
747     getABIInfo().computeInfo(*FI);
748   } else {
749     swiftcall::computeABIInfo(CGM, *FI);
750   }
751 
752   // Loop over all of the computed argument and return value info.  If any of
753   // them are direct or extend without a specified coerce type, specify the
754   // default now.
755   ABIArgInfo &retInfo = FI->getReturnInfo();
756   if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
757     retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
758 
759   for (auto &I : FI->arguments())
760     if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
761       I.info.setCoerceToType(ConvertType(I.type));
762 
763   bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
764   assert(erased && "Not in set?");
765 
766   return *FI;
767 }
768 
769 CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
770                                        bool instanceMethod,
771                                        bool chainCall,
772                                        const FunctionType::ExtInfo &info,
773                                        ArrayRef<ExtParameterInfo> paramInfos,
774                                        CanQualType resultType,
775                                        ArrayRef<CanQualType> argTypes,
776                                        RequiredArgs required) {
777   assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
778 
779   void *buffer =
780     operator new(totalSizeToAlloc<ArgInfo,             ExtParameterInfo>(
781                                   argTypes.size() + 1, paramInfos.size()));
782 
783   CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
784   FI->CallingConvention = llvmCC;
785   FI->EffectiveCallingConvention = llvmCC;
786   FI->ASTCallingConvention = info.getCC();
787   FI->InstanceMethod = instanceMethod;
788   FI->ChainCall = chainCall;
789   FI->NoReturn = info.getNoReturn();
790   FI->ReturnsRetained = info.getProducesResult();
791   FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
792   FI->Required = required;
793   FI->HasRegParm = info.getHasRegParm();
794   FI->RegParm = info.getRegParm();
795   FI->ArgStruct = nullptr;
796   FI->ArgStructAlign = 0;
797   FI->NumArgs = argTypes.size();
798   FI->HasExtParameterInfos = !paramInfos.empty();
799   FI->getArgsBuffer()[0].type = resultType;
800   for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
801     FI->getArgsBuffer()[i + 1].type = argTypes[i];
802   for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
803     FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
804   return FI;
805 }
806 
807 /***/
808 
809 namespace {
810 // ABIArgInfo::Expand implementation.
811 
812 // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
813 struct TypeExpansion {
814   enum TypeExpansionKind {
815     // Elements of constant arrays are expanded recursively.
816     TEK_ConstantArray,
817     // Record fields are expanded recursively (but if record is a union, only
818     // the field with the largest size is expanded).
819     TEK_Record,
820     // For complex types, real and imaginary parts are expanded recursively.
821     TEK_Complex,
822     // All other types are not expandable.
823     TEK_None
824   };
825 
826   const TypeExpansionKind Kind;
827 
828   TypeExpansion(TypeExpansionKind K) : Kind(K) {}
829   virtual ~TypeExpansion() {}
830 };
831 
832 struct ConstantArrayExpansion : TypeExpansion {
833   QualType EltTy;
834   uint64_t NumElts;
835 
836   ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
837       : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
838   static bool classof(const TypeExpansion *TE) {
839     return TE->Kind == TEK_ConstantArray;
840   }
841 };
842 
843 struct RecordExpansion : TypeExpansion {
844   SmallVector<const CXXBaseSpecifier *, 1> Bases;
845 
846   SmallVector<const FieldDecl *, 1> Fields;
847 
848   RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
849                   SmallVector<const FieldDecl *, 1> &&Fields)
850       : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
851         Fields(std::move(Fields)) {}
852   static bool classof(const TypeExpansion *TE) {
853     return TE->Kind == TEK_Record;
854   }
855 };
856 
857 struct ComplexExpansion : TypeExpansion {
858   QualType EltTy;
859 
860   ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
861   static bool classof(const TypeExpansion *TE) {
862     return TE->Kind == TEK_Complex;
863   }
864 };
865 
866 struct NoExpansion : TypeExpansion {
867   NoExpansion() : TypeExpansion(TEK_None) {}
868   static bool classof(const TypeExpansion *TE) {
869     return TE->Kind == TEK_None;
870   }
871 };
872 }  // namespace
873 
874 static std::unique_ptr<TypeExpansion>
875 getTypeExpansion(QualType Ty, const ASTContext &Context) {
876   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
877     return llvm::make_unique<ConstantArrayExpansion>(
878         AT->getElementType(), AT->getSize().getZExtValue());
879   }
880   if (const RecordType *RT = Ty->getAs<RecordType>()) {
881     SmallVector<const CXXBaseSpecifier *, 1> Bases;
882     SmallVector<const FieldDecl *, 1> Fields;
883     const RecordDecl *RD = RT->getDecl();
884     assert(!RD->hasFlexibleArrayMember() &&
885            "Cannot expand structure with flexible array.");
886     if (RD->isUnion()) {
887       // Unions can be here only in degenerative cases - all the fields are same
888       // after flattening. Thus we have to use the "largest" field.
889       const FieldDecl *LargestFD = nullptr;
890       CharUnits UnionSize = CharUnits::Zero();
891 
892       for (const auto *FD : RD->fields()) {
893         // Skip zero length bitfields.
894         if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
895           continue;
896         assert(!FD->isBitField() &&
897                "Cannot expand structure with bit-field members.");
898         CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
899         if (UnionSize < FieldSize) {
900           UnionSize = FieldSize;
901           LargestFD = FD;
902         }
903       }
904       if (LargestFD)
905         Fields.push_back(LargestFD);
906     } else {
907       if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
908         assert(!CXXRD->isDynamicClass() &&
909                "cannot expand vtable pointers in dynamic classes");
910         for (const CXXBaseSpecifier &BS : CXXRD->bases())
911           Bases.push_back(&BS);
912       }
913 
914       for (const auto *FD : RD->fields()) {
915         // Skip zero length bitfields.
916         if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
917           continue;
918         assert(!FD->isBitField() &&
919                "Cannot expand structure with bit-field members.");
920         Fields.push_back(FD);
921       }
922     }
923     return llvm::make_unique<RecordExpansion>(std::move(Bases),
924                                               std::move(Fields));
925   }
926   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
927     return llvm::make_unique<ComplexExpansion>(CT->getElementType());
928   }
929   return llvm::make_unique<NoExpansion>();
930 }
931 
932 static int getExpansionSize(QualType Ty, const ASTContext &Context) {
933   auto Exp = getTypeExpansion(Ty, Context);
934   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
935     return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
936   }
937   if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
938     int Res = 0;
939     for (auto BS : RExp->Bases)
940       Res += getExpansionSize(BS->getType(), Context);
941     for (auto FD : RExp->Fields)
942       Res += getExpansionSize(FD->getType(), Context);
943     return Res;
944   }
945   if (isa<ComplexExpansion>(Exp.get()))
946     return 2;
947   assert(isa<NoExpansion>(Exp.get()));
948   return 1;
949 }
950 
951 void
952 CodeGenTypes::getExpandedTypes(QualType Ty,
953                                SmallVectorImpl<llvm::Type *>::iterator &TI) {
954   auto Exp = getTypeExpansion(Ty, Context);
955   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
956     for (int i = 0, n = CAExp->NumElts; i < n; i++) {
957       getExpandedTypes(CAExp->EltTy, TI);
958     }
959   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
960     for (auto BS : RExp->Bases)
961       getExpandedTypes(BS->getType(), TI);
962     for (auto FD : RExp->Fields)
963       getExpandedTypes(FD->getType(), TI);
964   } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
965     llvm::Type *EltTy = ConvertType(CExp->EltTy);
966     *TI++ = EltTy;
967     *TI++ = EltTy;
968   } else {
969     assert(isa<NoExpansion>(Exp.get()));
970     *TI++ = ConvertType(Ty);
971   }
972 }
973 
974 static void forConstantArrayExpansion(CodeGenFunction &CGF,
975                                       ConstantArrayExpansion *CAE,
976                                       Address BaseAddr,
977                                       llvm::function_ref<void(Address)> Fn) {
978   CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
979   CharUnits EltAlign =
980     BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
981 
982   for (int i = 0, n = CAE->NumElts; i < n; i++) {
983     llvm::Value *EltAddr =
984       CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
985     Fn(Address(EltAddr, EltAlign));
986   }
987 }
988 
989 void CodeGenFunction::ExpandTypeFromArgs(
990     QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
991   assert(LV.isSimple() &&
992          "Unexpected non-simple lvalue during struct expansion.");
993 
994   auto Exp = getTypeExpansion(Ty, getContext());
995   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
996     forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
997                               [&](Address EltAddr) {
998       LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
999       ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
1000     });
1001   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1002     Address This = LV.getAddress();
1003     for (const CXXBaseSpecifier *BS : RExp->Bases) {
1004       // Perform a single step derived-to-base conversion.
1005       Address Base =
1006           GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1007                                 /*NullCheckValue=*/false, SourceLocation());
1008       LValue SubLV = MakeAddrLValue(Base, BS->getType());
1009 
1010       // Recurse onto bases.
1011       ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1012     }
1013     for (auto FD : RExp->Fields) {
1014       // FIXME: What are the right qualifiers here?
1015       LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
1016       ExpandTypeFromArgs(FD->getType(), SubLV, AI);
1017     }
1018   } else if (isa<ComplexExpansion>(Exp.get())) {
1019     auto realValue = *AI++;
1020     auto imagValue = *AI++;
1021     EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
1022   } else {
1023     assert(isa<NoExpansion>(Exp.get()));
1024     EmitStoreThroughLValue(RValue::get(*AI++), LV);
1025   }
1026 }
1027 
1028 void CodeGenFunction::ExpandTypeToArgs(
1029     QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
1030     SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1031   auto Exp = getTypeExpansion(Ty, getContext());
1032   if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1033     forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
1034                               [&](Address EltAddr) {
1035       RValue EltRV =
1036           convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
1037       ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
1038     });
1039   } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1040     Address This = RV.getAggregateAddress();
1041     for (const CXXBaseSpecifier *BS : RExp->Bases) {
1042       // Perform a single step derived-to-base conversion.
1043       Address Base =
1044           GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1045                                 /*NullCheckValue=*/false, SourceLocation());
1046       RValue BaseRV = RValue::getAggregate(Base);
1047 
1048       // Recurse onto bases.
1049       ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
1050                        IRCallArgPos);
1051     }
1052 
1053     LValue LV = MakeAddrLValue(This, Ty);
1054     for (auto FD : RExp->Fields) {
1055       RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
1056       ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
1057                        IRCallArgPos);
1058     }
1059   } else if (isa<ComplexExpansion>(Exp.get())) {
1060     ComplexPairTy CV = RV.getComplexVal();
1061     IRCallArgs[IRCallArgPos++] = CV.first;
1062     IRCallArgs[IRCallArgPos++] = CV.second;
1063   } else {
1064     assert(isa<NoExpansion>(Exp.get()));
1065     assert(RV.isScalar() &&
1066            "Unexpected non-scalar rvalue during struct expansion.");
1067 
1068     // Insert a bitcast as needed.
1069     llvm::Value *V = RV.getScalarVal();
1070     if (IRCallArgPos < IRFuncTy->getNumParams() &&
1071         V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1072       V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1073 
1074     IRCallArgs[IRCallArgPos++] = V;
1075   }
1076 }
1077 
1078 /// Create a temporary allocation for the purposes of coercion.
1079 static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1080                                            CharUnits MinAlign) {
1081   // Don't use an alignment that's worse than what LLVM would prefer.
1082   auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1083   CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1084 
1085   return CGF.CreateTempAlloca(Ty, Align);
1086 }
1087 
1088 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1089 /// accessing some number of bytes out of it, try to gep into the struct to get
1090 /// at its inner goodness.  Dive as deep as possible without entering an element
1091 /// with an in-memory size smaller than DstSize.
1092 static Address
1093 EnterStructPointerForCoercedAccess(Address SrcPtr,
1094                                    llvm::StructType *SrcSTy,
1095                                    uint64_t DstSize, CodeGenFunction &CGF) {
1096   // We can't dive into a zero-element struct.
1097   if (SrcSTy->getNumElements() == 0) return SrcPtr;
1098 
1099   llvm::Type *FirstElt = SrcSTy->getElementType(0);
1100 
1101   // If the first elt is at least as large as what we're looking for, or if the
1102   // first element is the same size as the whole struct, we can enter it. The
1103   // comparison must be made on the store size and not the alloca size. Using
1104   // the alloca size may overstate the size of the load.
1105   uint64_t FirstEltSize =
1106     CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
1107   if (FirstEltSize < DstSize &&
1108       FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
1109     return SrcPtr;
1110 
1111   // GEP into the first element.
1112   SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
1113 
1114   // If the first element is a struct, recurse.
1115   llvm::Type *SrcTy = SrcPtr.getElementType();
1116   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
1117     return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
1118 
1119   return SrcPtr;
1120 }
1121 
1122 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1123 /// are either integers or pointers.  This does a truncation of the value if it
1124 /// is too large or a zero extension if it is too small.
1125 ///
1126 /// This behaves as if the value were coerced through memory, so on big-endian
1127 /// targets the high bits are preserved in a truncation, while little-endian
1128 /// targets preserve the low bits.
1129 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
1130                                              llvm::Type *Ty,
1131                                              CodeGenFunction &CGF) {
1132   if (Val->getType() == Ty)
1133     return Val;
1134 
1135   if (isa<llvm::PointerType>(Val->getType())) {
1136     // If this is Pointer->Pointer avoid conversion to and from int.
1137     if (isa<llvm::PointerType>(Ty))
1138       return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
1139 
1140     // Convert the pointer to an integer so we can play with its width.
1141     Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
1142   }
1143 
1144   llvm::Type *DestIntTy = Ty;
1145   if (isa<llvm::PointerType>(DestIntTy))
1146     DestIntTy = CGF.IntPtrTy;
1147 
1148   if (Val->getType() != DestIntTy) {
1149     const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1150     if (DL.isBigEndian()) {
1151       // Preserve the high bits on big-endian targets.
1152       // That is what memory coercion does.
1153       uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1154       uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1155 
1156       if (SrcSize > DstSize) {
1157         Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1158         Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1159       } else {
1160         Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1161         Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1162       }
1163     } else {
1164       // Little-endian targets preserve the low bits. No shifts required.
1165       Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1166     }
1167   }
1168 
1169   if (isa<llvm::PointerType>(Ty))
1170     Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1171   return Val;
1172 }
1173 
1174 
1175 
1176 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1177 /// a pointer to an object of type \arg Ty, known to be aligned to
1178 /// \arg SrcAlign bytes.
1179 ///
1180 /// This safely handles the case when the src type is smaller than the
1181 /// destination type; in this situation the values of bits which not
1182 /// present in the src are undefined.
1183 static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
1184                                       CodeGenFunction &CGF) {
1185   llvm::Type *SrcTy = Src.getElementType();
1186 
1187   // If SrcTy and Ty are the same, just do a load.
1188   if (SrcTy == Ty)
1189     return CGF.Builder.CreateLoad(Src);
1190 
1191   uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
1192 
1193   if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1194     Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1195     SrcTy = Src.getType()->getElementType();
1196   }
1197 
1198   uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1199 
1200   // If the source and destination are integer or pointer types, just do an
1201   // extension or truncation to the desired type.
1202   if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1203       (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
1204     llvm::Value *Load = CGF.Builder.CreateLoad(Src);
1205     return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1206   }
1207 
1208   // If load is legal, just bitcast the src pointer.
1209   if (SrcSize >= DstSize) {
1210     // Generally SrcSize is never greater than DstSize, since this means we are
1211     // losing bits. However, this can happen in cases where the structure has
1212     // additional padding, for example due to a user specified alignment.
1213     //
1214     // FIXME: Assert that we aren't truncating non-padding bits when have access
1215     // to that information.
1216     Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1217     return CGF.Builder.CreateLoad(Src);
1218   }
1219 
1220   // Otherwise do coercion through memory. This is stupid, but simple.
1221   Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1222   Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1223   Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
1224   CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1225       llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
1226       false);
1227   return CGF.Builder.CreateLoad(Tmp);
1228 }
1229 
1230 // Function to store a first-class aggregate into memory.  We prefer to
1231 // store the elements rather than the aggregate to be more friendly to
1232 // fast-isel.
1233 // FIXME: Do we need to recurse here?
1234 static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
1235                           Address Dest, bool DestIsVolatile) {
1236   // Prefer scalar stores to first-class aggregate stores.
1237   if (llvm::StructType *STy =
1238         dyn_cast<llvm::StructType>(Val->getType())) {
1239     const llvm::StructLayout *Layout =
1240       CGF.CGM.getDataLayout().getStructLayout(STy);
1241 
1242     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1243       auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1244       Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
1245       llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
1246       CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
1247     }
1248   } else {
1249     CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
1250   }
1251 }
1252 
1253 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1254 /// where the source and destination may have different types.  The
1255 /// destination is known to be aligned to \arg DstAlign bytes.
1256 ///
1257 /// This safely handles the case when the src type is larger than the
1258 /// destination type; the upper bits of the src will be lost.
1259 static void CreateCoercedStore(llvm::Value *Src,
1260                                Address Dst,
1261                                bool DstIsVolatile,
1262                                CodeGenFunction &CGF) {
1263   llvm::Type *SrcTy = Src->getType();
1264   llvm::Type *DstTy = Dst.getType()->getElementType();
1265   if (SrcTy == DstTy) {
1266     CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1267     return;
1268   }
1269 
1270   uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1271 
1272   if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1273     Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1274     DstTy = Dst.getType()->getElementType();
1275   }
1276 
1277   // If the source and destination are integer or pointer types, just do an
1278   // extension or truncation to the desired type.
1279   if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1280       (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1281     Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1282     CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1283     return;
1284   }
1285 
1286   uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
1287 
1288   // If store is legal, just bitcast the src pointer.
1289   if (SrcSize <= DstSize) {
1290     Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1291     BuildAggStore(CGF, Src, Dst, DstIsVolatile);
1292   } else {
1293     // Otherwise do coercion through memory. This is stupid, but
1294     // simple.
1295 
1296     // Generally SrcSize is never greater than DstSize, since this means we are
1297     // losing bits. However, this can happen in cases where the structure has
1298     // additional padding, for example due to a user specified alignment.
1299     //
1300     // FIXME: Assert that we aren't truncating non-padding bits when have access
1301     // to that information.
1302     Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1303     CGF.Builder.CreateStore(Src, Tmp);
1304     Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1305     Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
1306     CGF.Builder.CreateMemCpy(DstCasted, Casted,
1307         llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1308         false);
1309   }
1310 }
1311 
1312 static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1313                                    const ABIArgInfo &info) {
1314   if (unsigned offset = info.getDirectOffset()) {
1315     addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1316     addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1317                                              CharUnits::fromQuantity(offset));
1318     addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1319   }
1320   return addr;
1321 }
1322 
1323 namespace {
1324 
1325 /// Encapsulates information about the way function arguments from
1326 /// CGFunctionInfo should be passed to actual LLVM IR function.
1327 class ClangToLLVMArgMapping {
1328   static const unsigned InvalidIndex = ~0U;
1329   unsigned InallocaArgNo;
1330   unsigned SRetArgNo;
1331   unsigned TotalIRArgs;
1332 
1333   /// Arguments of LLVM IR function corresponding to single Clang argument.
1334   struct IRArgs {
1335     unsigned PaddingArgIndex;
1336     // Argument is expanded to IR arguments at positions
1337     // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1338     unsigned FirstArgIndex;
1339     unsigned NumberOfArgs;
1340 
1341     IRArgs()
1342         : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1343           NumberOfArgs(0) {}
1344   };
1345 
1346   SmallVector<IRArgs, 8> ArgInfo;
1347 
1348 public:
1349   ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1350                         bool OnlyRequiredArgs = false)
1351       : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1352         ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1353     construct(Context, FI, OnlyRequiredArgs);
1354   }
1355 
1356   bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1357   unsigned getInallocaArgNo() const {
1358     assert(hasInallocaArg());
1359     return InallocaArgNo;
1360   }
1361 
1362   bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1363   unsigned getSRetArgNo() const {
1364     assert(hasSRetArg());
1365     return SRetArgNo;
1366   }
1367 
1368   unsigned totalIRArgs() const { return TotalIRArgs; }
1369 
1370   bool hasPaddingArg(unsigned ArgNo) const {
1371     assert(ArgNo < ArgInfo.size());
1372     return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1373   }
1374   unsigned getPaddingArgNo(unsigned ArgNo) const {
1375     assert(hasPaddingArg(ArgNo));
1376     return ArgInfo[ArgNo].PaddingArgIndex;
1377   }
1378 
1379   /// Returns index of first IR argument corresponding to ArgNo, and their
1380   /// quantity.
1381   std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1382     assert(ArgNo < ArgInfo.size());
1383     return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1384                           ArgInfo[ArgNo].NumberOfArgs);
1385   }
1386 
1387 private:
1388   void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1389                  bool OnlyRequiredArgs);
1390 };
1391 
1392 void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1393                                       const CGFunctionInfo &FI,
1394                                       bool OnlyRequiredArgs) {
1395   unsigned IRArgNo = 0;
1396   bool SwapThisWithSRet = false;
1397   const ABIArgInfo &RetAI = FI.getReturnInfo();
1398 
1399   if (RetAI.getKind() == ABIArgInfo::Indirect) {
1400     SwapThisWithSRet = RetAI.isSRetAfterThis();
1401     SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1402   }
1403 
1404   unsigned ArgNo = 0;
1405   unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1406   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1407        ++I, ++ArgNo) {
1408     assert(I != FI.arg_end());
1409     QualType ArgType = I->type;
1410     const ABIArgInfo &AI = I->info;
1411     // Collect data about IR arguments corresponding to Clang argument ArgNo.
1412     auto &IRArgs = ArgInfo[ArgNo];
1413 
1414     if (AI.getPaddingType())
1415       IRArgs.PaddingArgIndex = IRArgNo++;
1416 
1417     switch (AI.getKind()) {
1418     case ABIArgInfo::Extend:
1419     case ABIArgInfo::Direct: {
1420       // FIXME: handle sseregparm someday...
1421       llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1422       if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1423         IRArgs.NumberOfArgs = STy->getNumElements();
1424       } else {
1425         IRArgs.NumberOfArgs = 1;
1426       }
1427       break;
1428     }
1429     case ABIArgInfo::Indirect:
1430       IRArgs.NumberOfArgs = 1;
1431       break;
1432     case ABIArgInfo::Ignore:
1433     case ABIArgInfo::InAlloca:
1434       // ignore and inalloca doesn't have matching LLVM parameters.
1435       IRArgs.NumberOfArgs = 0;
1436       break;
1437     case ABIArgInfo::CoerceAndExpand:
1438       IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1439       break;
1440     case ABIArgInfo::Expand:
1441       IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1442       break;
1443     }
1444 
1445     if (IRArgs.NumberOfArgs > 0) {
1446       IRArgs.FirstArgIndex = IRArgNo;
1447       IRArgNo += IRArgs.NumberOfArgs;
1448     }
1449 
1450     // Skip over the sret parameter when it comes second.  We already handled it
1451     // above.
1452     if (IRArgNo == 1 && SwapThisWithSRet)
1453       IRArgNo++;
1454   }
1455   assert(ArgNo == ArgInfo.size());
1456 
1457   if (FI.usesInAlloca())
1458     InallocaArgNo = IRArgNo++;
1459 
1460   TotalIRArgs = IRArgNo;
1461 }
1462 }  // namespace
1463 
1464 /***/
1465 
1466 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
1467   return FI.getReturnInfo().isIndirect();
1468 }
1469 
1470 bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1471   return ReturnTypeUsesSRet(FI) &&
1472          getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1473 }
1474 
1475 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1476   if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1477     switch (BT->getKind()) {
1478     default:
1479       return false;
1480     case BuiltinType::Float:
1481       return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
1482     case BuiltinType::Double:
1483       return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
1484     case BuiltinType::LongDouble:
1485       return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
1486     }
1487   }
1488 
1489   return false;
1490 }
1491 
1492 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1493   if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1494     if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1495       if (BT->getKind() == BuiltinType::LongDouble)
1496         return getTarget().useObjCFP2RetForComplexLongDouble();
1497     }
1498   }
1499 
1500   return false;
1501 }
1502 
1503 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
1504   const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1505   return GetFunctionType(FI);
1506 }
1507 
1508 llvm::FunctionType *
1509 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
1510 
1511   bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1512   (void)Inserted;
1513   assert(Inserted && "Recursively being processed?");
1514 
1515   llvm::Type *resultType = nullptr;
1516   const ABIArgInfo &retAI = FI.getReturnInfo();
1517   switch (retAI.getKind()) {
1518   case ABIArgInfo::Expand:
1519     llvm_unreachable("Invalid ABI kind for return argument");
1520 
1521   case ABIArgInfo::Extend:
1522   case ABIArgInfo::Direct:
1523     resultType = retAI.getCoerceToType();
1524     break;
1525 
1526   case ABIArgInfo::InAlloca:
1527     if (retAI.getInAllocaSRet()) {
1528       // sret things on win32 aren't void, they return the sret pointer.
1529       QualType ret = FI.getReturnType();
1530       llvm::Type *ty = ConvertType(ret);
1531       unsigned addressSpace = Context.getTargetAddressSpace(ret);
1532       resultType = llvm::PointerType::get(ty, addressSpace);
1533     } else {
1534       resultType = llvm::Type::getVoidTy(getLLVMContext());
1535     }
1536     break;
1537 
1538   case ABIArgInfo::Indirect:
1539   case ABIArgInfo::Ignore:
1540     resultType = llvm::Type::getVoidTy(getLLVMContext());
1541     break;
1542 
1543   case ABIArgInfo::CoerceAndExpand:
1544     resultType = retAI.getUnpaddedCoerceAndExpandType();
1545     break;
1546   }
1547 
1548   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1549   SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1550 
1551   // Add type for sret argument.
1552   if (IRFunctionArgs.hasSRetArg()) {
1553     QualType Ret = FI.getReturnType();
1554     llvm::Type *Ty = ConvertType(Ret);
1555     unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1556     ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1557         llvm::PointerType::get(Ty, AddressSpace);
1558   }
1559 
1560   // Add type for inalloca argument.
1561   if (IRFunctionArgs.hasInallocaArg()) {
1562     auto ArgStruct = FI.getArgStruct();
1563     assert(ArgStruct);
1564     ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1565   }
1566 
1567   // Add in all of the required arguments.
1568   unsigned ArgNo = 0;
1569   CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1570                                      ie = it + FI.getNumRequiredArgs();
1571   for (; it != ie; ++it, ++ArgNo) {
1572     const ABIArgInfo &ArgInfo = it->info;
1573 
1574     // Insert a padding type to ensure proper alignment.
1575     if (IRFunctionArgs.hasPaddingArg(ArgNo))
1576       ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1577           ArgInfo.getPaddingType();
1578 
1579     unsigned FirstIRArg, NumIRArgs;
1580     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1581 
1582     switch (ArgInfo.getKind()) {
1583     case ABIArgInfo::Ignore:
1584     case ABIArgInfo::InAlloca:
1585       assert(NumIRArgs == 0);
1586       break;
1587 
1588     case ABIArgInfo::Indirect: {
1589       assert(NumIRArgs == 1);
1590       // indirect arguments are always on the stack, which is alloca addr space.
1591       llvm::Type *LTy = ConvertTypeForMem(it->type);
1592       ArgTypes[FirstIRArg] = LTy->getPointerTo(
1593           CGM.getDataLayout().getAllocaAddrSpace());
1594       break;
1595     }
1596 
1597     case ABIArgInfo::Extend:
1598     case ABIArgInfo::Direct: {
1599       // Fast-isel and the optimizer generally like scalar values better than
1600       // FCAs, so we flatten them if this is safe to do for this argument.
1601       llvm::Type *argType = ArgInfo.getCoerceToType();
1602       llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1603       if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1604         assert(NumIRArgs == st->getNumElements());
1605         for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1606           ArgTypes[FirstIRArg + i] = st->getElementType(i);
1607       } else {
1608         assert(NumIRArgs == 1);
1609         ArgTypes[FirstIRArg] = argType;
1610       }
1611       break;
1612     }
1613 
1614     case ABIArgInfo::CoerceAndExpand: {
1615       auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1616       for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1617         *ArgTypesIter++ = EltTy;
1618       }
1619       assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1620       break;
1621     }
1622 
1623     case ABIArgInfo::Expand:
1624       auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1625       getExpandedTypes(it->type, ArgTypesIter);
1626       assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1627       break;
1628     }
1629   }
1630 
1631   bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1632   assert(Erased && "Not in set?");
1633 
1634   return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1635 }
1636 
1637 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
1638   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1639   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1640 
1641   if (!isFuncTypeConvertible(FPT))
1642     return llvm::StructType::get(getLLVMContext());
1643 
1644   const CGFunctionInfo *Info;
1645   if (isa<CXXDestructorDecl>(MD))
1646     Info =
1647         &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
1648   else
1649     Info = &arrangeCXXMethodDeclaration(MD);
1650   return GetFunctionType(*Info);
1651 }
1652 
1653 static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1654                                                llvm::AttrBuilder &FuncAttrs,
1655                                                const FunctionProtoType *FPT) {
1656   if (!FPT)
1657     return;
1658 
1659   if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1660       FPT->isNothrow(Ctx))
1661     FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1662 }
1663 
1664 void CodeGenModule::ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1665                                                bool AttrOnCallSite,
1666                                                llvm::AttrBuilder &FuncAttrs) {
1667   // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1668   if (!HasOptnone) {
1669     if (CodeGenOpts.OptimizeSize)
1670       FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1671     if (CodeGenOpts.OptimizeSize == 2)
1672       FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1673   }
1674 
1675   if (CodeGenOpts.DisableRedZone)
1676     FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1677   if (CodeGenOpts.NoImplicitFloat)
1678     FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1679 
1680   if (AttrOnCallSite) {
1681     // Attributes that should go on the call site only.
1682     if (!CodeGenOpts.SimplifyLibCalls ||
1683         CodeGenOpts.isNoBuiltinFunc(Name.data()))
1684       FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1685     if (!CodeGenOpts.TrapFuncName.empty())
1686       FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1687   } else {
1688     // Attributes that should go on the function, but not the call site.
1689     if (!CodeGenOpts.DisableFPElim) {
1690       FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1691     } else if (CodeGenOpts.OmitLeafFramePointer) {
1692       FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1693       FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1694     } else {
1695       FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
1696       FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1697     }
1698 
1699     FuncAttrs.addAttribute("less-precise-fpmad",
1700                            llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
1701 
1702     if (!CodeGenOpts.FPDenormalMode.empty())
1703       FuncAttrs.addAttribute("denormal-fp-math", CodeGenOpts.FPDenormalMode);
1704 
1705     FuncAttrs.addAttribute("no-trapping-math",
1706                            llvm::toStringRef(CodeGenOpts.NoTrappingMath));
1707 
1708     // TODO: Are these all needed?
1709     // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1710     FuncAttrs.addAttribute("no-infs-fp-math",
1711                            llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
1712     FuncAttrs.addAttribute("no-nans-fp-math",
1713                            llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
1714     FuncAttrs.addAttribute("unsafe-fp-math",
1715                            llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
1716     FuncAttrs.addAttribute("use-soft-float",
1717                            llvm::toStringRef(CodeGenOpts.SoftFloat));
1718     FuncAttrs.addAttribute("stack-protector-buffer-size",
1719                            llvm::utostr(CodeGenOpts.SSPBufferSize));
1720     FuncAttrs.addAttribute("no-signed-zeros-fp-math",
1721                            llvm::toStringRef(CodeGenOpts.NoSignedZeros));
1722     FuncAttrs.addAttribute(
1723         "correctly-rounded-divide-sqrt-fp-math",
1724         llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
1725 
1726     // TODO: Reciprocal estimate codegen options should apply to instructions?
1727     std::vector<std::string> &Recips = getTarget().getTargetOpts().Reciprocals;
1728     if (!Recips.empty())
1729       FuncAttrs.addAttribute("reciprocal-estimates",
1730                              llvm::join(Recips.begin(), Recips.end(), ","));
1731 
1732     if (CodeGenOpts.StackRealignment)
1733       FuncAttrs.addAttribute("stackrealign");
1734     if (CodeGenOpts.Backchain)
1735       FuncAttrs.addAttribute("backchain");
1736   }
1737 
1738   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1739     // Conservatively, mark all functions and calls in CUDA as convergent
1740     // (meaning, they may call an intrinsically convergent op, such as
1741     // __syncthreads(), and so can't have certain optimizations applied around
1742     // them).  LLVM will remove this attribute where it safely can.
1743     FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1744 
1745     // Exceptions aren't supported in CUDA device code.
1746     FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1747 
1748     // Respect -fcuda-flush-denormals-to-zero.
1749     if (getLangOpts().CUDADeviceFlushDenormalsToZero)
1750       FuncAttrs.addAttribute("nvptx-f32ftz", "true");
1751   }
1752 }
1753 
1754 void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) {
1755   llvm::AttrBuilder FuncAttrs;
1756   ConstructDefaultFnAttrList(F.getName(),
1757                              F.hasFnAttribute(llvm::Attribute::OptimizeNone),
1758                              /* AttrOnCallsite = */ false, FuncAttrs);
1759   llvm::AttributeList AS = llvm::AttributeList::get(
1760       getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
1761   F.addAttributes(llvm::AttributeList::FunctionIndex, AS);
1762 }
1763 
1764 void CodeGenModule::ConstructAttributeList(
1765     StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1766     llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) {
1767   llvm::AttrBuilder FuncAttrs;
1768   llvm::AttrBuilder RetAttrs;
1769 
1770   CallingConv = FI.getEffectiveCallingConvention();
1771   if (FI.isNoReturn())
1772     FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1773 
1774   // If we have information about the function prototype, we can learn
1775   // attributes form there.
1776   AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1777                                      CalleeInfo.getCalleeFunctionProtoType());
1778 
1779   const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1780 
1781   bool HasOptnone = false;
1782   // FIXME: handle sseregparm someday...
1783   if (TargetDecl) {
1784     if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
1785       FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
1786     if (TargetDecl->hasAttr<NoThrowAttr>())
1787       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1788     if (TargetDecl->hasAttr<NoReturnAttr>())
1789       FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1790     if (TargetDecl->hasAttr<NoDuplicateAttr>())
1791       FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
1792     if (TargetDecl->hasAttr<ConvergentAttr>())
1793       FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1794 
1795     if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
1796       AddAttributesFromFunctionProtoType(
1797           getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
1798       // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1799       // These attributes are not inherited by overloads.
1800       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1801       if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
1802         FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1803     }
1804 
1805     // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
1806     if (TargetDecl->hasAttr<ConstAttr>()) {
1807       FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1808       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1809     } else if (TargetDecl->hasAttr<PureAttr>()) {
1810       FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1811       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1812     } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1813       FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1814       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1815     }
1816     if (TargetDecl->hasAttr<RestrictAttr>())
1817       RetAttrs.addAttribute(llvm::Attribute::NoAlias);
1818     if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1819       RetAttrs.addAttribute(llvm::Attribute::NonNull);
1820     if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
1821       FuncAttrs.addAttribute("no_caller_saved_registers");
1822 
1823     HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
1824     if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
1825       Optional<unsigned> NumElemsParam;
1826       // alloc_size args are base-1, 0 means not present.
1827       if (unsigned N = AllocSize->getNumElemsParam())
1828         NumElemsParam = N - 1;
1829       FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam() - 1,
1830                                  NumElemsParam);
1831     }
1832   }
1833 
1834   ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
1835 
1836   if (CodeGenOpts.EnableSegmentedStacks &&
1837       !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
1838     FuncAttrs.addAttribute("split-stack");
1839 
1840   if (!AttrOnCallSite) {
1841     bool DisableTailCalls =
1842         CodeGenOpts.DisableTailCalls ||
1843         (TargetDecl && (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
1844                         TargetDecl->hasAttr<AnyX86InterruptAttr>()));
1845     FuncAttrs.addAttribute("disable-tail-calls",
1846                            llvm::toStringRef(DisableTailCalls));
1847 
1848     // Add target-cpu and target-features attributes to functions. If
1849     // we have a decl for the function and it has a target attribute then
1850     // parse that and add it to the feature set.
1851     StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1852     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
1853     if (FD && FD->hasAttr<TargetAttr>()) {
1854       llvm::StringMap<bool> FeatureMap;
1855       getFunctionFeatureMap(FeatureMap, FD);
1856 
1857       // Produce the canonical string for this set of features.
1858       std::vector<std::string> Features;
1859       for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1860                                                  ie = FeatureMap.end();
1861            it != ie; ++it)
1862         Features.push_back((it->second ? "+" : "-") + it->first().str());
1863 
1864       // Now add the target-cpu and target-features to the function.
1865       // While we populated the feature map above, we still need to
1866       // get and parse the target attribute so we can get the cpu for
1867       // the function.
1868       const auto *TD = FD->getAttr<TargetAttr>();
1869       TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1870       if (ParsedAttr.second != "")
1871         TargetCPU = ParsedAttr.second;
1872       if (TargetCPU != "")
1873         FuncAttrs.addAttribute("target-cpu", TargetCPU);
1874       if (!Features.empty()) {
1875         std::sort(Features.begin(), Features.end());
1876         FuncAttrs.addAttribute(
1877             "target-features",
1878             llvm::join(Features.begin(), Features.end(), ","));
1879       }
1880     } else {
1881       // Otherwise just add the existing target cpu and target features to the
1882       // function.
1883       std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1884       if (TargetCPU != "")
1885         FuncAttrs.addAttribute("target-cpu", TargetCPU);
1886       if (!Features.empty()) {
1887         std::sort(Features.begin(), Features.end());
1888         FuncAttrs.addAttribute(
1889             "target-features",
1890             llvm::join(Features.begin(), Features.end(), ","));
1891       }
1892     }
1893   }
1894 
1895   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
1896 
1897   QualType RetTy = FI.getReturnType();
1898   const ABIArgInfo &RetAI = FI.getReturnInfo();
1899   switch (RetAI.getKind()) {
1900   case ABIArgInfo::Extend:
1901     if (RetTy->hasSignedIntegerRepresentation())
1902       RetAttrs.addAttribute(llvm::Attribute::SExt);
1903     else if (RetTy->hasUnsignedIntegerRepresentation())
1904       RetAttrs.addAttribute(llvm::Attribute::ZExt);
1905     // FALL THROUGH
1906   case ABIArgInfo::Direct:
1907     if (RetAI.getInReg())
1908       RetAttrs.addAttribute(llvm::Attribute::InReg);
1909     break;
1910   case ABIArgInfo::Ignore:
1911     break;
1912 
1913   case ABIArgInfo::InAlloca:
1914   case ABIArgInfo::Indirect: {
1915     // inalloca and sret disable readnone and readonly
1916     FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1917       .removeAttribute(llvm::Attribute::ReadNone);
1918     break;
1919   }
1920 
1921   case ABIArgInfo::CoerceAndExpand:
1922     break;
1923 
1924   case ABIArgInfo::Expand:
1925     llvm_unreachable("Invalid ABI kind for return argument");
1926   }
1927 
1928   if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1929     QualType PTy = RefTy->getPointeeType();
1930     if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1931       RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1932                                         .getQuantity());
1933     else if (getContext().getTargetAddressSpace(PTy) == 0)
1934       RetAttrs.addAttribute(llvm::Attribute::NonNull);
1935   }
1936 
1937   bool hasUsedSRet = false;
1938   SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
1939 
1940   // Attach attributes to sret.
1941   if (IRFunctionArgs.hasSRetArg()) {
1942     llvm::AttrBuilder SRETAttrs;
1943     SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1944     hasUsedSRet = true;
1945     if (RetAI.getInReg())
1946       SRETAttrs.addAttribute(llvm::Attribute::InReg);
1947     ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
1948         llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
1949   }
1950 
1951   // Attach attributes to inalloca argument.
1952   if (IRFunctionArgs.hasInallocaArg()) {
1953     llvm::AttrBuilder Attrs;
1954     Attrs.addAttribute(llvm::Attribute::InAlloca);
1955     ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
1956         llvm::AttributeSet::get(getLLVMContext(), Attrs);
1957   }
1958 
1959   unsigned ArgNo = 0;
1960   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1961                                           E = FI.arg_end();
1962        I != E; ++I, ++ArgNo) {
1963     QualType ParamType = I->type;
1964     const ABIArgInfo &AI = I->info;
1965     llvm::AttrBuilder Attrs;
1966 
1967     // Add attribute for padding argument, if necessary.
1968     if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
1969       if (AI.getPaddingInReg()) {
1970         ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1971             llvm::AttributeSet::get(
1972                 getLLVMContext(),
1973                 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg));
1974       }
1975     }
1976 
1977     // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1978     // have the corresponding parameter variable.  It doesn't make
1979     // sense to do it here because parameters are so messed up.
1980     switch (AI.getKind()) {
1981     case ABIArgInfo::Extend:
1982       if (ParamType->isSignedIntegerOrEnumerationType())
1983         Attrs.addAttribute(llvm::Attribute::SExt);
1984       else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1985         if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1986           Attrs.addAttribute(llvm::Attribute::SExt);
1987         else
1988           Attrs.addAttribute(llvm::Attribute::ZExt);
1989       }
1990       // FALL THROUGH
1991     case ABIArgInfo::Direct:
1992       if (ArgNo == 0 && FI.isChainCall())
1993         Attrs.addAttribute(llvm::Attribute::Nest);
1994       else if (AI.getInReg())
1995         Attrs.addAttribute(llvm::Attribute::InReg);
1996       break;
1997 
1998     case ABIArgInfo::Indirect: {
1999       if (AI.getInReg())
2000         Attrs.addAttribute(llvm::Attribute::InReg);
2001 
2002       if (AI.getIndirectByVal())
2003         Attrs.addAttribute(llvm::Attribute::ByVal);
2004 
2005       CharUnits Align = AI.getIndirectAlign();
2006 
2007       // In a byval argument, it is important that the required
2008       // alignment of the type is honored, as LLVM might be creating a
2009       // *new* stack object, and needs to know what alignment to give
2010       // it. (Sometimes it can deduce a sensible alignment on its own,
2011       // but not if clang decides it must emit a packed struct, or the
2012       // user specifies increased alignment requirements.)
2013       //
2014       // This is different from indirect *not* byval, where the object
2015       // exists already, and the align attribute is purely
2016       // informative.
2017       assert(!Align.isZero());
2018 
2019       // For now, only add this when we have a byval argument.
2020       // TODO: be less lazy about updating test cases.
2021       if (AI.getIndirectByVal())
2022         Attrs.addAlignmentAttr(Align.getQuantity());
2023 
2024       // byval disables readnone and readonly.
2025       FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2026         .removeAttribute(llvm::Attribute::ReadNone);
2027       break;
2028     }
2029     case ABIArgInfo::Ignore:
2030     case ABIArgInfo::Expand:
2031     case ABIArgInfo::CoerceAndExpand:
2032       break;
2033 
2034     case ABIArgInfo::InAlloca:
2035       // inalloca disables readnone and readonly.
2036       FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2037           .removeAttribute(llvm::Attribute::ReadNone);
2038       continue;
2039     }
2040 
2041     if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2042       QualType PTy = RefTy->getPointeeType();
2043       if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2044         Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
2045                                        .getQuantity());
2046       else if (getContext().getTargetAddressSpace(PTy) == 0)
2047         Attrs.addAttribute(llvm::Attribute::NonNull);
2048     }
2049 
2050     switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2051     case ParameterABI::Ordinary:
2052       break;
2053 
2054     case ParameterABI::SwiftIndirectResult: {
2055       // Add 'sret' if we haven't already used it for something, but
2056       // only if the result is void.
2057       if (!hasUsedSRet && RetTy->isVoidType()) {
2058         Attrs.addAttribute(llvm::Attribute::StructRet);
2059         hasUsedSRet = true;
2060       }
2061 
2062       // Add 'noalias' in either case.
2063       Attrs.addAttribute(llvm::Attribute::NoAlias);
2064 
2065       // Add 'dereferenceable' and 'alignment'.
2066       auto PTy = ParamType->getPointeeType();
2067       if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2068         auto info = getContext().getTypeInfoInChars(PTy);
2069         Attrs.addDereferenceableAttr(info.first.getQuantity());
2070         Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
2071                                                  info.second.getQuantity()));
2072       }
2073       break;
2074     }
2075 
2076     case ParameterABI::SwiftErrorResult:
2077       Attrs.addAttribute(llvm::Attribute::SwiftError);
2078       break;
2079 
2080     case ParameterABI::SwiftContext:
2081       Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2082       break;
2083     }
2084 
2085     if (Attrs.hasAttributes()) {
2086       unsigned FirstIRArg, NumIRArgs;
2087       std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2088       for (unsigned i = 0; i < NumIRArgs; i++)
2089         ArgAttrs[FirstIRArg + i] =
2090             llvm::AttributeSet::get(getLLVMContext(), Attrs);
2091     }
2092   }
2093   assert(ArgNo == FI.arg_size());
2094 
2095   AttrList = llvm::AttributeList::get(
2096       getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2097       llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2098 }
2099 
2100 /// An argument came in as a promoted argument; demote it back to its
2101 /// declared type.
2102 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2103                                          const VarDecl *var,
2104                                          llvm::Value *value) {
2105   llvm::Type *varType = CGF.ConvertType(var->getType());
2106 
2107   // This can happen with promotions that actually don't change the
2108   // underlying type, like the enum promotions.
2109   if (value->getType() == varType) return value;
2110 
2111   assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2112          && "unexpected promotion type");
2113 
2114   if (isa<llvm::IntegerType>(varType))
2115     return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2116 
2117   return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2118 }
2119 
2120 /// Returns the attribute (either parameter attribute, or function
2121 /// attribute), which declares argument ArgNo to be non-null.
2122 static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2123                                          QualType ArgType, unsigned ArgNo) {
2124   // FIXME: __attribute__((nonnull)) can also be applied to:
2125   //   - references to pointers, where the pointee is known to be
2126   //     nonnull (apparently a Clang extension)
2127   //   - transparent unions containing pointers
2128   // In the former case, LLVM IR cannot represent the constraint. In
2129   // the latter case, we have no guarantee that the transparent union
2130   // is in fact passed as a pointer.
2131   if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2132     return nullptr;
2133   // First, check attribute on parameter itself.
2134   if (PVD) {
2135     if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2136       return ParmNNAttr;
2137   }
2138   // Check function attributes.
2139   if (!FD)
2140     return nullptr;
2141   for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2142     if (NNAttr->isNonNull(ArgNo))
2143       return NNAttr;
2144   }
2145   return nullptr;
2146 }
2147 
2148 namespace {
2149   struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2150     Address Temp;
2151     Address Arg;
2152     CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2153     void Emit(CodeGenFunction &CGF, Flags flags) override {
2154       llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2155       CGF.Builder.CreateStore(errorValue, Arg);
2156     }
2157   };
2158 }
2159 
2160 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2161                                          llvm::Function *Fn,
2162                                          const FunctionArgList &Args) {
2163   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2164     // Naked functions don't have prologues.
2165     return;
2166 
2167   // If this is an implicit-return-zero function, go ahead and
2168   // initialize the return value.  TODO: it might be nice to have
2169   // a more general mechanism for this that didn't require synthesized
2170   // return statements.
2171   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2172     if (FD->hasImplicitReturnZero()) {
2173       QualType RetTy = FD->getReturnType().getUnqualifiedType();
2174       llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2175       llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2176       Builder.CreateStore(Zero, ReturnValue);
2177     }
2178   }
2179 
2180   // FIXME: We no longer need the types from FunctionArgList; lift up and
2181   // simplify.
2182 
2183   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2184   // Flattened function arguments.
2185   SmallVector<llvm::Value *, 16> FnArgs;
2186   FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2187   for (auto &Arg : Fn->args()) {
2188     FnArgs.push_back(&Arg);
2189   }
2190   assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
2191 
2192   // If we're using inalloca, all the memory arguments are GEPs off of the last
2193   // parameter, which is a pointer to the complete memory area.
2194   Address ArgStruct = Address::invalid();
2195   const llvm::StructLayout *ArgStructLayout = nullptr;
2196   if (IRFunctionArgs.hasInallocaArg()) {
2197     ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2198     ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2199                         FI.getArgStructAlignment());
2200 
2201     assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
2202   }
2203 
2204   // Name the struct return parameter.
2205   if (IRFunctionArgs.hasSRetArg()) {
2206     auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
2207     AI->setName("agg.result");
2208     AI->addAttr(llvm::Attribute::NoAlias);
2209   }
2210 
2211   // Track if we received the parameter as a pointer (indirect, byval, or
2212   // inalloca).  If already have a pointer, EmitParmDecl doesn't need to copy it
2213   // into a local alloca for us.
2214   SmallVector<ParamValue, 16> ArgVals;
2215   ArgVals.reserve(Args.size());
2216 
2217   // Create a pointer value for every parameter declaration.  This usually
2218   // entails copying one or more LLVM IR arguments into an alloca.  Don't push
2219   // any cleanups or do anything that might unwind.  We do that separately, so
2220   // we can push the cleanups in the correct order for the ABI.
2221   assert(FI.arg_size() == Args.size() &&
2222          "Mismatch between function signature & arguments.");
2223   unsigned ArgNo = 0;
2224   CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
2225   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
2226        i != e; ++i, ++info_it, ++ArgNo) {
2227     const VarDecl *Arg = *i;
2228     QualType Ty = info_it->type;
2229     const ABIArgInfo &ArgI = info_it->info;
2230 
2231     bool isPromoted =
2232       isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2233 
2234     unsigned FirstIRArg, NumIRArgs;
2235     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2236 
2237     switch (ArgI.getKind()) {
2238     case ABIArgInfo::InAlloca: {
2239       assert(NumIRArgs == 0);
2240       auto FieldIndex = ArgI.getInAllocaFieldIndex();
2241       CharUnits FieldOffset =
2242         CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2243       Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2244                                           Arg->getName());
2245       ArgVals.push_back(ParamValue::forIndirect(V));
2246       break;
2247     }
2248 
2249     case ABIArgInfo::Indirect: {
2250       assert(NumIRArgs == 1);
2251       Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
2252 
2253       if (!hasScalarEvaluationKind(Ty)) {
2254         // Aggregates and complex variables are accessed by reference.  All we
2255         // need to do is realign the value, if requested.
2256         Address V = ParamAddr;
2257         if (ArgI.getIndirectRealign()) {
2258           Address AlignedTemp = CreateMemTemp(Ty, "coerce");
2259 
2260           // Copy from the incoming argument pointer to the temporary with the
2261           // appropriate alignment.
2262           //
2263           // FIXME: We should have a common utility for generating an aggregate
2264           // copy.
2265           CharUnits Size = getContext().getTypeSizeInChars(Ty);
2266           auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2267           Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2268           Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2269           Builder.CreateMemCpy(Dst, Src, SizeVal, false);
2270           V = AlignedTemp;
2271         }
2272         ArgVals.push_back(ParamValue::forIndirect(V));
2273       } else {
2274         // Load scalar value from indirect argument.
2275         llvm::Value *V =
2276           EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
2277 
2278         if (isPromoted)
2279           V = emitArgumentDemotion(*this, Arg, V);
2280         ArgVals.push_back(ParamValue::forDirect(V));
2281       }
2282       break;
2283     }
2284 
2285     case ABIArgInfo::Extend:
2286     case ABIArgInfo::Direct: {
2287 
2288       // If we have the trivial case, handle it with no muss and fuss.
2289       if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
2290           ArgI.getCoerceToType() == ConvertType(Ty) &&
2291           ArgI.getDirectOffset() == 0) {
2292         assert(NumIRArgs == 1);
2293         llvm::Value *V = FnArgs[FirstIRArg];
2294         auto AI = cast<llvm::Argument>(V);
2295 
2296         if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
2297           if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2298                              PVD->getFunctionScopeIndex()))
2299             AI->addAttr(llvm::Attribute::NonNull);
2300 
2301           QualType OTy = PVD->getOriginalType();
2302           if (const auto *ArrTy =
2303               getContext().getAsConstantArrayType(OTy)) {
2304             // A C99 array parameter declaration with the static keyword also
2305             // indicates dereferenceability, and if the size is constant we can
2306             // use the dereferenceable attribute (which requires the size in
2307             // bytes).
2308             if (ArrTy->getSizeModifier() == ArrayType::Static) {
2309               QualType ETy = ArrTy->getElementType();
2310               uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2311               if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2312                   ArrSize) {
2313                 llvm::AttrBuilder Attrs;
2314                 Attrs.addDereferenceableAttr(
2315                   getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2316                 AI->addAttrs(Attrs);
2317               } else if (getContext().getTargetAddressSpace(ETy) == 0) {
2318                 AI->addAttr(llvm::Attribute::NonNull);
2319               }
2320             }
2321           } else if (const auto *ArrTy =
2322                      getContext().getAsVariableArrayType(OTy)) {
2323             // For C99 VLAs with the static keyword, we don't know the size so
2324             // we can't use the dereferenceable attribute, but in addrspace(0)
2325             // we know that it must be nonnull.
2326             if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2327                 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
2328               AI->addAttr(llvm::Attribute::NonNull);
2329           }
2330 
2331           const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2332           if (!AVAttr)
2333             if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2334               AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2335           if (AVAttr) {
2336             llvm::Value *AlignmentValue =
2337               EmitScalarExpr(AVAttr->getAlignment());
2338             llvm::ConstantInt *AlignmentCI =
2339               cast<llvm::ConstantInt>(AlignmentValue);
2340             unsigned Alignment = std::min((unsigned)AlignmentCI->getZExtValue(),
2341                                           +llvm::Value::MaximumAlignment);
2342             AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
2343           }
2344         }
2345 
2346         if (Arg->getType().isRestrictQualified())
2347           AI->addAttr(llvm::Attribute::NoAlias);
2348 
2349         // LLVM expects swifterror parameters to be used in very restricted
2350         // ways.  Copy the value into a less-restricted temporary.
2351         if (FI.getExtParameterInfo(ArgNo).getABI()
2352               == ParameterABI::SwiftErrorResult) {
2353           QualType pointeeTy = Ty->getPointeeType();
2354           assert(pointeeTy->isPointerType());
2355           Address temp =
2356             CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2357           Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2358           llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2359           Builder.CreateStore(incomingErrorValue, temp);
2360           V = temp.getPointer();
2361 
2362           // Push a cleanup to copy the value back at the end of the function.
2363           // The convention does not guarantee that the value will be written
2364           // back if the function exits with an unwind exception.
2365           EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2366         }
2367 
2368         // Ensure the argument is the correct type.
2369         if (V->getType() != ArgI.getCoerceToType())
2370           V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2371 
2372         if (isPromoted)
2373           V = emitArgumentDemotion(*this, Arg, V);
2374 
2375         // Because of merging of function types from multiple decls it is
2376         // possible for the type of an argument to not match the corresponding
2377         // type in the function type. Since we are codegening the callee
2378         // in here, add a cast to the argument type.
2379         llvm::Type *LTy = ConvertType(Arg->getType());
2380         if (V->getType() != LTy)
2381           V = Builder.CreateBitCast(V, LTy);
2382 
2383         ArgVals.push_back(ParamValue::forDirect(V));
2384         break;
2385       }
2386 
2387       Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2388                                      Arg->getName());
2389 
2390       // Pointer to store into.
2391       Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
2392 
2393       // Fast-isel and the optimizer generally like scalar values better than
2394       // FCAs, so we flatten them if this is safe to do for this argument.
2395       llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
2396       if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2397           STy->getNumElements() > 1) {
2398         auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
2399         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
2400         llvm::Type *DstTy = Ptr.getElementType();
2401         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
2402 
2403         Address AddrToStoreInto = Address::invalid();
2404         if (SrcSize <= DstSize) {
2405           AddrToStoreInto =
2406             Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
2407         } else {
2408           AddrToStoreInto =
2409             CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
2410         }
2411 
2412         assert(STy->getNumElements() == NumIRArgs);
2413         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2414           auto AI = FnArgs[FirstIRArg + i];
2415           AI->setName(Arg->getName() + ".coerce" + Twine(i));
2416           auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2417           Address EltPtr =
2418             Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2419           Builder.CreateStore(AI, EltPtr);
2420         }
2421 
2422         if (SrcSize > DstSize) {
2423           Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2424         }
2425 
2426       } else {
2427         // Simple case, just do a coerced store of the argument into the alloca.
2428         assert(NumIRArgs == 1);
2429         auto AI = FnArgs[FirstIRArg];
2430         AI->setName(Arg->getName() + ".coerce");
2431         CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
2432       }
2433 
2434       // Match to what EmitParmDecl is expecting for this type.
2435       if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
2436         llvm::Value *V =
2437           EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
2438         if (isPromoted)
2439           V = emitArgumentDemotion(*this, Arg, V);
2440         ArgVals.push_back(ParamValue::forDirect(V));
2441       } else {
2442         ArgVals.push_back(ParamValue::forIndirect(Alloca));
2443       }
2444       break;
2445     }
2446 
2447     case ABIArgInfo::CoerceAndExpand: {
2448       // Reconstruct into a temporary.
2449       Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2450       ArgVals.push_back(ParamValue::forIndirect(alloca));
2451 
2452       auto coercionType = ArgI.getCoerceAndExpandType();
2453       alloca = Builder.CreateElementBitCast(alloca, coercionType);
2454       auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2455 
2456       unsigned argIndex = FirstIRArg;
2457       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2458         llvm::Type *eltType = coercionType->getElementType(i);
2459         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2460           continue;
2461 
2462         auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2463         auto elt = FnArgs[argIndex++];
2464         Builder.CreateStore(elt, eltAddr);
2465       }
2466       assert(argIndex == FirstIRArg + NumIRArgs);
2467       break;
2468     }
2469 
2470     case ABIArgInfo::Expand: {
2471       // If this structure was expanded into multiple arguments then
2472       // we need to create a temporary and reconstruct it from the
2473       // arguments.
2474       Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2475       LValue LV = MakeAddrLValue(Alloca, Ty);
2476       ArgVals.push_back(ParamValue::forIndirect(Alloca));
2477 
2478       auto FnArgIter = FnArgs.begin() + FirstIRArg;
2479       ExpandTypeFromArgs(Ty, LV, FnArgIter);
2480       assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2481       for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2482         auto AI = FnArgs[FirstIRArg + i];
2483         AI->setName(Arg->getName() + "." + Twine(i));
2484       }
2485       break;
2486     }
2487 
2488     case ABIArgInfo::Ignore:
2489       assert(NumIRArgs == 0);
2490       // Initialize the local variable appropriately.
2491       if (!hasScalarEvaluationKind(Ty)) {
2492         ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
2493       } else {
2494         llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
2495         ArgVals.push_back(ParamValue::forDirect(U));
2496       }
2497       break;
2498     }
2499   }
2500 
2501   if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2502     for (int I = Args.size() - 1; I >= 0; --I)
2503       EmitParmDecl(*Args[I], ArgVals[I], I + 1);
2504   } else {
2505     for (unsigned I = 0, E = Args.size(); I != E; ++I)
2506       EmitParmDecl(*Args[I], ArgVals[I], I + 1);
2507   }
2508 }
2509 
2510 static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2511   while (insn->use_empty()) {
2512     llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2513     if (!bitcast) return;
2514 
2515     // This is "safe" because we would have used a ConstantExpr otherwise.
2516     insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2517     bitcast->eraseFromParent();
2518   }
2519 }
2520 
2521 /// Try to emit a fused autorelease of a return result.
2522 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2523                                                     llvm::Value *result) {
2524   // We must be immediately followed the cast.
2525   llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
2526   if (BB->empty()) return nullptr;
2527   if (&BB->back() != result) return nullptr;
2528 
2529   llvm::Type *resultType = result->getType();
2530 
2531   // result is in a BasicBlock and is therefore an Instruction.
2532   llvm::Instruction *generator = cast<llvm::Instruction>(result);
2533 
2534   SmallVector<llvm::Instruction *, 4> InstsToKill;
2535 
2536   // Look for:
2537   //  %generator = bitcast %type1* %generator2 to %type2*
2538   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2539     // We would have emitted this as a constant if the operand weren't
2540     // an Instruction.
2541     generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2542 
2543     // Require the generator to be immediately followed by the cast.
2544     if (generator->getNextNode() != bitcast)
2545       return nullptr;
2546 
2547     InstsToKill.push_back(bitcast);
2548   }
2549 
2550   // Look for:
2551   //   %generator = call i8* @objc_retain(i8* %originalResult)
2552   // or
2553   //   %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2554   llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
2555   if (!call) return nullptr;
2556 
2557   bool doRetainAutorelease;
2558 
2559   if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
2560     doRetainAutorelease = true;
2561   } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
2562                                           .objc_retainAutoreleasedReturnValue) {
2563     doRetainAutorelease = false;
2564 
2565     // If we emitted an assembly marker for this call (and the
2566     // ARCEntrypoints field should have been set if so), go looking
2567     // for that call.  If we can't find it, we can't do this
2568     // optimization.  But it should always be the immediately previous
2569     // instruction, unless we needed bitcasts around the call.
2570     if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
2571       llvm::Instruction *prev = call->getPrevNode();
2572       assert(prev);
2573       if (isa<llvm::BitCastInst>(prev)) {
2574         prev = prev->getPrevNode();
2575         assert(prev);
2576       }
2577       assert(isa<llvm::CallInst>(prev));
2578       assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
2579                CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
2580       InstsToKill.push_back(prev);
2581     }
2582   } else {
2583     return nullptr;
2584   }
2585 
2586   result = call->getArgOperand(0);
2587   InstsToKill.push_back(call);
2588 
2589   // Keep killing bitcasts, for sanity.  Note that we no longer care
2590   // about precise ordering as long as there's exactly one use.
2591   while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2592     if (!bitcast->hasOneUse()) break;
2593     InstsToKill.push_back(bitcast);
2594     result = bitcast->getOperand(0);
2595   }
2596 
2597   // Delete all the unnecessary instructions, from latest to earliest.
2598   for (auto *I : InstsToKill)
2599     I->eraseFromParent();
2600 
2601   // Do the fused retain/autorelease if we were asked to.
2602   if (doRetainAutorelease)
2603     result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2604 
2605   // Cast back to the result type.
2606   return CGF.Builder.CreateBitCast(result, resultType);
2607 }
2608 
2609 /// If this is a +1 of the value of an immutable 'self', remove it.
2610 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2611                                           llvm::Value *result) {
2612   // This is only applicable to a method with an immutable 'self'.
2613   const ObjCMethodDecl *method =
2614     dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
2615   if (!method) return nullptr;
2616   const VarDecl *self = method->getSelfDecl();
2617   if (!self->getType().isConstQualified()) return nullptr;
2618 
2619   // Look for a retain call.
2620   llvm::CallInst *retainCall =
2621     dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2622   if (!retainCall ||
2623       retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
2624     return nullptr;
2625 
2626   // Look for an ordinary load of 'self'.
2627   llvm::Value *retainedValue = retainCall->getArgOperand(0);
2628   llvm::LoadInst *load =
2629     dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2630   if (!load || load->isAtomic() || load->isVolatile() ||
2631       load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
2632     return nullptr;
2633 
2634   // Okay!  Burn it all down.  This relies for correctness on the
2635   // assumption that the retain is emitted as part of the return and
2636   // that thereafter everything is used "linearly".
2637   llvm::Type *resultType = result->getType();
2638   eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2639   assert(retainCall->use_empty());
2640   retainCall->eraseFromParent();
2641   eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2642 
2643   return CGF.Builder.CreateBitCast(load, resultType);
2644 }
2645 
2646 /// Emit an ARC autorelease of the result of a function.
2647 ///
2648 /// \return the value to actually return from the function
2649 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2650                                             llvm::Value *result) {
2651   // If we're returning 'self', kill the initial retain.  This is a
2652   // heuristic attempt to "encourage correctness" in the really unfortunate
2653   // case where we have a return of self during a dealloc and we desperately
2654   // need to avoid the possible autorelease.
2655   if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2656     return self;
2657 
2658   // At -O0, try to emit a fused retain/autorelease.
2659   if (CGF.shouldUseFusedARCCalls())
2660     if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2661       return fused;
2662 
2663   return CGF.EmitARCAutoreleaseReturnValue(result);
2664 }
2665 
2666 /// Heuristically search for a dominating store to the return-value slot.
2667 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2668   // Check if a User is a store which pointerOperand is the ReturnValue.
2669   // We are looking for stores to the ReturnValue, not for stores of the
2670   // ReturnValue to some other location.
2671   auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2672     auto *SI = dyn_cast<llvm::StoreInst>(U);
2673     if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2674       return nullptr;
2675     // These aren't actually possible for non-coerced returns, and we
2676     // only care about non-coerced returns on this code path.
2677     assert(!SI->isAtomic() && !SI->isVolatile());
2678     return SI;
2679   };
2680   // If there are multiple uses of the return-value slot, just check
2681   // for something immediately preceding the IP.  Sometimes this can
2682   // happen with how we generate implicit-returns; it can also happen
2683   // with noreturn cleanups.
2684   if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
2685     llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2686     if (IP->empty()) return nullptr;
2687     llvm::Instruction *I = &IP->back();
2688 
2689     // Skip lifetime markers
2690     for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2691                                             IE = IP->rend();
2692          II != IE; ++II) {
2693       if (llvm::IntrinsicInst *Intrinsic =
2694               dyn_cast<llvm::IntrinsicInst>(&*II)) {
2695         if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2696           const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2697           ++II;
2698           if (II == IE)
2699             break;
2700           if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2701             continue;
2702         }
2703       }
2704       I = &*II;
2705       break;
2706     }
2707 
2708     return GetStoreIfValid(I);
2709   }
2710 
2711   llvm::StoreInst *store =
2712       GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
2713   if (!store) return nullptr;
2714 
2715   // Now do a first-and-dirty dominance check: just walk up the
2716   // single-predecessors chain from the current insertion point.
2717   llvm::BasicBlock *StoreBB = store->getParent();
2718   llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2719   while (IP != StoreBB) {
2720     if (!(IP = IP->getSinglePredecessor()))
2721       return nullptr;
2722   }
2723 
2724   // Okay, the store's basic block dominates the insertion point; we
2725   // can do our thing.
2726   return store;
2727 }
2728 
2729 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
2730                                          bool EmitRetDbgLoc,
2731                                          SourceLocation EndLoc) {
2732   if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2733     // Naked functions don't have epilogues.
2734     Builder.CreateUnreachable();
2735     return;
2736   }
2737 
2738   // Functions with no result always return void.
2739   if (!ReturnValue.isValid()) {
2740     Builder.CreateRetVoid();
2741     return;
2742   }
2743 
2744   llvm::DebugLoc RetDbgLoc;
2745   llvm::Value *RV = nullptr;
2746   QualType RetTy = FI.getReturnType();
2747   const ABIArgInfo &RetAI = FI.getReturnInfo();
2748 
2749   switch (RetAI.getKind()) {
2750   case ABIArgInfo::InAlloca:
2751     // Aggregrates get evaluated directly into the destination.  Sometimes we
2752     // need to return the sret value in a register, though.
2753     assert(hasAggregateEvaluationKind(RetTy));
2754     if (RetAI.getInAllocaSRet()) {
2755       llvm::Function::arg_iterator EI = CurFn->arg_end();
2756       --EI;
2757       llvm::Value *ArgStruct = &*EI;
2758       llvm::Value *SRet = Builder.CreateStructGEP(
2759           nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
2760       RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
2761     }
2762     break;
2763 
2764   case ABIArgInfo::Indirect: {
2765     auto AI = CurFn->arg_begin();
2766     if (RetAI.isSRetAfterThis())
2767       ++AI;
2768     switch (getEvaluationKind(RetTy)) {
2769     case TEK_Complex: {
2770       ComplexPairTy RT =
2771         EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
2772       EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
2773                          /*isInit*/ true);
2774       break;
2775     }
2776     case TEK_Aggregate:
2777       // Do nothing; aggregrates get evaluated directly into the destination.
2778       break;
2779     case TEK_Scalar:
2780       EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
2781                         MakeNaturalAlignAddrLValue(&*AI, RetTy),
2782                         /*isInit*/ true);
2783       break;
2784     }
2785     break;
2786   }
2787 
2788   case ABIArgInfo::Extend:
2789   case ABIArgInfo::Direct:
2790     if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2791         RetAI.getDirectOffset() == 0) {
2792       // The internal return value temp always will have pointer-to-return-type
2793       // type, just do a load.
2794 
2795       // If there is a dominating store to ReturnValue, we can elide
2796       // the load, zap the store, and usually zap the alloca.
2797       if (llvm::StoreInst *SI =
2798               findDominatingStoreToReturnValue(*this)) {
2799         // Reuse the debug location from the store unless there is
2800         // cleanup code to be emitted between the store and return
2801         // instruction.
2802         if (EmitRetDbgLoc && !AutoreleaseResult)
2803           RetDbgLoc = SI->getDebugLoc();
2804         // Get the stored value and nuke the now-dead store.
2805         RV = SI->getValueOperand();
2806         SI->eraseFromParent();
2807 
2808         // If that was the only use of the return value, nuke it as well now.
2809         auto returnValueInst = ReturnValue.getPointer();
2810         if (returnValueInst->use_empty()) {
2811           if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2812             alloca->eraseFromParent();
2813             ReturnValue = Address::invalid();
2814           }
2815         }
2816 
2817       // Otherwise, we have to do a simple load.
2818       } else {
2819         RV = Builder.CreateLoad(ReturnValue);
2820       }
2821     } else {
2822       // If the value is offset in memory, apply the offset now.
2823       Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
2824 
2825       RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
2826     }
2827 
2828     // In ARC, end functions that return a retainable type with a call
2829     // to objc_autoreleaseReturnValue.
2830     if (AutoreleaseResult) {
2831 #ifndef NDEBUG
2832       // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2833       // been stripped of the typedefs, so we cannot use RetTy here. Get the
2834       // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2835       // CurCodeDecl or BlockInfo.
2836       QualType RT;
2837 
2838       if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2839         RT = FD->getReturnType();
2840       else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2841         RT = MD->getReturnType();
2842       else if (isa<BlockDecl>(CurCodeDecl))
2843         RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2844       else
2845         llvm_unreachable("Unexpected function/method type");
2846 
2847       assert(getLangOpts().ObjCAutoRefCount &&
2848              !FI.isReturnsRetained() &&
2849              RT->isObjCRetainableType());
2850 #endif
2851       RV = emitAutoreleaseOfResult(*this, RV);
2852     }
2853 
2854     break;
2855 
2856   case ABIArgInfo::Ignore:
2857     break;
2858 
2859   case ABIArgInfo::CoerceAndExpand: {
2860     auto coercionType = RetAI.getCoerceAndExpandType();
2861     auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2862 
2863     // Load all of the coerced elements out into results.
2864     llvm::SmallVector<llvm::Value*, 4> results;
2865     Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2866     for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2867       auto coercedEltType = coercionType->getElementType(i);
2868       if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2869         continue;
2870 
2871       auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2872       auto elt = Builder.CreateLoad(eltAddr);
2873       results.push_back(elt);
2874     }
2875 
2876     // If we have one result, it's the single direct result type.
2877     if (results.size() == 1) {
2878       RV = results[0];
2879 
2880     // Otherwise, we need to make a first-class aggregate.
2881     } else {
2882       // Construct a return type that lacks padding elements.
2883       llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2884 
2885       RV = llvm::UndefValue::get(returnType);
2886       for (unsigned i = 0, e = results.size(); i != e; ++i) {
2887         RV = Builder.CreateInsertValue(RV, results[i], i);
2888       }
2889     }
2890     break;
2891   }
2892 
2893   case ABIArgInfo::Expand:
2894     llvm_unreachable("Invalid ABI kind for return argument");
2895   }
2896 
2897   llvm::Instruction *Ret;
2898   if (RV) {
2899     EmitReturnValueCheck(RV, EndLoc);
2900     Ret = Builder.CreateRet(RV);
2901   } else {
2902     Ret = Builder.CreateRetVoid();
2903   }
2904 
2905   if (RetDbgLoc)
2906     Ret->setDebugLoc(std::move(RetDbgLoc));
2907 }
2908 
2909 void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV,
2910                                            SourceLocation EndLoc) {
2911   // A current decl may not be available when emitting vtable thunks.
2912   if (!CurCodeDecl)
2913     return;
2914 
2915   ReturnsNonNullAttr *RetNNAttr = nullptr;
2916   if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
2917     RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
2918 
2919   if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
2920     return;
2921 
2922   // Prefer the returns_nonnull attribute if it's present.
2923   SourceLocation AttrLoc;
2924   SanitizerMask CheckKind;
2925   SanitizerHandler Handler;
2926   if (RetNNAttr) {
2927     assert(!requiresReturnValueNullabilityCheck() &&
2928            "Cannot check nullability and the nonnull attribute");
2929     AttrLoc = RetNNAttr->getLocation();
2930     CheckKind = SanitizerKind::ReturnsNonnullAttribute;
2931     Handler = SanitizerHandler::NonnullReturn;
2932   } else {
2933     if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
2934       if (auto *TSI = DD->getTypeSourceInfo())
2935         if (auto FTL = TSI->getTypeLoc().castAs<FunctionTypeLoc>())
2936           AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
2937     CheckKind = SanitizerKind::NullabilityReturn;
2938     Handler = SanitizerHandler::NullabilityReturn;
2939   }
2940 
2941   SanitizerScope SanScope(this);
2942 
2943   llvm::BasicBlock *Check = nullptr;
2944   llvm::BasicBlock *NoCheck = nullptr;
2945   if (requiresReturnValueNullabilityCheck()) {
2946     // Before doing the nullability check, make sure that the preconditions for
2947     // the check are met.
2948     Check = createBasicBlock("nullcheck");
2949     NoCheck = createBasicBlock("no.nullcheck");
2950     Builder.CreateCondBr(RetValNullabilityPrecondition, Check, NoCheck);
2951     EmitBlock(Check);
2952   }
2953 
2954   // Now do the null check. If the returns_nonnull attribute is present, this
2955   // is done unconditionally.
2956   llvm::Value *Cond = Builder.CreateIsNotNull(RV);
2957   llvm::Constant *StaticData[] = {
2958       EmitCheckSourceLocation(EndLoc), EmitCheckSourceLocation(AttrLoc),
2959   };
2960   EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
2961 
2962   if (requiresReturnValueNullabilityCheck())
2963     EmitBlock(NoCheck);
2964 }
2965 
2966 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2967   const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2968   return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2969 }
2970 
2971 static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2972                                           QualType Ty) {
2973   // FIXME: Generate IR in one pass, rather than going back and fixing up these
2974   // placeholders.
2975   llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2976   llvm::Type *IRPtrTy = IRTy->getPointerTo();
2977   llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
2978 
2979   // FIXME: When we generate this IR in one pass, we shouldn't need
2980   // this win32-specific alignment hack.
2981   CharUnits Align = CharUnits::fromQuantity(4);
2982   Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
2983 
2984   return AggValueSlot::forAddr(Address(Placeholder, Align),
2985                                Ty.getQualifiers(),
2986                                AggValueSlot::IsNotDestructed,
2987                                AggValueSlot::DoesNotNeedGCBarriers,
2988                                AggValueSlot::IsNotAliased);
2989 }
2990 
2991 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
2992                                           const VarDecl *param,
2993                                           SourceLocation loc) {
2994   // StartFunction converted the ABI-lowered parameter(s) into a
2995   // local alloca.  We need to turn that into an r-value suitable
2996   // for EmitCall.
2997   Address local = GetAddrOfLocalVar(param);
2998 
2999   QualType type = param->getType();
3000 
3001   assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
3002          "cannot emit delegate call arguments for inalloca arguments!");
3003 
3004   // GetAddrOfLocalVar returns a pointer-to-pointer for references,
3005   // but the argument needs to be the original pointer.
3006   if (type->isReferenceType()) {
3007     args.add(RValue::get(Builder.CreateLoad(local)), type);
3008 
3009   // In ARC, move out of consumed arguments so that the release cleanup
3010   // entered by StartFunction doesn't cause an over-release.  This isn't
3011   // optimal -O0 code generation, but it should get cleaned up when
3012   // optimization is enabled.  This also assumes that delegate calls are
3013   // performed exactly once for a set of arguments, but that should be safe.
3014   } else if (getLangOpts().ObjCAutoRefCount &&
3015              param->hasAttr<NSConsumedAttr>() &&
3016              type->isObjCRetainableType()) {
3017     llvm::Value *ptr = Builder.CreateLoad(local);
3018     auto null =
3019       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
3020     Builder.CreateStore(null, local);
3021     args.add(RValue::get(ptr), type);
3022 
3023   // For the most part, we just need to load the alloca, except that
3024   // aggregate r-values are actually pointers to temporaries.
3025   } else {
3026     args.add(convertTempToRValue(local, type, loc), type);
3027   }
3028 }
3029 
3030 static bool isProvablyNull(llvm::Value *addr) {
3031   return isa<llvm::ConstantPointerNull>(addr);
3032 }
3033 
3034 /// Emit the actual writing-back of a writeback.
3035 static void emitWriteback(CodeGenFunction &CGF,
3036                           const CallArgList::Writeback &writeback) {
3037   const LValue &srcLV = writeback.Source;
3038   Address srcAddr = srcLV.getAddress();
3039   assert(!isProvablyNull(srcAddr.getPointer()) &&
3040          "shouldn't have writeback for provably null argument");
3041 
3042   llvm::BasicBlock *contBB = nullptr;
3043 
3044   // If the argument wasn't provably non-null, we need to null check
3045   // before doing the store.
3046   bool provablyNonNull = llvm::isKnownNonNull(srcAddr.getPointer());
3047   if (!provablyNonNull) {
3048     llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
3049     contBB = CGF.createBasicBlock("icr.done");
3050 
3051     llvm::Value *isNull =
3052       CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3053     CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
3054     CGF.EmitBlock(writebackBB);
3055   }
3056 
3057   // Load the value to writeback.
3058   llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3059 
3060   // Cast it back, in case we're writing an id to a Foo* or something.
3061   value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3062                                     "icr.writeback-cast");
3063 
3064   // Perform the writeback.
3065 
3066   // If we have a "to use" value, it's something we need to emit a use
3067   // of.  This has to be carefully threaded in: if it's done after the
3068   // release it's potentially undefined behavior (and the optimizer
3069   // will ignore it), and if it happens before the retain then the
3070   // optimizer could move the release there.
3071   if (writeback.ToUse) {
3072     assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
3073 
3074     // Retain the new value.  No need to block-copy here:  the block's
3075     // being passed up the stack.
3076     value = CGF.EmitARCRetainNonBlock(value);
3077 
3078     // Emit the intrinsic use here.
3079     CGF.EmitARCIntrinsicUse(writeback.ToUse);
3080 
3081     // Load the old value (primitively).
3082     llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
3083 
3084     // Put the new value in place (primitively).
3085     CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3086 
3087     // Release the old value.
3088     CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3089 
3090   // Otherwise, we can just do a normal lvalue store.
3091   } else {
3092     CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3093   }
3094 
3095   // Jump to the continuation block.
3096   if (!provablyNonNull)
3097     CGF.EmitBlock(contBB);
3098 }
3099 
3100 static void emitWritebacks(CodeGenFunction &CGF,
3101                            const CallArgList &args) {
3102   for (const auto &I : args.writebacks())
3103     emitWriteback(CGF, I);
3104 }
3105 
3106 static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3107                                             const CallArgList &CallArgs) {
3108   assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
3109   ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3110     CallArgs.getCleanupsToDeactivate();
3111   // Iterate in reverse to increase the likelihood of popping the cleanup.
3112   for (const auto &I : llvm::reverse(Cleanups)) {
3113     CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3114     I.IsActiveIP->eraseFromParent();
3115   }
3116 }
3117 
3118 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3119   if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3120     if (uop->getOpcode() == UO_AddrOf)
3121       return uop->getSubExpr();
3122   return nullptr;
3123 }
3124 
3125 /// Emit an argument that's being passed call-by-writeback.  That is,
3126 /// we are passing the address of an __autoreleased temporary; it
3127 /// might be copy-initialized with the current value of the given
3128 /// address, but it will definitely be copied out of after the call.
3129 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3130                              const ObjCIndirectCopyRestoreExpr *CRE) {
3131   LValue srcLV;
3132 
3133   // Make an optimistic effort to emit the address as an l-value.
3134   // This can fail if the argument expression is more complicated.
3135   if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3136     srcLV = CGF.EmitLValue(lvExpr);
3137 
3138   // Otherwise, just emit it as a scalar.
3139   } else {
3140     Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
3141 
3142     QualType srcAddrType =
3143       CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3144     srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
3145   }
3146   Address srcAddr = srcLV.getAddress();
3147 
3148   // The dest and src types don't necessarily match in LLVM terms
3149   // because of the crazy ObjC compatibility rules.
3150 
3151   llvm::PointerType *destType =
3152     cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3153 
3154   // If the address is a constant null, just pass the appropriate null.
3155   if (isProvablyNull(srcAddr.getPointer())) {
3156     args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3157              CRE->getType());
3158     return;
3159   }
3160 
3161   // Create the temporary.
3162   Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3163                                       CGF.getPointerAlign(),
3164                                       "icr.temp");
3165   // Loading an l-value can introduce a cleanup if the l-value is __weak,
3166   // and that cleanup will be conditional if we can't prove that the l-value
3167   // isn't null, so we need to register a dominating point so that the cleanups
3168   // system will make valid IR.
3169   CodeGenFunction::ConditionalEvaluation condEval(CGF);
3170 
3171   // Zero-initialize it if we're not doing a copy-initialization.
3172   bool shouldCopy = CRE->shouldCopy();
3173   if (!shouldCopy) {
3174     llvm::Value *null =
3175       llvm::ConstantPointerNull::get(
3176         cast<llvm::PointerType>(destType->getElementType()));
3177     CGF.Builder.CreateStore(null, temp);
3178   }
3179 
3180   llvm::BasicBlock *contBB = nullptr;
3181   llvm::BasicBlock *originBB = nullptr;
3182 
3183   // If the address is *not* known to be non-null, we need to switch.
3184   llvm::Value *finalArgument;
3185 
3186   bool provablyNonNull = llvm::isKnownNonNull(srcAddr.getPointer());
3187   if (provablyNonNull) {
3188     finalArgument = temp.getPointer();
3189   } else {
3190     llvm::Value *isNull =
3191       CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3192 
3193     finalArgument = CGF.Builder.CreateSelect(isNull,
3194                                    llvm::ConstantPointerNull::get(destType),
3195                                              temp.getPointer(), "icr.argument");
3196 
3197     // If we need to copy, then the load has to be conditional, which
3198     // means we need control flow.
3199     if (shouldCopy) {
3200       originBB = CGF.Builder.GetInsertBlock();
3201       contBB = CGF.createBasicBlock("icr.cont");
3202       llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3203       CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3204       CGF.EmitBlock(copyBB);
3205       condEval.begin(CGF);
3206     }
3207   }
3208 
3209   llvm::Value *valueToUse = nullptr;
3210 
3211   // Perform a copy if necessary.
3212   if (shouldCopy) {
3213     RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
3214     assert(srcRV.isScalar());
3215 
3216     llvm::Value *src = srcRV.getScalarVal();
3217     src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3218                                     "icr.cast");
3219 
3220     // Use an ordinary store, not a store-to-lvalue.
3221     CGF.Builder.CreateStore(src, temp);
3222 
3223     // If optimization is enabled, and the value was held in a
3224     // __strong variable, we need to tell the optimizer that this
3225     // value has to stay alive until we're doing the store back.
3226     // This is because the temporary is effectively unretained,
3227     // and so otherwise we can violate the high-level semantics.
3228     if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3229         srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3230       valueToUse = src;
3231     }
3232   }
3233 
3234   // Finish the control flow if we needed it.
3235   if (shouldCopy && !provablyNonNull) {
3236     llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
3237     CGF.EmitBlock(contBB);
3238 
3239     // Make a phi for the value to intrinsically use.
3240     if (valueToUse) {
3241       llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3242                                                       "icr.to-use");
3243       phiToUse->addIncoming(valueToUse, copyBB);
3244       phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3245                             originBB);
3246       valueToUse = phiToUse;
3247     }
3248 
3249     condEval.end(CGF);
3250   }
3251 
3252   args.addWriteback(srcLV, temp, valueToUse);
3253   args.add(RValue::get(finalArgument), CRE->getType());
3254 }
3255 
3256 void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
3257   assert(!StackBase);
3258 
3259   // Save the stack.
3260   llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
3261   StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
3262 }
3263 
3264 void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3265   if (StackBase) {
3266     // Restore the stack after the call.
3267     llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
3268     CGF.Builder.CreateCall(F, StackBase);
3269   }
3270 }
3271 
3272 void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3273                                           SourceLocation ArgLoc,
3274                                           AbstractCallee AC,
3275                                           unsigned ParmNum) {
3276   if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
3277                          SanOpts.has(SanitizerKind::NullabilityArg)))
3278     return;
3279 
3280   // The param decl may be missing in a variadic function.
3281   auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
3282   unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3283 
3284   // Prefer the nonnull attribute if it's present.
3285   const NonNullAttr *NNAttr = nullptr;
3286   if (SanOpts.has(SanitizerKind::NonnullAttribute))
3287     NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
3288 
3289   bool CanCheckNullability = false;
3290   if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
3291     auto Nullability = PVD->getType()->getNullability(getContext());
3292     CanCheckNullability = Nullability &&
3293                           *Nullability == NullabilityKind::NonNull &&
3294                           PVD->getTypeSourceInfo();
3295   }
3296 
3297   if (!NNAttr && !CanCheckNullability)
3298     return;
3299 
3300   SourceLocation AttrLoc;
3301   SanitizerMask CheckKind;
3302   SanitizerHandler Handler;
3303   if (NNAttr) {
3304     AttrLoc = NNAttr->getLocation();
3305     CheckKind = SanitizerKind::NonnullAttribute;
3306     Handler = SanitizerHandler::NonnullArg;
3307   } else {
3308     AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
3309     CheckKind = SanitizerKind::NullabilityArg;
3310     Handler = SanitizerHandler::NullabilityArg;
3311   }
3312 
3313   SanitizerScope SanScope(this);
3314   assert(RV.isScalar());
3315   llvm::Value *V = RV.getScalarVal();
3316   llvm::Value *Cond =
3317       Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
3318   llvm::Constant *StaticData[] = {
3319       EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
3320       llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
3321   };
3322   EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
3323 }
3324 
3325 void CodeGenFunction::EmitCallArgs(
3326     CallArgList &Args, ArrayRef<QualType> ArgTypes,
3327     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3328     AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
3329   assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
3330 
3331   // We *have* to evaluate arguments from right to left in the MS C++ ABI,
3332   // because arguments are destroyed left to right in the callee. As a special
3333   // case, there are certain language constructs that require left-to-right
3334   // evaluation, and in those cases we consider the evaluation order requirement
3335   // to trump the "destruction order is reverse construction order" guarantee.
3336   bool LeftToRight =
3337       CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
3338           ? Order == EvaluationOrder::ForceLeftToRight
3339           : Order != EvaluationOrder::ForceRightToLeft;
3340 
3341   auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
3342                                          RValue EmittedArg) {
3343     if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
3344       return;
3345     auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3346     if (PS == nullptr)
3347       return;
3348 
3349     const auto &Context = getContext();
3350     auto SizeTy = Context.getSizeType();
3351     auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3352     assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
3353     llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
3354                                                      EmittedArg.getScalarVal());
3355     Args.add(RValue::get(V), SizeTy);
3356     // If we're emitting args in reverse, be sure to do so with
3357     // pass_object_size, as well.
3358     if (!LeftToRight)
3359       std::swap(Args.back(), *(&Args.back() - 1));
3360   };
3361 
3362   // Insert a stack save if we're going to need any inalloca args.
3363   bool HasInAllocaArgs = false;
3364   if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3365     for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3366          I != E && !HasInAllocaArgs; ++I)
3367       HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3368     if (HasInAllocaArgs) {
3369       assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3370       Args.allocateArgumentMemory(*this);
3371     }
3372   }
3373 
3374   // Evaluate each argument in the appropriate order.
3375   size_t CallArgsStart = Args.size();
3376   for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
3377     unsigned Idx = LeftToRight ? I : E - I - 1;
3378     CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
3379     unsigned InitialArgSize = Args.size();
3380     EmitCallArg(Args, *Arg, ArgTypes[Idx]);
3381     // In particular, we depend on it being the last arg in Args, and the
3382     // objectsize bits depend on there only being one arg if !LeftToRight.
3383     assert(InitialArgSize + 1 == Args.size() &&
3384            "The code below depends on only adding one arg per EmitCallArg");
3385     (void)InitialArgSize;
3386     RValue RVArg = Args.back().RV;
3387     EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
3388                         ParamsToSkip + Idx);
3389     // @llvm.objectsize should never have side-effects and shouldn't need
3390     // destruction/cleanups, so we can safely "emit" it after its arg,
3391     // regardless of right-to-leftness
3392     MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
3393   }
3394 
3395   if (!LeftToRight) {
3396     // Un-reverse the arguments we just evaluated so they match up with the LLVM
3397     // IR function.
3398     std::reverse(Args.begin() + CallArgsStart, Args.end());
3399   }
3400 }
3401 
3402 namespace {
3403 
3404 struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
3405   DestroyUnpassedArg(Address Addr, QualType Ty)
3406       : Addr(Addr), Ty(Ty) {}
3407 
3408   Address Addr;
3409   QualType Ty;
3410 
3411   void Emit(CodeGenFunction &CGF, Flags flags) override {
3412     const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3413     assert(!Dtor->isTrivial());
3414     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3415                               /*Delegating=*/false, Addr);
3416   }
3417 };
3418 
3419 struct DisableDebugLocationUpdates {
3420   CodeGenFunction &CGF;
3421   bool disabledDebugInfo;
3422   DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3423     if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3424       CGF.disableDebugInfo();
3425   }
3426   ~DisableDebugLocationUpdates() {
3427     if (disabledDebugInfo)
3428       CGF.enableDebugInfo();
3429   }
3430 };
3431 
3432 } // end anonymous namespace
3433 
3434 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3435                                   QualType type) {
3436   DisableDebugLocationUpdates Dis(*this, E);
3437   if (const ObjCIndirectCopyRestoreExpr *CRE
3438         = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
3439     assert(getLangOpts().ObjCAutoRefCount);
3440     assert(getContext().hasSameUnqualifiedType(E->getType(), type));
3441     return emitWritebackArg(*this, args, CRE);
3442   }
3443 
3444   assert(type->isReferenceType() == E->isGLValue() &&
3445          "reference binding to unmaterialized r-value!");
3446 
3447   if (E->isGLValue()) {
3448     assert(E->getObjectKind() == OK_Ordinary);
3449     return args.add(EmitReferenceBindingToExpr(E), type);
3450   }
3451 
3452   bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3453 
3454   // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3455   // However, we still have to push an EH-only cleanup in case we unwind before
3456   // we make it to the call.
3457   if (HasAggregateEvalKind &&
3458       CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3459     // If we're using inalloca, use the argument memory.  Otherwise, use a
3460     // temporary.
3461     AggValueSlot Slot;
3462     if (args.isUsingInAlloca())
3463       Slot = createPlaceholderSlot(*this, type);
3464     else
3465       Slot = CreateAggTemp(type, "agg.tmp");
3466 
3467     const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3468     bool DestroyedInCallee =
3469         RD && RD->hasNonTrivialDestructor() &&
3470         CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
3471     if (DestroyedInCallee)
3472       Slot.setExternallyDestructed();
3473 
3474     EmitAggExpr(E, Slot);
3475     RValue RV = Slot.asRValue();
3476     args.add(RV, type);
3477 
3478     if (DestroyedInCallee) {
3479       // Create a no-op GEP between the placeholder and the cleanup so we can
3480       // RAUW it successfully.  It also serves as a marker of the first
3481       // instruction where the cleanup is active.
3482       pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3483                                               type);
3484       // This unreachable is a temporary marker which will be removed later.
3485       llvm::Instruction *IsActive = Builder.CreateUnreachable();
3486       args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
3487     }
3488     return;
3489   }
3490 
3491   if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
3492       cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3493     LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3494     assert(L.isSimple());
3495     if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3496       args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3497     } else {
3498       // We can't represent a misaligned lvalue in the CallArgList, so copy
3499       // to an aligned temporary now.
3500       Address tmp = CreateMemTemp(type);
3501       EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
3502       args.add(RValue::getAggregate(tmp), type);
3503     }
3504     return;
3505   }
3506 
3507   args.add(EmitAnyExprToTemp(E), type);
3508 }
3509 
3510 QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3511   // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3512   // implicitly widens null pointer constants that are arguments to varargs
3513   // functions to pointer-sized ints.
3514   if (!getTarget().getTriple().isOSWindows())
3515     return Arg->getType();
3516 
3517   if (Arg->getType()->isIntegerType() &&
3518       getContext().getTypeSize(Arg->getType()) <
3519           getContext().getTargetInfo().getPointerWidth(0) &&
3520       Arg->isNullPointerConstant(getContext(),
3521                                  Expr::NPC_ValueDependentIsNotNull)) {
3522     return getContext().getIntPtrType();
3523   }
3524 
3525   return Arg->getType();
3526 }
3527 
3528 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3529 // optimizer it can aggressively ignore unwind edges.
3530 void
3531 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3532   if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3533       !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3534     Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3535                       CGM.getNoObjCARCExceptionsMetadata());
3536 }
3537 
3538 /// Emits a call to the given no-arguments nounwind runtime function.
3539 llvm::CallInst *
3540 CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3541                                          const llvm::Twine &name) {
3542   return EmitNounwindRuntimeCall(callee, None, name);
3543 }
3544 
3545 /// Emits a call to the given nounwind runtime function.
3546 llvm::CallInst *
3547 CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3548                                          ArrayRef<llvm::Value*> args,
3549                                          const llvm::Twine &name) {
3550   llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3551   call->setDoesNotThrow();
3552   return call;
3553 }
3554 
3555 /// Emits a simple call (never an invoke) to the given no-arguments
3556 /// runtime function.
3557 llvm::CallInst *
3558 CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3559                                  const llvm::Twine &name) {
3560   return EmitRuntimeCall(callee, None, name);
3561 }
3562 
3563 // Calls which may throw must have operand bundles indicating which funclet
3564 // they are nested within.
3565 static void
3566 getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
3567                      SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
3568   // There is no need for a funclet operand bundle if we aren't inside a
3569   // funclet.
3570   if (!CurrentFuncletPad)
3571     return;
3572 
3573   // Skip intrinsics which cannot throw.
3574   auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3575   if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3576     return;
3577 
3578   BundleList.emplace_back("funclet", CurrentFuncletPad);
3579 }
3580 
3581 /// Emits a simple call (never an invoke) to the given runtime function.
3582 llvm::CallInst *
3583 CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3584                                  ArrayRef<llvm::Value*> args,
3585                                  const llvm::Twine &name) {
3586   SmallVector<llvm::OperandBundleDef, 1> BundleList;
3587   getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3588 
3589   llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3590   call->setCallingConv(getRuntimeCC());
3591   return call;
3592 }
3593 
3594 /// Emits a call or invoke to the given noreturn runtime function.
3595 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3596                                                ArrayRef<llvm::Value*> args) {
3597   SmallVector<llvm::OperandBundleDef, 1> BundleList;
3598   getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3599 
3600   if (getInvokeDest()) {
3601     llvm::InvokeInst *invoke =
3602       Builder.CreateInvoke(callee,
3603                            getUnreachableBlock(),
3604                            getInvokeDest(),
3605                            args,
3606                            BundleList);
3607     invoke->setDoesNotReturn();
3608     invoke->setCallingConv(getRuntimeCC());
3609   } else {
3610     llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
3611     call->setDoesNotReturn();
3612     call->setCallingConv(getRuntimeCC());
3613     Builder.CreateUnreachable();
3614   }
3615 }
3616 
3617 /// Emits a call or invoke instruction to the given nullary runtime function.
3618 llvm::CallSite
3619 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3620                                          const Twine &name) {
3621   return EmitRuntimeCallOrInvoke(callee, None, name);
3622 }
3623 
3624 /// Emits a call or invoke instruction to the given runtime function.
3625 llvm::CallSite
3626 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3627                                          ArrayRef<llvm::Value*> args,
3628                                          const Twine &name) {
3629   llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3630   callSite.setCallingConv(getRuntimeCC());
3631   return callSite;
3632 }
3633 
3634 /// Emits a call or invoke instruction to the given function, depending
3635 /// on the current state of the EH stack.
3636 llvm::CallSite
3637 CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
3638                                   ArrayRef<llvm::Value *> Args,
3639                                   const Twine &Name) {
3640   llvm::BasicBlock *InvokeDest = getInvokeDest();
3641   SmallVector<llvm::OperandBundleDef, 1> BundleList;
3642   getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
3643 
3644   llvm::Instruction *Inst;
3645   if (!InvokeDest)
3646     Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
3647   else {
3648     llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
3649     Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3650                                 Name);
3651     EmitBlock(ContBB);
3652   }
3653 
3654   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3655   // optimizer it can aggressively ignore unwind edges.
3656   if (CGM.getLangOpts().ObjCAutoRefCount)
3657     AddObjCARCExceptionMetadata(Inst);
3658 
3659   return llvm::CallSite(Inst);
3660 }
3661 
3662 /// \brief Store a non-aggregate value to an address to initialize it.  For
3663 /// initialization, a non-atomic store will be used.
3664 static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3665                                         LValue Dst) {
3666   if (Src.isScalar())
3667     CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3668   else
3669     CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3670 }
3671 
3672 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3673                                                   llvm::Value *New) {
3674   DeferredReplacements.push_back(std::make_pair(Old, New));
3675 }
3676 
3677 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
3678                                  const CGCallee &Callee,
3679                                  ReturnValueSlot ReturnValue,
3680                                  const CallArgList &CallArgs,
3681                                  llvm::Instruction **callOrInvoke) {
3682   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
3683 
3684   assert(Callee.isOrdinary());
3685 
3686   // Handle struct-return functions by passing a pointer to the
3687   // location that we would like to return into.
3688   QualType RetTy = CallInfo.getReturnType();
3689   const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
3690 
3691   llvm::FunctionType *IRFuncTy = Callee.getFunctionType();
3692 
3693   // 1. Set up the arguments.
3694 
3695   // If we're using inalloca, insert the allocation after the stack save.
3696   // FIXME: Do this earlier rather than hacking it in here!
3697   Address ArgMemory = Address::invalid();
3698   const llvm::StructLayout *ArgMemoryLayout = nullptr;
3699   if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
3700     const llvm::DataLayout &DL = CGM.getDataLayout();
3701     ArgMemoryLayout = DL.getStructLayout(ArgStruct);
3702     llvm::Instruction *IP = CallArgs.getStackBase();
3703     llvm::AllocaInst *AI;
3704     if (IP) {
3705       IP = IP->getNextNode();
3706       AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
3707                                 "argmem", IP);
3708     } else {
3709       AI = CreateTempAlloca(ArgStruct, "argmem");
3710     }
3711     auto Align = CallInfo.getArgStructAlignment();
3712     AI->setAlignment(Align.getQuantity());
3713     AI->setUsedWithInAlloca(true);
3714     assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
3715     ArgMemory = Address(AI, Align);
3716   }
3717 
3718   // Helper function to drill into the inalloca allocation.
3719   auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3720     auto FieldOffset =
3721       CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3722     return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3723   };
3724 
3725   ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
3726   SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3727 
3728   // If the call returns a temporary with struct return, create a temporary
3729   // alloca to hold the result, unless one is given to us.
3730   Address SRetPtr = Address::invalid();
3731   size_t UnusedReturnSize = 0;
3732   if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
3733     if (!ReturnValue.isNull()) {
3734       SRetPtr = ReturnValue.getValue();
3735     } else {
3736       SRetPtr = CreateMemTemp(RetTy);
3737       if (HaveInsertPoint() && ReturnValue.isUnused()) {
3738         uint64_t size =
3739             CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
3740         if (EmitLifetimeStart(size, SRetPtr.getPointer()))
3741           UnusedReturnSize = size;
3742       }
3743     }
3744     if (IRFunctionArgs.hasSRetArg()) {
3745       IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
3746     } else if (RetAI.isInAlloca()) {
3747       Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3748       Builder.CreateStore(SRetPtr.getPointer(), Addr);
3749     }
3750   }
3751 
3752   Address swiftErrorTemp = Address::invalid();
3753   Address swiftErrorArg = Address::invalid();
3754 
3755   // Translate all of the arguments as necessary to match the IR lowering.
3756   assert(CallInfo.arg_size() == CallArgs.size() &&
3757          "Mismatch between function signature & arguments.");
3758   unsigned ArgNo = 0;
3759   CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
3760   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
3761        I != E; ++I, ++info_it, ++ArgNo) {
3762     const ABIArgInfo &ArgInfo = info_it->info;
3763     RValue RV = I->RV;
3764 
3765     // Insert a padding argument to ensure proper alignment.
3766     if (IRFunctionArgs.hasPaddingArg(ArgNo))
3767       IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3768           llvm::UndefValue::get(ArgInfo.getPaddingType());
3769 
3770     unsigned FirstIRArg, NumIRArgs;
3771     std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3772 
3773     switch (ArgInfo.getKind()) {
3774     case ABIArgInfo::InAlloca: {
3775       assert(NumIRArgs == 0);
3776       assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3777       if (RV.isAggregate()) {
3778         // Replace the placeholder with the appropriate argument slot GEP.
3779         llvm::Instruction *Placeholder =
3780             cast<llvm::Instruction>(RV.getAggregatePointer());
3781         CGBuilderTy::InsertPoint IP = Builder.saveIP();
3782         Builder.SetInsertPoint(Placeholder);
3783         Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3784         Builder.restoreIP(IP);
3785         deferPlaceholderReplacement(Placeholder, Addr.getPointer());
3786       } else {
3787         // Store the RValue into the argument struct.
3788         Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3789         unsigned AS = Addr.getType()->getPointerAddressSpace();
3790         llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3791         // There are some cases where a trivial bitcast is not avoidable.  The
3792         // definition of a type later in a translation unit may change it's type
3793         // from {}* to (%struct.foo*)*.
3794         if (Addr.getType() != MemType)
3795           Addr = Builder.CreateBitCast(Addr, MemType);
3796         LValue argLV = MakeAddrLValue(Addr, I->Ty);
3797         EmitInitStoreOfNonAggregate(*this, RV, argLV);
3798       }
3799       break;
3800     }
3801 
3802     case ABIArgInfo::Indirect: {
3803       assert(NumIRArgs == 1);
3804       if (RV.isScalar() || RV.isComplex()) {
3805         // Make a temporary alloca to pass the argument.
3806         Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3807         IRCallArgs[FirstIRArg] = Addr.getPointer();
3808 
3809         LValue argLV = MakeAddrLValue(Addr, I->Ty);
3810         EmitInitStoreOfNonAggregate(*this, RV, argLV);
3811       } else {
3812         // We want to avoid creating an unnecessary temporary+copy here;
3813         // however, we need one in three cases:
3814         // 1. If the argument is not byval, and we are required to copy the
3815         //    source.  (This case doesn't occur on any common architecture.)
3816         // 2. If the argument is byval, RV is not sufficiently aligned, and
3817         //    we cannot force it to be sufficiently aligned.
3818         // 3. If the argument is byval, but RV is located in an address space
3819         //    different than that of the argument (0).
3820         Address Addr = RV.getAggregateAddress();
3821         CharUnits Align = ArgInfo.getIndirectAlign();
3822         const llvm::DataLayout *TD = &CGM.getDataLayout();
3823         const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
3824         const unsigned ArgAddrSpace =
3825             (FirstIRArg < IRFuncTy->getNumParams()
3826                  ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3827                  : 0);
3828         if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
3829             (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3830              llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3831                                               Align.getQuantity(), *TD)
3832                < Align.getQuantity()) ||
3833             (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
3834           // Create an aligned temporary, and copy to it.
3835           Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3836           IRCallArgs[FirstIRArg] = AI.getPointer();
3837           EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
3838         } else {
3839           // Skip the extra memcpy call.
3840           IRCallArgs[FirstIRArg] = Addr.getPointer();
3841         }
3842       }
3843       break;
3844     }
3845 
3846     case ABIArgInfo::Ignore:
3847       assert(NumIRArgs == 0);
3848       break;
3849 
3850     case ABIArgInfo::Extend:
3851     case ABIArgInfo::Direct: {
3852       if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
3853           ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3854           ArgInfo.getDirectOffset() == 0) {
3855         assert(NumIRArgs == 1);
3856         llvm::Value *V;
3857         if (RV.isScalar())
3858           V = RV.getScalarVal();
3859         else
3860           V = Builder.CreateLoad(RV.getAggregateAddress());
3861 
3862         // Implement swifterror by copying into a new swifterror argument.
3863         // We'll write back in the normal path out of the call.
3864         if (CallInfo.getExtParameterInfo(ArgNo).getABI()
3865               == ParameterABI::SwiftErrorResult) {
3866           assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
3867 
3868           QualType pointeeTy = I->Ty->getPointeeType();
3869           swiftErrorArg =
3870             Address(V, getContext().getTypeAlignInChars(pointeeTy));
3871 
3872           swiftErrorTemp =
3873             CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3874           V = swiftErrorTemp.getPointer();
3875           cast<llvm::AllocaInst>(V)->setSwiftError(true);
3876 
3877           llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
3878           Builder.CreateStore(errorValue, swiftErrorTemp);
3879         }
3880 
3881         // We might have to widen integers, but we should never truncate.
3882         if (ArgInfo.getCoerceToType() != V->getType() &&
3883             V->getType()->isIntegerTy())
3884           V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3885 
3886         // If the argument doesn't match, perform a bitcast to coerce it.  This
3887         // can happen due to trivial type mismatches.
3888         if (FirstIRArg < IRFuncTy->getNumParams() &&
3889             V->getType() != IRFuncTy->getParamType(FirstIRArg))
3890           V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3891 
3892         IRCallArgs[FirstIRArg] = V;
3893         break;
3894       }
3895 
3896       // FIXME: Avoid the conversion through memory if possible.
3897       Address Src = Address::invalid();
3898       if (RV.isScalar() || RV.isComplex()) {
3899         Src = CreateMemTemp(I->Ty, "coerce");
3900         LValue SrcLV = MakeAddrLValue(Src, I->Ty);
3901         EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
3902       } else {
3903         Src = RV.getAggregateAddress();
3904       }
3905 
3906       // If the value is offset in memory, apply the offset now.
3907       Src = emitAddressAtOffset(*this, Src, ArgInfo);
3908 
3909       // Fast-isel and the optimizer generally like scalar values better than
3910       // FCAs, so we flatten them if this is safe to do for this argument.
3911       llvm::StructType *STy =
3912             dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
3913       if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
3914         llvm::Type *SrcTy = Src.getType()->getElementType();
3915         uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3916         uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3917 
3918         // If the source type is smaller than the destination type of the
3919         // coerce-to logic, copy the source value into a temp alloca the size
3920         // of the destination type to allow loading all of it. The bits past
3921         // the source value are left undef.
3922         if (SrcSize < DstSize) {
3923           Address TempAlloca
3924             = CreateTempAlloca(STy, Src.getAlignment(),
3925                                Src.getName() + ".coerce");
3926           Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3927           Src = TempAlloca;
3928         } else {
3929           Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
3930         }
3931 
3932         auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
3933         assert(NumIRArgs == STy->getNumElements());
3934         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3935           auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3936           Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3937           llvm::Value *LI = Builder.CreateLoad(EltPtr);
3938           IRCallArgs[FirstIRArg + i] = LI;
3939         }
3940       } else {
3941         // In the simple case, just pass the coerced loaded value.
3942         assert(NumIRArgs == 1);
3943         IRCallArgs[FirstIRArg] =
3944           CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
3945       }
3946 
3947       break;
3948     }
3949 
3950     case ABIArgInfo::CoerceAndExpand: {
3951       auto coercionType = ArgInfo.getCoerceAndExpandType();
3952       auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3953 
3954       llvm::Value *tempSize = nullptr;
3955       Address addr = Address::invalid();
3956       if (RV.isAggregate()) {
3957         addr = RV.getAggregateAddress();
3958       } else {
3959         assert(RV.isScalar()); // complex should always just be direct
3960 
3961         llvm::Type *scalarType = RV.getScalarVal()->getType();
3962         auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
3963         auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
3964 
3965         tempSize = llvm::ConstantInt::get(CGM.Int64Ty, scalarSize);
3966 
3967         // Materialize to a temporary.
3968         addr = CreateTempAlloca(RV.getScalarVal()->getType(),
3969                  CharUnits::fromQuantity(std::max(layout->getAlignment(),
3970                                                   scalarAlign)));
3971         EmitLifetimeStart(scalarSize, addr.getPointer());
3972 
3973         Builder.CreateStore(RV.getScalarVal(), addr);
3974       }
3975 
3976       addr = Builder.CreateElementBitCast(addr, coercionType);
3977 
3978       unsigned IRArgPos = FirstIRArg;
3979       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3980         llvm::Type *eltType = coercionType->getElementType(i);
3981         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3982         Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3983         llvm::Value *elt = Builder.CreateLoad(eltAddr);
3984         IRCallArgs[IRArgPos++] = elt;
3985       }
3986       assert(IRArgPos == FirstIRArg + NumIRArgs);
3987 
3988       if (tempSize) {
3989         EmitLifetimeEnd(tempSize, addr.getPointer());
3990       }
3991 
3992       break;
3993     }
3994 
3995     case ABIArgInfo::Expand:
3996       unsigned IRArgPos = FirstIRArg;
3997       ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3998       assert(IRArgPos == FirstIRArg + NumIRArgs);
3999       break;
4000     }
4001   }
4002 
4003   llvm::Value *CalleePtr = Callee.getFunctionPointer();
4004 
4005   // If we're using inalloca, set up that argument.
4006   if (ArgMemory.isValid()) {
4007     llvm::Value *Arg = ArgMemory.getPointer();
4008     if (CallInfo.isVariadic()) {
4009       // When passing non-POD arguments by value to variadic functions, we will
4010       // end up with a variadic prototype and an inalloca call site.  In such
4011       // cases, we can't do any parameter mismatch checks.  Give up and bitcast
4012       // the callee.
4013       unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
4014       auto FnTy = getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS);
4015       CalleePtr = Builder.CreateBitCast(CalleePtr, FnTy);
4016     } else {
4017       llvm::Type *LastParamTy =
4018           IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
4019       if (Arg->getType() != LastParamTy) {
4020 #ifndef NDEBUG
4021         // Assert that these structs have equivalent element types.
4022         llvm::StructType *FullTy = CallInfo.getArgStruct();
4023         llvm::StructType *DeclaredTy = cast<llvm::StructType>(
4024             cast<llvm::PointerType>(LastParamTy)->getElementType());
4025         assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
4026         for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
4027                                                 DE = DeclaredTy->element_end(),
4028                                                 FI = FullTy->element_begin();
4029              DI != DE; ++DI, ++FI)
4030           assert(*DI == *FI);
4031 #endif
4032         Arg = Builder.CreateBitCast(Arg, LastParamTy);
4033       }
4034     }
4035     assert(IRFunctionArgs.hasInallocaArg());
4036     IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
4037   }
4038 
4039   // 2. Prepare the function pointer.
4040 
4041   // If the callee is a bitcast of a non-variadic function to have a
4042   // variadic function pointer type, check to see if we can remove the
4043   // bitcast.  This comes up with unprototyped functions.
4044   //
4045   // This makes the IR nicer, but more importantly it ensures that we
4046   // can inline the function at -O0 if it is marked always_inline.
4047   auto simplifyVariadicCallee = [](llvm::Value *Ptr) -> llvm::Value* {
4048     llvm::FunctionType *CalleeFT =
4049       cast<llvm::FunctionType>(Ptr->getType()->getPointerElementType());
4050     if (!CalleeFT->isVarArg())
4051       return Ptr;
4052 
4053     llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr);
4054     if (!CE || CE->getOpcode() != llvm::Instruction::BitCast)
4055       return Ptr;
4056 
4057     llvm::Function *OrigFn = dyn_cast<llvm::Function>(CE->getOperand(0));
4058     if (!OrigFn)
4059       return Ptr;
4060 
4061     llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
4062 
4063     // If the original type is variadic, or if any of the component types
4064     // disagree, we cannot remove the cast.
4065     if (OrigFT->isVarArg() ||
4066         OrigFT->getNumParams() != CalleeFT->getNumParams() ||
4067         OrigFT->getReturnType() != CalleeFT->getReturnType())
4068       return Ptr;
4069 
4070     for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
4071       if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
4072         return Ptr;
4073 
4074     return OrigFn;
4075   };
4076   CalleePtr = simplifyVariadicCallee(CalleePtr);
4077 
4078   // 3. Perform the actual call.
4079 
4080   // Deactivate any cleanups that we're supposed to do immediately before
4081   // the call.
4082   if (!CallArgs.getCleanupsToDeactivate().empty())
4083     deactivateArgCleanupsBeforeCall(*this, CallArgs);
4084 
4085   // Assert that the arguments we computed match up.  The IR verifier
4086   // will catch this, but this is a common enough source of problems
4087   // during IRGen changes that it's way better for debugging to catch
4088   // it ourselves here.
4089 #ifndef NDEBUG
4090   assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
4091   for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
4092     // Inalloca argument can have different type.
4093     if (IRFunctionArgs.hasInallocaArg() &&
4094         i == IRFunctionArgs.getInallocaArgNo())
4095       continue;
4096     if (i < IRFuncTy->getNumParams())
4097       assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
4098   }
4099 #endif
4100 
4101   // Compute the calling convention and attributes.
4102   unsigned CallingConv;
4103   llvm::AttributeList Attrs;
4104   CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
4105                              Callee.getAbstractInfo(), Attrs, CallingConv,
4106                              /*AttrOnCallSite=*/true);
4107 
4108   // Apply some call-site-specific attributes.
4109   // TODO: work this into building the attribute set.
4110 
4111   // Apply always_inline to all calls within flatten functions.
4112   // FIXME: should this really take priority over __try, below?
4113   if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
4114       !(Callee.getAbstractInfo().getCalleeDecl() &&
4115         Callee.getAbstractInfo().getCalleeDecl()->hasAttr<NoInlineAttr>())) {
4116     Attrs =
4117         Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
4118                            llvm::Attribute::AlwaysInline);
4119   }
4120 
4121   // Disable inlining inside SEH __try blocks.
4122   if (isSEHTryScope()) {
4123     Attrs =
4124         Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
4125                            llvm::Attribute::NoInline);
4126   }
4127 
4128   // Decide whether to use a call or an invoke.
4129   bool CannotThrow;
4130   if (currentFunctionUsesSEHTry()) {
4131     // SEH cares about asynchronous exceptions, so everything can "throw."
4132     CannotThrow = false;
4133   } else if (isCleanupPadScope() &&
4134              EHPersonality::get(*this).isMSVCXXPersonality()) {
4135     // The MSVC++ personality will implicitly terminate the program if an
4136     // exception is thrown during a cleanup outside of a try/catch.
4137     // We don't need to model anything in IR to get this behavior.
4138     CannotThrow = true;
4139   } else {
4140     // Otherwise, nounwind call sites will never throw.
4141     CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex,
4142                                      llvm::Attribute::NoUnwind);
4143   }
4144   llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
4145 
4146   SmallVector<llvm::OperandBundleDef, 1> BundleList;
4147   getBundlesForFunclet(CalleePtr, CurrentFuncletPad, BundleList);
4148 
4149   // Emit the actual call/invoke instruction.
4150   llvm::CallSite CS;
4151   if (!InvokeDest) {
4152     CS = Builder.CreateCall(CalleePtr, IRCallArgs, BundleList);
4153   } else {
4154     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
4155     CS = Builder.CreateInvoke(CalleePtr, Cont, InvokeDest, IRCallArgs,
4156                               BundleList);
4157     EmitBlock(Cont);
4158   }
4159   llvm::Instruction *CI = CS.getInstruction();
4160   if (callOrInvoke)
4161     *callOrInvoke = CI;
4162 
4163   // Apply the attributes and calling convention.
4164   CS.setAttributes(Attrs);
4165   CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
4166 
4167   // Apply various metadata.
4168 
4169   if (!CI->getType()->isVoidTy())
4170     CI->setName("call");
4171 
4172   // Insert instrumentation or attach profile metadata at indirect call sites.
4173   // For more details, see the comment before the definition of
4174   // IPVK_IndirectCallTarget in InstrProfData.inc.
4175   if (!CS.getCalledFunction())
4176     PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
4177                      CI, CalleePtr);
4178 
4179   // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4180   // optimizer it can aggressively ignore unwind edges.
4181   if (CGM.getLangOpts().ObjCAutoRefCount)
4182     AddObjCARCExceptionMetadata(CI);
4183 
4184   // Suppress tail calls if requested.
4185   if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
4186     const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
4187     if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
4188       Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
4189   }
4190 
4191   // 4. Finish the call.
4192 
4193   // If the call doesn't return, finish the basic block and clear the
4194   // insertion point; this allows the rest of IRGen to discard
4195   // unreachable code.
4196   if (CS.doesNotReturn()) {
4197     if (UnusedReturnSize)
4198       EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
4199                       SRetPtr.getPointer());
4200 
4201     Builder.CreateUnreachable();
4202     Builder.ClearInsertionPoint();
4203 
4204     // FIXME: For now, emit a dummy basic block because expr emitters in
4205     // generally are not ready to handle emitting expressions at unreachable
4206     // points.
4207     EnsureInsertPoint();
4208 
4209     // Return a reasonable RValue.
4210     return GetUndefRValue(RetTy);
4211   }
4212 
4213   // Perform the swifterror writeback.
4214   if (swiftErrorTemp.isValid()) {
4215     llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
4216     Builder.CreateStore(errorResult, swiftErrorArg);
4217   }
4218 
4219   // Emit any call-associated writebacks immediately.  Arguably this
4220   // should happen after any return-value munging.
4221   if (CallArgs.hasWritebacks())
4222     emitWritebacks(*this, CallArgs);
4223 
4224   // The stack cleanup for inalloca arguments has to run out of the normal
4225   // lexical order, so deactivate it and run it manually here.
4226   CallArgs.freeArgumentMemory(*this);
4227 
4228   // Extract the return value.
4229   RValue Ret = [&] {
4230     switch (RetAI.getKind()) {
4231     case ABIArgInfo::CoerceAndExpand: {
4232       auto coercionType = RetAI.getCoerceAndExpandType();
4233       auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4234 
4235       Address addr = SRetPtr;
4236       addr = Builder.CreateElementBitCast(addr, coercionType);
4237 
4238       assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
4239       bool requiresExtract = isa<llvm::StructType>(CI->getType());
4240 
4241       unsigned unpaddedIndex = 0;
4242       for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4243         llvm::Type *eltType = coercionType->getElementType(i);
4244         if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4245         Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
4246         llvm::Value *elt = CI;
4247         if (requiresExtract)
4248           elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4249         else
4250           assert(unpaddedIndex == 0);
4251         Builder.CreateStore(elt, eltAddr);
4252       }
4253       // FALLTHROUGH
4254     }
4255 
4256     case ABIArgInfo::InAlloca:
4257     case ABIArgInfo::Indirect: {
4258       RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
4259       if (UnusedReturnSize)
4260         EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
4261                         SRetPtr.getPointer());
4262       return ret;
4263     }
4264 
4265     case ABIArgInfo::Ignore:
4266       // If we are ignoring an argument that had a result, make sure to
4267       // construct the appropriate return value for our caller.
4268       return GetUndefRValue(RetTy);
4269 
4270     case ABIArgInfo::Extend:
4271     case ABIArgInfo::Direct: {
4272       llvm::Type *RetIRTy = ConvertType(RetTy);
4273       if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4274         switch (getEvaluationKind(RetTy)) {
4275         case TEK_Complex: {
4276           llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4277           llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4278           return RValue::getComplex(std::make_pair(Real, Imag));
4279         }
4280         case TEK_Aggregate: {
4281           Address DestPtr = ReturnValue.getValue();
4282           bool DestIsVolatile = ReturnValue.isVolatile();
4283 
4284           if (!DestPtr.isValid()) {
4285             DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4286             DestIsVolatile = false;
4287           }
4288           BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
4289           return RValue::getAggregate(DestPtr);
4290         }
4291         case TEK_Scalar: {
4292           // If the argument doesn't match, perform a bitcast to coerce it.  This
4293           // can happen due to trivial type mismatches.
4294           llvm::Value *V = CI;
4295           if (V->getType() != RetIRTy)
4296             V = Builder.CreateBitCast(V, RetIRTy);
4297           return RValue::get(V);
4298         }
4299         }
4300         llvm_unreachable("bad evaluation kind");
4301       }
4302 
4303       Address DestPtr = ReturnValue.getValue();
4304       bool DestIsVolatile = ReturnValue.isVolatile();
4305 
4306       if (!DestPtr.isValid()) {
4307         DestPtr = CreateMemTemp(RetTy, "coerce");
4308         DestIsVolatile = false;
4309       }
4310 
4311       // If the value is offset in memory, apply the offset now.
4312       Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4313       CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
4314 
4315       return convertTempToRValue(DestPtr, RetTy, SourceLocation());
4316     }
4317 
4318     case ABIArgInfo::Expand:
4319       llvm_unreachable("Invalid ABI kind for return argument");
4320     }
4321 
4322     llvm_unreachable("Unhandled ABIArgInfo::Kind");
4323   } ();
4324 
4325   // Emit the assume_aligned check on the return value.
4326   const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
4327   if (Ret.isScalar() && TargetDecl) {
4328     if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4329       llvm::Value *OffsetValue = nullptr;
4330       if (const auto *Offset = AA->getOffset())
4331         OffsetValue = EmitScalarExpr(Offset);
4332 
4333       llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4334       llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
4335       EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
4336                               OffsetValue);
4337     } else if (const auto *AA = TargetDecl->getAttr<AllocAlignAttr>()) {
4338       llvm::Value *ParamVal =
4339           CallArgs[AA->getParamIndex() - 1].RV.getScalarVal();
4340       EmitAlignmentAssumption(Ret.getScalarVal(), ParamVal);
4341     }
4342   }
4343 
4344   return Ret;
4345 }
4346 
4347 /* VarArg handling */
4348 
4349 Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4350   VAListAddr = VE->isMicrosoftABI()
4351                  ? EmitMSVAListRef(VE->getSubExpr())
4352                  : EmitVAListRef(VE->getSubExpr());
4353   QualType Ty = VE->getType();
4354   if (VE->isMicrosoftABI())
4355     return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
4356   return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
4357 }
4358