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