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