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