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