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