xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/CallLowering.cpp (revision 3c4ba5f55438f7afd4f4b0b56f88f2bb505fd6a6)
1 //===-- lib/CodeGen/GlobalISel/CallLowering.cpp - Call lowering -----------===//
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 /// \file
10 /// This file implements some simple delegations needed for call lowering.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
15 #include "llvm/CodeGen/Analysis.h"
16 #include "llvm/CodeGen/CallingConvLower.h"
17 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
18 #include "llvm/CodeGen/GlobalISel/Utils.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineOperand.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/TargetLowering.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Target/TargetMachine.h"
27 
28 #define DEBUG_TYPE "call-lowering"
29 
30 using namespace llvm;
31 
32 void CallLowering::anchor() {}
33 
34 /// Helper function which updates \p Flags when \p AttrFn returns true.
35 static void
36 addFlagsUsingAttrFn(ISD::ArgFlagsTy &Flags,
37                     const std::function<bool(Attribute::AttrKind)> &AttrFn) {
38   if (AttrFn(Attribute::SExt))
39     Flags.setSExt();
40   if (AttrFn(Attribute::ZExt))
41     Flags.setZExt();
42   if (AttrFn(Attribute::InReg))
43     Flags.setInReg();
44   if (AttrFn(Attribute::StructRet))
45     Flags.setSRet();
46   if (AttrFn(Attribute::Nest))
47     Flags.setNest();
48   if (AttrFn(Attribute::ByVal))
49     Flags.setByVal();
50   if (AttrFn(Attribute::Preallocated))
51     Flags.setPreallocated();
52   if (AttrFn(Attribute::InAlloca))
53     Flags.setInAlloca();
54   if (AttrFn(Attribute::Returned))
55     Flags.setReturned();
56   if (AttrFn(Attribute::SwiftSelf))
57     Flags.setSwiftSelf();
58   if (AttrFn(Attribute::SwiftAsync))
59     Flags.setSwiftAsync();
60   if (AttrFn(Attribute::SwiftError))
61     Flags.setSwiftError();
62 }
63 
64 ISD::ArgFlagsTy CallLowering::getAttributesForArgIdx(const CallBase &Call,
65                                                      unsigned ArgIdx) const {
66   ISD::ArgFlagsTy Flags;
67   addFlagsUsingAttrFn(Flags, [&Call, &ArgIdx](Attribute::AttrKind Attr) {
68     return Call.paramHasAttr(ArgIdx, Attr);
69   });
70   return Flags;
71 }
72 
73 void CallLowering::addArgFlagsFromAttributes(ISD::ArgFlagsTy &Flags,
74                                              const AttributeList &Attrs,
75                                              unsigned OpIdx) const {
76   addFlagsUsingAttrFn(Flags, [&Attrs, &OpIdx](Attribute::AttrKind Attr) {
77     return Attrs.hasAttributeAtIndex(OpIdx, Attr);
78   });
79 }
80 
81 bool CallLowering::lowerCall(MachineIRBuilder &MIRBuilder, const CallBase &CB,
82                              ArrayRef<Register> ResRegs,
83                              ArrayRef<ArrayRef<Register>> ArgRegs,
84                              Register SwiftErrorVReg,
85                              std::function<unsigned()> GetCalleeReg) const {
86   CallLoweringInfo Info;
87   const DataLayout &DL = MIRBuilder.getDataLayout();
88   MachineFunction &MF = MIRBuilder.getMF();
89   MachineRegisterInfo &MRI = MF.getRegInfo();
90   bool CanBeTailCalled = CB.isTailCall() &&
91                          isInTailCallPosition(CB, MF.getTarget()) &&
92                          (MF.getFunction()
93                               .getFnAttribute("disable-tail-calls")
94                               .getValueAsString() != "true");
95 
96   CallingConv::ID CallConv = CB.getCallingConv();
97   Type *RetTy = CB.getType();
98   bool IsVarArg = CB.getFunctionType()->isVarArg();
99 
100   SmallVector<BaseArgInfo, 4> SplitArgs;
101   getReturnInfo(CallConv, RetTy, CB.getAttributes(), SplitArgs, DL);
102   Info.CanLowerReturn = canLowerReturn(MF, CallConv, SplitArgs, IsVarArg);
103 
104   if (!Info.CanLowerReturn) {
105     // Callee requires sret demotion.
106     insertSRetOutgoingArgument(MIRBuilder, CB, Info);
107 
108     // The sret demotion isn't compatible with tail-calls, since the sret
109     // argument points into the caller's stack frame.
110     CanBeTailCalled = false;
111   }
112 
113 
114   // First step is to marshall all the function's parameters into the correct
115   // physregs and memory locations. Gather the sequence of argument types that
116   // we'll pass to the assigner function.
117   unsigned i = 0;
118   unsigned NumFixedArgs = CB.getFunctionType()->getNumParams();
119   for (const auto &Arg : CB.args()) {
120     ArgInfo OrigArg{ArgRegs[i], *Arg.get(), i, getAttributesForArgIdx(CB, i),
121                     i < NumFixedArgs};
122     setArgFlags(OrigArg, i + AttributeList::FirstArgIndex, DL, CB);
123 
124     // If we have an explicit sret argument that is an Instruction, (i.e., it
125     // might point to function-local memory), we can't meaningfully tail-call.
126     if (OrigArg.Flags[0].isSRet() && isa<Instruction>(&Arg))
127       CanBeTailCalled = false;
128 
129     Info.OrigArgs.push_back(OrigArg);
130     ++i;
131   }
132 
133   // Try looking through a bitcast from one function type to another.
134   // Commonly happens with calls to objc_msgSend().
135   const Value *CalleeV = CB.getCalledOperand()->stripPointerCasts();
136   if (const Function *F = dyn_cast<Function>(CalleeV))
137     Info.Callee = MachineOperand::CreateGA(F, 0);
138   else
139     Info.Callee = MachineOperand::CreateReg(GetCalleeReg(), false);
140 
141   Register ReturnHintAlignReg;
142   Align ReturnHintAlign;
143 
144   Info.OrigRet = ArgInfo{ResRegs, RetTy, 0, ISD::ArgFlagsTy{}};
145 
146   if (!Info.OrigRet.Ty->isVoidTy()) {
147     setArgFlags(Info.OrigRet, AttributeList::ReturnIndex, DL, CB);
148 
149     if (MaybeAlign Alignment = CB.getRetAlign()) {
150       if (*Alignment > Align(1)) {
151         ReturnHintAlignReg = MRI.cloneVirtualRegister(ResRegs[0]);
152         Info.OrigRet.Regs[0] = ReturnHintAlignReg;
153         ReturnHintAlign = *Alignment;
154       }
155     }
156   }
157 
158   Info.CB = &CB;
159   Info.KnownCallees = CB.getMetadata(LLVMContext::MD_callees);
160   Info.CallConv = CallConv;
161   Info.SwiftErrorVReg = SwiftErrorVReg;
162   Info.IsMustTailCall = CB.isMustTailCall();
163   Info.IsTailCall = CanBeTailCalled;
164   Info.IsVarArg = IsVarArg;
165   if (!lowerCall(MIRBuilder, Info))
166     return false;
167 
168   if (ReturnHintAlignReg && !Info.IsTailCall) {
169     MIRBuilder.buildAssertAlign(ResRegs[0], ReturnHintAlignReg,
170                                 ReturnHintAlign);
171   }
172 
173   return true;
174 }
175 
176 template <typename FuncInfoTy>
177 void CallLowering::setArgFlags(CallLowering::ArgInfo &Arg, unsigned OpIdx,
178                                const DataLayout &DL,
179                                const FuncInfoTy &FuncInfo) const {
180   auto &Flags = Arg.Flags[0];
181   const AttributeList &Attrs = FuncInfo.getAttributes();
182   addArgFlagsFromAttributes(Flags, Attrs, OpIdx);
183 
184   PointerType *PtrTy = dyn_cast<PointerType>(Arg.Ty->getScalarType());
185   if (PtrTy) {
186     Flags.setPointer();
187     Flags.setPointerAddrSpace(PtrTy->getPointerAddressSpace());
188   }
189 
190   Align MemAlign = DL.getABITypeAlign(Arg.Ty);
191   if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) {
192     assert(OpIdx >= AttributeList::FirstArgIndex);
193     unsigned ParamIdx = OpIdx - AttributeList::FirstArgIndex;
194 
195     Type *ElementTy = FuncInfo.getParamByValType(ParamIdx);
196     if (!ElementTy)
197       ElementTy = FuncInfo.getParamInAllocaType(ParamIdx);
198     if (!ElementTy)
199       ElementTy = FuncInfo.getParamPreallocatedType(ParamIdx);
200     assert(ElementTy && "Must have byval, inalloca or preallocated type");
201     Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
202 
203     // For ByVal, alignment should be passed from FE.  BE will guess if
204     // this info is not there but there are cases it cannot get right.
205     if (auto ParamAlign = FuncInfo.getParamStackAlign(ParamIdx))
206       MemAlign = *ParamAlign;
207     else if ((ParamAlign = FuncInfo.getParamAlign(ParamIdx)))
208       MemAlign = *ParamAlign;
209     else
210       MemAlign = Align(getTLI()->getByValTypeAlignment(ElementTy, DL));
211   } else if (OpIdx >= AttributeList::FirstArgIndex) {
212     if (auto ParamAlign =
213             FuncInfo.getParamStackAlign(OpIdx - AttributeList::FirstArgIndex))
214       MemAlign = *ParamAlign;
215   }
216   Flags.setMemAlign(MemAlign);
217   Flags.setOrigAlign(DL.getABITypeAlign(Arg.Ty));
218 
219   // Don't try to use the returned attribute if the argument is marked as
220   // swiftself, since it won't be passed in x0.
221   if (Flags.isSwiftSelf())
222     Flags.setReturned(false);
223 }
224 
225 template void
226 CallLowering::setArgFlags<Function>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
227                                     const DataLayout &DL,
228                                     const Function &FuncInfo) const;
229 
230 template void
231 CallLowering::setArgFlags<CallBase>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
232                                     const DataLayout &DL,
233                                     const CallBase &FuncInfo) const;
234 
235 void CallLowering::splitToValueTypes(const ArgInfo &OrigArg,
236                                      SmallVectorImpl<ArgInfo> &SplitArgs,
237                                      const DataLayout &DL,
238                                      CallingConv::ID CallConv,
239                                      SmallVectorImpl<uint64_t> *Offsets) const {
240   LLVMContext &Ctx = OrigArg.Ty->getContext();
241 
242   SmallVector<EVT, 4> SplitVTs;
243   ComputeValueVTs(*TLI, DL, OrigArg.Ty, SplitVTs, Offsets, 0);
244 
245   if (SplitVTs.size() == 0)
246     return;
247 
248   if (SplitVTs.size() == 1) {
249     // No splitting to do, but we want to replace the original type (e.g. [1 x
250     // double] -> double).
251     SplitArgs.emplace_back(OrigArg.Regs[0], SplitVTs[0].getTypeForEVT(Ctx),
252                            OrigArg.OrigArgIndex, OrigArg.Flags[0],
253                            OrigArg.IsFixed, OrigArg.OrigValue);
254     return;
255   }
256 
257   // Create one ArgInfo for each virtual register in the original ArgInfo.
258   assert(OrigArg.Regs.size() == SplitVTs.size() && "Regs / types mismatch");
259 
260   bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
261       OrigArg.Ty, CallConv, false, DL);
262   for (unsigned i = 0, e = SplitVTs.size(); i < e; ++i) {
263     Type *SplitTy = SplitVTs[i].getTypeForEVT(Ctx);
264     SplitArgs.emplace_back(OrigArg.Regs[i], SplitTy, OrigArg.OrigArgIndex,
265                            OrigArg.Flags[0], OrigArg.IsFixed);
266     if (NeedsRegBlock)
267       SplitArgs.back().Flags[0].setInConsecutiveRegs();
268   }
269 
270   SplitArgs.back().Flags[0].setInConsecutiveRegsLast();
271 }
272 
273 /// Pack values \p SrcRegs to cover the vector type result \p DstRegs.
274 static MachineInstrBuilder
275 mergeVectorRegsToResultRegs(MachineIRBuilder &B, ArrayRef<Register> DstRegs,
276                             ArrayRef<Register> SrcRegs) {
277   MachineRegisterInfo &MRI = *B.getMRI();
278   LLT LLTy = MRI.getType(DstRegs[0]);
279   LLT PartLLT = MRI.getType(SrcRegs[0]);
280 
281   // Deal with v3s16 split into v2s16
282   LLT LCMTy = getCoverTy(LLTy, PartLLT);
283   if (LCMTy == LLTy) {
284     // Common case where no padding is needed.
285     assert(DstRegs.size() == 1);
286     return B.buildConcatVectors(DstRegs[0], SrcRegs);
287   }
288 
289   // We need to create an unmerge to the result registers, which may require
290   // widening the original value.
291   Register UnmergeSrcReg;
292   if (LCMTy != PartLLT) {
293     assert(DstRegs.size() == 1);
294     return B.buildDeleteTrailingVectorElements(DstRegs[0],
295                                                B.buildMerge(LCMTy, SrcRegs));
296   } else {
297     // We don't need to widen anything if we're extracting a scalar which was
298     // promoted to a vector e.g. s8 -> v4s8 -> s8
299     assert(SrcRegs.size() == 1);
300     UnmergeSrcReg = SrcRegs[0];
301   }
302 
303   int NumDst = LCMTy.getSizeInBits() / LLTy.getSizeInBits();
304 
305   SmallVector<Register, 8> PadDstRegs(NumDst);
306   std::copy(DstRegs.begin(), DstRegs.end(), PadDstRegs.begin());
307 
308   // Create the excess dead defs for the unmerge.
309   for (int I = DstRegs.size(); I != NumDst; ++I)
310     PadDstRegs[I] = MRI.createGenericVirtualRegister(LLTy);
311 
312   if (PadDstRegs.size() == 1)
313     return B.buildDeleteTrailingVectorElements(DstRegs[0], UnmergeSrcReg);
314   return B.buildUnmerge(PadDstRegs, UnmergeSrcReg);
315 }
316 
317 /// Create a sequence of instructions to combine pieces split into register
318 /// typed values to the original IR value. \p OrigRegs contains the destination
319 /// value registers of type \p LLTy, and \p Regs contains the legalized pieces
320 /// with type \p PartLLT. This is used for incoming values (physregs to vregs).
321 static void buildCopyFromRegs(MachineIRBuilder &B, ArrayRef<Register> OrigRegs,
322                               ArrayRef<Register> Regs, LLT LLTy, LLT PartLLT,
323                               const ISD::ArgFlagsTy Flags) {
324   MachineRegisterInfo &MRI = *B.getMRI();
325 
326   if (PartLLT == LLTy) {
327     // We should have avoided introducing a new virtual register, and just
328     // directly assigned here.
329     assert(OrigRegs[0] == Regs[0]);
330     return;
331   }
332 
333   if (PartLLT.getSizeInBits() == LLTy.getSizeInBits() && OrigRegs.size() == 1 &&
334       Regs.size() == 1) {
335     B.buildBitcast(OrigRegs[0], Regs[0]);
336     return;
337   }
338 
339   // A vector PartLLT needs extending to LLTy's element size.
340   // E.g. <2 x s64> = G_SEXT <2 x s32>.
341   if (PartLLT.isVector() == LLTy.isVector() &&
342       PartLLT.getScalarSizeInBits() > LLTy.getScalarSizeInBits() &&
343       (!PartLLT.isVector() ||
344        PartLLT.getNumElements() == LLTy.getNumElements()) &&
345       OrigRegs.size() == 1 && Regs.size() == 1) {
346     Register SrcReg = Regs[0];
347 
348     LLT LocTy = MRI.getType(SrcReg);
349 
350     if (Flags.isSExt()) {
351       SrcReg = B.buildAssertSExt(LocTy, SrcReg, LLTy.getScalarSizeInBits())
352                    .getReg(0);
353     } else if (Flags.isZExt()) {
354       SrcReg = B.buildAssertZExt(LocTy, SrcReg, LLTy.getScalarSizeInBits())
355                    .getReg(0);
356     }
357 
358     // Sometimes pointers are passed zero extended.
359     LLT OrigTy = MRI.getType(OrigRegs[0]);
360     if (OrigTy.isPointer()) {
361       LLT IntPtrTy = LLT::scalar(OrigTy.getSizeInBits());
362       B.buildIntToPtr(OrigRegs[0], B.buildTrunc(IntPtrTy, SrcReg));
363       return;
364     }
365 
366     B.buildTrunc(OrigRegs[0], SrcReg);
367     return;
368   }
369 
370   if (!LLTy.isVector() && !PartLLT.isVector()) {
371     assert(OrigRegs.size() == 1);
372     LLT OrigTy = MRI.getType(OrigRegs[0]);
373 
374     unsigned SrcSize = PartLLT.getSizeInBits().getFixedSize() * Regs.size();
375     if (SrcSize == OrigTy.getSizeInBits())
376       B.buildMerge(OrigRegs[0], Regs);
377     else {
378       auto Widened = B.buildMerge(LLT::scalar(SrcSize), Regs);
379       B.buildTrunc(OrigRegs[0], Widened);
380     }
381 
382     return;
383   }
384 
385   if (PartLLT.isVector()) {
386     assert(OrigRegs.size() == 1);
387     SmallVector<Register> CastRegs(Regs.begin(), Regs.end());
388 
389     // If PartLLT is a mismatched vector in both number of elements and element
390     // size, e.g. PartLLT == v2s64 and LLTy is v3s32, then first coerce it to
391     // have the same elt type, i.e. v4s32.
392     if (PartLLT.getSizeInBits() > LLTy.getSizeInBits() &&
393         PartLLT.getScalarSizeInBits() == LLTy.getScalarSizeInBits() * 2 &&
394         Regs.size() == 1) {
395       LLT NewTy = PartLLT.changeElementType(LLTy.getElementType())
396                       .changeElementCount(PartLLT.getElementCount() * 2);
397       CastRegs[0] = B.buildBitcast(NewTy, Regs[0]).getReg(0);
398       PartLLT = NewTy;
399     }
400 
401     if (LLTy.getScalarType() == PartLLT.getElementType()) {
402       mergeVectorRegsToResultRegs(B, OrigRegs, CastRegs);
403     } else {
404       unsigned I = 0;
405       LLT GCDTy = getGCDType(LLTy, PartLLT);
406 
407       // We are both splitting a vector, and bitcasting its element types. Cast
408       // the source pieces into the appropriate number of pieces with the result
409       // element type.
410       for (Register SrcReg : CastRegs)
411         CastRegs[I++] = B.buildBitcast(GCDTy, SrcReg).getReg(0);
412       mergeVectorRegsToResultRegs(B, OrigRegs, CastRegs);
413     }
414 
415     return;
416   }
417 
418   assert(LLTy.isVector() && !PartLLT.isVector());
419 
420   LLT DstEltTy = LLTy.getElementType();
421 
422   // Pointer information was discarded. We'll need to coerce some register types
423   // to avoid violating type constraints.
424   LLT RealDstEltTy = MRI.getType(OrigRegs[0]).getElementType();
425 
426   assert(DstEltTy.getSizeInBits() == RealDstEltTy.getSizeInBits());
427 
428   if (DstEltTy == PartLLT) {
429     // Vector was trivially scalarized.
430 
431     if (RealDstEltTy.isPointer()) {
432       for (Register Reg : Regs)
433         MRI.setType(Reg, RealDstEltTy);
434     }
435 
436     B.buildBuildVector(OrigRegs[0], Regs);
437   } else if (DstEltTy.getSizeInBits() > PartLLT.getSizeInBits()) {
438     // Deal with vector with 64-bit elements decomposed to 32-bit
439     // registers. Need to create intermediate 64-bit elements.
440     SmallVector<Register, 8> EltMerges;
441     int PartsPerElt = DstEltTy.getSizeInBits() / PartLLT.getSizeInBits();
442 
443     assert(DstEltTy.getSizeInBits() % PartLLT.getSizeInBits() == 0);
444 
445     for (int I = 0, NumElts = LLTy.getNumElements(); I != NumElts; ++I) {
446       auto Merge = B.buildMerge(RealDstEltTy, Regs.take_front(PartsPerElt));
447       // Fix the type in case this is really a vector of pointers.
448       MRI.setType(Merge.getReg(0), RealDstEltTy);
449       EltMerges.push_back(Merge.getReg(0));
450       Regs = Regs.drop_front(PartsPerElt);
451     }
452 
453     B.buildBuildVector(OrigRegs[0], EltMerges);
454   } else {
455     // Vector was split, and elements promoted to a wider type.
456     // FIXME: Should handle floating point promotions.
457     LLT BVType = LLT::fixed_vector(LLTy.getNumElements(), PartLLT);
458     auto BV = B.buildBuildVector(BVType, Regs);
459     B.buildTrunc(OrigRegs[0], BV);
460   }
461 }
462 
463 /// Create a sequence of instructions to expand the value in \p SrcReg (of type
464 /// \p SrcTy) to the types in \p DstRegs (of type \p PartTy). \p ExtendOp should
465 /// contain the type of scalar value extension if necessary.
466 ///
467 /// This is used for outgoing values (vregs to physregs)
468 static void buildCopyToRegs(MachineIRBuilder &B, ArrayRef<Register> DstRegs,
469                             Register SrcReg, LLT SrcTy, LLT PartTy,
470                             unsigned ExtendOp = TargetOpcode::G_ANYEXT) {
471   // We could just insert a regular copy, but this is unreachable at the moment.
472   assert(SrcTy != PartTy && "identical part types shouldn't reach here");
473 
474   const unsigned PartSize = PartTy.getSizeInBits();
475 
476   if (PartTy.isVector() == SrcTy.isVector() &&
477       PartTy.getScalarSizeInBits() > SrcTy.getScalarSizeInBits()) {
478     assert(DstRegs.size() == 1);
479     B.buildInstr(ExtendOp, {DstRegs[0]}, {SrcReg});
480     return;
481   }
482 
483   if (SrcTy.isVector() && !PartTy.isVector() &&
484       PartSize > SrcTy.getElementType().getSizeInBits()) {
485     // Vector was scalarized, and the elements extended.
486     auto UnmergeToEltTy = B.buildUnmerge(SrcTy.getElementType(), SrcReg);
487     for (int i = 0, e = DstRegs.size(); i != e; ++i)
488       B.buildAnyExt(DstRegs[i], UnmergeToEltTy.getReg(i));
489     return;
490   }
491 
492   LLT GCDTy = getGCDType(SrcTy, PartTy);
493   if (GCDTy == PartTy) {
494     // If this already evenly divisible, we can create a simple unmerge.
495     B.buildUnmerge(DstRegs, SrcReg);
496     return;
497   }
498 
499   MachineRegisterInfo &MRI = *B.getMRI();
500   LLT DstTy = MRI.getType(DstRegs[0]);
501   LLT LCMTy = getCoverTy(SrcTy, PartTy);
502 
503   if (PartTy.isVector() && LCMTy == PartTy) {
504     assert(DstRegs.size() == 1);
505     B.buildPadVectorWithUndefElements(DstRegs[0], SrcReg);
506     return;
507   }
508 
509   const unsigned DstSize = DstTy.getSizeInBits();
510   const unsigned SrcSize = SrcTy.getSizeInBits();
511   unsigned CoveringSize = LCMTy.getSizeInBits();
512 
513   Register UnmergeSrc = SrcReg;
514 
515   if (!LCMTy.isVector() && CoveringSize != SrcSize) {
516     // For scalars, it's common to be able to use a simple extension.
517     if (SrcTy.isScalar() && DstTy.isScalar()) {
518       CoveringSize = alignTo(SrcSize, DstSize);
519       LLT CoverTy = LLT::scalar(CoveringSize);
520       UnmergeSrc = B.buildInstr(ExtendOp, {CoverTy}, {SrcReg}).getReg(0);
521     } else {
522       // Widen to the common type.
523       // FIXME: This should respect the extend type
524       Register Undef = B.buildUndef(SrcTy).getReg(0);
525       SmallVector<Register, 8> MergeParts(1, SrcReg);
526       for (unsigned Size = SrcSize; Size != CoveringSize; Size += SrcSize)
527         MergeParts.push_back(Undef);
528       UnmergeSrc = B.buildMerge(LCMTy, MergeParts).getReg(0);
529     }
530   }
531 
532   if (LCMTy.isVector() && CoveringSize != SrcSize)
533     UnmergeSrc = B.buildPadVectorWithUndefElements(LCMTy, SrcReg).getReg(0);
534 
535   B.buildUnmerge(DstRegs, UnmergeSrc);
536 }
537 
538 bool CallLowering::determineAndHandleAssignments(
539     ValueHandler &Handler, ValueAssigner &Assigner,
540     SmallVectorImpl<ArgInfo> &Args, MachineIRBuilder &MIRBuilder,
541     CallingConv::ID CallConv, bool IsVarArg,
542     ArrayRef<Register> ThisReturnRegs) const {
543   MachineFunction &MF = MIRBuilder.getMF();
544   const Function &F = MF.getFunction();
545   SmallVector<CCValAssign, 16> ArgLocs;
546 
547   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, F.getContext());
548   if (!determineAssignments(Assigner, Args, CCInfo))
549     return false;
550 
551   return handleAssignments(Handler, Args, CCInfo, ArgLocs, MIRBuilder,
552                            ThisReturnRegs);
553 }
554 
555 static unsigned extendOpFromFlags(llvm::ISD::ArgFlagsTy Flags) {
556   if (Flags.isSExt())
557     return TargetOpcode::G_SEXT;
558   if (Flags.isZExt())
559     return TargetOpcode::G_ZEXT;
560   return TargetOpcode::G_ANYEXT;
561 }
562 
563 bool CallLowering::determineAssignments(ValueAssigner &Assigner,
564                                         SmallVectorImpl<ArgInfo> &Args,
565                                         CCState &CCInfo) const {
566   LLVMContext &Ctx = CCInfo.getContext();
567   const CallingConv::ID CallConv = CCInfo.getCallingConv();
568 
569   unsigned NumArgs = Args.size();
570   for (unsigned i = 0; i != NumArgs; ++i) {
571     EVT CurVT = EVT::getEVT(Args[i].Ty);
572 
573     MVT NewVT = TLI->getRegisterTypeForCallingConv(Ctx, CallConv, CurVT);
574 
575     // If we need to split the type over multiple regs, check it's a scenario
576     // we currently support.
577     unsigned NumParts =
578         TLI->getNumRegistersForCallingConv(Ctx, CallConv, CurVT);
579 
580     if (NumParts == 1) {
581       // Try to use the register type if we couldn't assign the VT.
582       if (Assigner.assignArg(i, CurVT, NewVT, NewVT, CCValAssign::Full, Args[i],
583                              Args[i].Flags[0], CCInfo))
584         return false;
585       continue;
586     }
587 
588     // For incoming arguments (physregs to vregs), we could have values in
589     // physregs (or memlocs) which we want to extract and copy to vregs.
590     // During this, we might have to deal with the LLT being split across
591     // multiple regs, so we have to record this information for later.
592     //
593     // If we have outgoing args, then we have the opposite case. We have a
594     // vreg with an LLT which we want to assign to a physical location, and
595     // we might have to record that the value has to be split later.
596 
597     // We're handling an incoming arg which is split over multiple regs.
598     // E.g. passing an s128 on AArch64.
599     ISD::ArgFlagsTy OrigFlags = Args[i].Flags[0];
600     Args[i].Flags.clear();
601 
602     for (unsigned Part = 0; Part < NumParts; ++Part) {
603       ISD::ArgFlagsTy Flags = OrigFlags;
604       if (Part == 0) {
605         Flags.setSplit();
606       } else {
607         Flags.setOrigAlign(Align(1));
608         if (Part == NumParts - 1)
609           Flags.setSplitEnd();
610       }
611 
612       Args[i].Flags.push_back(Flags);
613       if (Assigner.assignArg(i, CurVT, NewVT, NewVT, CCValAssign::Full, Args[i],
614                              Args[i].Flags[Part], CCInfo)) {
615         // Still couldn't assign this smaller part type for some reason.
616         return false;
617       }
618     }
619   }
620 
621   return true;
622 }
623 
624 bool CallLowering::handleAssignments(ValueHandler &Handler,
625                                      SmallVectorImpl<ArgInfo> &Args,
626                                      CCState &CCInfo,
627                                      SmallVectorImpl<CCValAssign> &ArgLocs,
628                                      MachineIRBuilder &MIRBuilder,
629                                      ArrayRef<Register> ThisReturnRegs) const {
630   MachineFunction &MF = MIRBuilder.getMF();
631   MachineRegisterInfo &MRI = MF.getRegInfo();
632   const Function &F = MF.getFunction();
633   const DataLayout &DL = F.getParent()->getDataLayout();
634 
635   const unsigned NumArgs = Args.size();
636 
637   // Stores thunks for outgoing register assignments. This is used so we delay
638   // generating register copies until mem loc assignments are done. We do this
639   // so that if the target is using the delayed stack protector feature, we can
640   // find the split point of the block accurately. E.g. if we have:
641   // G_STORE %val, %memloc
642   // $x0 = COPY %foo
643   // $x1 = COPY %bar
644   // CALL func
645   // ... then the split point for the block will correctly be at, and including,
646   // the copy to $x0. If instead the G_STORE instruction immediately precedes
647   // the CALL, then we'd prematurely choose the CALL as the split point, thus
648   // generating a split block with a CALL that uses undefined physregs.
649   SmallVector<std::function<void()>> DelayedOutgoingRegAssignments;
650 
651   for (unsigned i = 0, j = 0; i != NumArgs; ++i, ++j) {
652     assert(j < ArgLocs.size() && "Skipped too many arg locs");
653     CCValAssign &VA = ArgLocs[j];
654     assert(VA.getValNo() == i && "Location doesn't correspond to current arg");
655 
656     if (VA.needsCustom()) {
657       std::function<void()> Thunk;
658       unsigned NumArgRegs = Handler.assignCustomValue(
659           Args[i], makeArrayRef(ArgLocs).slice(j), &Thunk);
660       if (Thunk)
661         DelayedOutgoingRegAssignments.emplace_back(Thunk);
662       if (!NumArgRegs)
663         return false;
664       j += NumArgRegs;
665       continue;
666     }
667 
668     const MVT ValVT = VA.getValVT();
669     const MVT LocVT = VA.getLocVT();
670 
671     const LLT LocTy(LocVT);
672     const LLT ValTy(ValVT);
673     const LLT NewLLT = Handler.isIncomingArgumentHandler() ? LocTy : ValTy;
674     const EVT OrigVT = EVT::getEVT(Args[i].Ty);
675     const LLT OrigTy = getLLTForType(*Args[i].Ty, DL);
676 
677     // Expected to be multiple regs for a single incoming arg.
678     // There should be Regs.size() ArgLocs per argument.
679     // This should be the same as getNumRegistersForCallingConv
680     const unsigned NumParts = Args[i].Flags.size();
681 
682     // Now split the registers into the assigned types.
683     Args[i].OrigRegs.assign(Args[i].Regs.begin(), Args[i].Regs.end());
684 
685     if (NumParts != 1 || NewLLT != OrigTy) {
686       // If we can't directly assign the register, we need one or more
687       // intermediate values.
688       Args[i].Regs.resize(NumParts);
689 
690       // For each split register, create and assign a vreg that will store
691       // the incoming component of the larger value. These will later be
692       // merged to form the final vreg.
693       for (unsigned Part = 0; Part < NumParts; ++Part)
694         Args[i].Regs[Part] = MRI.createGenericVirtualRegister(NewLLT);
695     }
696 
697     assert((j + (NumParts - 1)) < ArgLocs.size() &&
698            "Too many regs for number of args");
699 
700     // Coerce into outgoing value types before register assignment.
701     if (!Handler.isIncomingArgumentHandler() && OrigTy != ValTy) {
702       assert(Args[i].OrigRegs.size() == 1);
703       buildCopyToRegs(MIRBuilder, Args[i].Regs, Args[i].OrigRegs[0], OrigTy,
704                       ValTy, extendOpFromFlags(Args[i].Flags[0]));
705     }
706 
707     bool BigEndianPartOrdering = TLI->hasBigEndianPartOrdering(OrigVT, DL);
708     for (unsigned Part = 0; Part < NumParts; ++Part) {
709       Register ArgReg = Args[i].Regs[Part];
710       // There should be Regs.size() ArgLocs per argument.
711       unsigned Idx = BigEndianPartOrdering ? NumParts - 1 - Part : Part;
712       CCValAssign &VA = ArgLocs[j + Idx];
713       const ISD::ArgFlagsTy Flags = Args[i].Flags[Part];
714 
715       if (VA.isMemLoc() && !Flags.isByVal()) {
716         // Individual pieces may have been spilled to the stack and others
717         // passed in registers.
718 
719         // TODO: The memory size may be larger than the value we need to
720         // store. We may need to adjust the offset for big endian targets.
721         LLT MemTy = Handler.getStackValueStoreType(DL, VA, Flags);
722 
723         MachinePointerInfo MPO;
724         Register StackAddr = Handler.getStackAddress(
725             MemTy.getSizeInBytes(), VA.getLocMemOffset(), MPO, Flags);
726 
727         Handler.assignValueToAddress(Args[i], Part, StackAddr, MemTy, MPO, VA);
728         continue;
729       }
730 
731       if (VA.isMemLoc() && Flags.isByVal()) {
732         assert(Args[i].Regs.size() == 1 &&
733                "didn't expect split byval pointer");
734 
735         if (Handler.isIncomingArgumentHandler()) {
736           // We just need to copy the frame index value to the pointer.
737           MachinePointerInfo MPO;
738           Register StackAddr = Handler.getStackAddress(
739               Flags.getByValSize(), VA.getLocMemOffset(), MPO, Flags);
740           MIRBuilder.buildCopy(Args[i].Regs[0], StackAddr);
741         } else {
742           // For outgoing byval arguments, insert the implicit copy byval
743           // implies, such that writes in the callee do not modify the caller's
744           // value.
745           uint64_t MemSize = Flags.getByValSize();
746           int64_t Offset = VA.getLocMemOffset();
747 
748           MachinePointerInfo DstMPO;
749           Register StackAddr =
750               Handler.getStackAddress(MemSize, Offset, DstMPO, Flags);
751 
752           MachinePointerInfo SrcMPO(Args[i].OrigValue);
753           if (!Args[i].OrigValue) {
754             // We still need to accurately track the stack address space if we
755             // don't know the underlying value.
756             const LLT PtrTy = MRI.getType(StackAddr);
757             SrcMPO = MachinePointerInfo(PtrTy.getAddressSpace());
758           }
759 
760           Align DstAlign = std::max(Flags.getNonZeroByValAlign(),
761                                     inferAlignFromPtrInfo(MF, DstMPO));
762 
763           Align SrcAlign = std::max(Flags.getNonZeroByValAlign(),
764                                     inferAlignFromPtrInfo(MF, SrcMPO));
765 
766           Handler.copyArgumentMemory(Args[i], StackAddr, Args[i].Regs[0],
767                                      DstMPO, DstAlign, SrcMPO, SrcAlign,
768                                      MemSize, VA);
769         }
770         continue;
771       }
772 
773       assert(!VA.needsCustom() && "custom loc should have been handled already");
774 
775       if (i == 0 && !ThisReturnRegs.empty() &&
776           Handler.isIncomingArgumentHandler() &&
777           isTypeIsValidForThisReturn(ValVT)) {
778         Handler.assignValueToReg(ArgReg, ThisReturnRegs[Part], VA);
779         continue;
780       }
781 
782       if (Handler.isIncomingArgumentHandler())
783         Handler.assignValueToReg(ArgReg, VA.getLocReg(), VA);
784       else {
785         DelayedOutgoingRegAssignments.emplace_back([=, &Handler]() {
786           Handler.assignValueToReg(ArgReg, VA.getLocReg(), VA);
787         });
788       }
789     }
790 
791     // Now that all pieces have been assigned, re-pack the register typed values
792     // into the original value typed registers.
793     if (Handler.isIncomingArgumentHandler() && OrigVT != LocVT) {
794       // Merge the split registers into the expected larger result vregs of
795       // the original call.
796       buildCopyFromRegs(MIRBuilder, Args[i].OrigRegs, Args[i].Regs, OrigTy,
797                         LocTy, Args[i].Flags[0]);
798     }
799 
800     j += NumParts - 1;
801   }
802   for (auto &Fn : DelayedOutgoingRegAssignments)
803     Fn();
804 
805   return true;
806 }
807 
808 void CallLowering::insertSRetLoads(MachineIRBuilder &MIRBuilder, Type *RetTy,
809                                    ArrayRef<Register> VRegs, Register DemoteReg,
810                                    int FI) const {
811   MachineFunction &MF = MIRBuilder.getMF();
812   MachineRegisterInfo &MRI = MF.getRegInfo();
813   const DataLayout &DL = MF.getDataLayout();
814 
815   SmallVector<EVT, 4> SplitVTs;
816   SmallVector<uint64_t, 4> Offsets;
817   ComputeValueVTs(*TLI, DL, RetTy, SplitVTs, &Offsets, 0);
818 
819   assert(VRegs.size() == SplitVTs.size());
820 
821   unsigned NumValues = SplitVTs.size();
822   Align BaseAlign = DL.getPrefTypeAlign(RetTy);
823   Type *RetPtrTy = RetTy->getPointerTo(DL.getAllocaAddrSpace());
824   LLT OffsetLLTy = getLLTForType(*DL.getIntPtrType(RetPtrTy), DL);
825 
826   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
827 
828   for (unsigned I = 0; I < NumValues; ++I) {
829     Register Addr;
830     MIRBuilder.materializePtrAdd(Addr, DemoteReg, OffsetLLTy, Offsets[I]);
831     auto *MMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
832                                         MRI.getType(VRegs[I]),
833                                         commonAlignment(BaseAlign, Offsets[I]));
834     MIRBuilder.buildLoad(VRegs[I], Addr, *MMO);
835   }
836 }
837 
838 void CallLowering::insertSRetStores(MachineIRBuilder &MIRBuilder, Type *RetTy,
839                                     ArrayRef<Register> VRegs,
840                                     Register DemoteReg) const {
841   MachineFunction &MF = MIRBuilder.getMF();
842   MachineRegisterInfo &MRI = MF.getRegInfo();
843   const DataLayout &DL = MF.getDataLayout();
844 
845   SmallVector<EVT, 4> SplitVTs;
846   SmallVector<uint64_t, 4> Offsets;
847   ComputeValueVTs(*TLI, DL, RetTy, SplitVTs, &Offsets, 0);
848 
849   assert(VRegs.size() == SplitVTs.size());
850 
851   unsigned NumValues = SplitVTs.size();
852   Align BaseAlign = DL.getPrefTypeAlign(RetTy);
853   unsigned AS = DL.getAllocaAddrSpace();
854   LLT OffsetLLTy =
855       getLLTForType(*DL.getIntPtrType(RetTy->getPointerTo(AS)), DL);
856 
857   MachinePointerInfo PtrInfo(AS);
858 
859   for (unsigned I = 0; I < NumValues; ++I) {
860     Register Addr;
861     MIRBuilder.materializePtrAdd(Addr, DemoteReg, OffsetLLTy, Offsets[I]);
862     auto *MMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
863                                         MRI.getType(VRegs[I]),
864                                         commonAlignment(BaseAlign, Offsets[I]));
865     MIRBuilder.buildStore(VRegs[I], Addr, *MMO);
866   }
867 }
868 
869 void CallLowering::insertSRetIncomingArgument(
870     const Function &F, SmallVectorImpl<ArgInfo> &SplitArgs, Register &DemoteReg,
871     MachineRegisterInfo &MRI, const DataLayout &DL) const {
872   unsigned AS = DL.getAllocaAddrSpace();
873   DemoteReg = MRI.createGenericVirtualRegister(
874       LLT::pointer(AS, DL.getPointerSizeInBits(AS)));
875 
876   Type *PtrTy = PointerType::get(F.getReturnType(), AS);
877 
878   SmallVector<EVT, 1> ValueVTs;
879   ComputeValueVTs(*TLI, DL, PtrTy, ValueVTs);
880 
881   // NOTE: Assume that a pointer won't get split into more than one VT.
882   assert(ValueVTs.size() == 1);
883 
884   ArgInfo DemoteArg(DemoteReg, ValueVTs[0].getTypeForEVT(PtrTy->getContext()),
885                     ArgInfo::NoArgIndex);
886   setArgFlags(DemoteArg, AttributeList::ReturnIndex, DL, F);
887   DemoteArg.Flags[0].setSRet();
888   SplitArgs.insert(SplitArgs.begin(), DemoteArg);
889 }
890 
891 void CallLowering::insertSRetOutgoingArgument(MachineIRBuilder &MIRBuilder,
892                                               const CallBase &CB,
893                                               CallLoweringInfo &Info) const {
894   const DataLayout &DL = MIRBuilder.getDataLayout();
895   Type *RetTy = CB.getType();
896   unsigned AS = DL.getAllocaAddrSpace();
897   LLT FramePtrTy = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
898 
899   int FI = MIRBuilder.getMF().getFrameInfo().CreateStackObject(
900       DL.getTypeAllocSize(RetTy), DL.getPrefTypeAlign(RetTy), false);
901 
902   Register DemoteReg = MIRBuilder.buildFrameIndex(FramePtrTy, FI).getReg(0);
903   ArgInfo DemoteArg(DemoteReg, PointerType::get(RetTy, AS),
904                     ArgInfo::NoArgIndex);
905   setArgFlags(DemoteArg, AttributeList::ReturnIndex, DL, CB);
906   DemoteArg.Flags[0].setSRet();
907 
908   Info.OrigArgs.insert(Info.OrigArgs.begin(), DemoteArg);
909   Info.DemoteStackIndex = FI;
910   Info.DemoteRegister = DemoteReg;
911 }
912 
913 bool CallLowering::checkReturn(CCState &CCInfo,
914                                SmallVectorImpl<BaseArgInfo> &Outs,
915                                CCAssignFn *Fn) const {
916   for (unsigned I = 0, E = Outs.size(); I < E; ++I) {
917     MVT VT = MVT::getVT(Outs[I].Ty);
918     if (Fn(I, VT, VT, CCValAssign::Full, Outs[I].Flags[0], CCInfo))
919       return false;
920   }
921   return true;
922 }
923 
924 void CallLowering::getReturnInfo(CallingConv::ID CallConv, Type *RetTy,
925                                  AttributeList Attrs,
926                                  SmallVectorImpl<BaseArgInfo> &Outs,
927                                  const DataLayout &DL) const {
928   LLVMContext &Context = RetTy->getContext();
929   ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
930 
931   SmallVector<EVT, 4> SplitVTs;
932   ComputeValueVTs(*TLI, DL, RetTy, SplitVTs);
933   addArgFlagsFromAttributes(Flags, Attrs, AttributeList::ReturnIndex);
934 
935   for (EVT VT : SplitVTs) {
936     unsigned NumParts =
937         TLI->getNumRegistersForCallingConv(Context, CallConv, VT);
938     MVT RegVT = TLI->getRegisterTypeForCallingConv(Context, CallConv, VT);
939     Type *PartTy = EVT(RegVT).getTypeForEVT(Context);
940 
941     for (unsigned I = 0; I < NumParts; ++I) {
942       Outs.emplace_back(PartTy, Flags);
943     }
944   }
945 }
946 
947 bool CallLowering::checkReturnTypeForCallConv(MachineFunction &MF) const {
948   const auto &F = MF.getFunction();
949   Type *ReturnType = F.getReturnType();
950   CallingConv::ID CallConv = F.getCallingConv();
951 
952   SmallVector<BaseArgInfo, 4> SplitArgs;
953   getReturnInfo(CallConv, ReturnType, F.getAttributes(), SplitArgs,
954                 MF.getDataLayout());
955   return canLowerReturn(MF, CallConv, SplitArgs, F.isVarArg());
956 }
957 
958 bool CallLowering::parametersInCSRMatch(
959     const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask,
960     const SmallVectorImpl<CCValAssign> &OutLocs,
961     const SmallVectorImpl<ArgInfo> &OutArgs) const {
962   for (unsigned i = 0; i < OutLocs.size(); ++i) {
963     const auto &ArgLoc = OutLocs[i];
964     // If it's not a register, it's fine.
965     if (!ArgLoc.isRegLoc())
966       continue;
967 
968     MCRegister PhysReg = ArgLoc.getLocReg();
969 
970     // Only look at callee-saved registers.
971     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, PhysReg))
972       continue;
973 
974     LLVM_DEBUG(
975         dbgs()
976         << "... Call has an argument passed in a callee-saved register.\n");
977 
978     // Check if it was copied from.
979     const ArgInfo &OutInfo = OutArgs[i];
980 
981     if (OutInfo.Regs.size() > 1) {
982       LLVM_DEBUG(
983           dbgs() << "... Cannot handle arguments in multiple registers.\n");
984       return false;
985     }
986 
987     // Check if we copy the register, walking through copies from virtual
988     // registers. Note that getDefIgnoringCopies does not ignore copies from
989     // physical registers.
990     MachineInstr *RegDef = getDefIgnoringCopies(OutInfo.Regs[0], MRI);
991     if (!RegDef || RegDef->getOpcode() != TargetOpcode::COPY) {
992       LLVM_DEBUG(
993           dbgs()
994           << "... Parameter was not copied into a VReg, cannot tail call.\n");
995       return false;
996     }
997 
998     // Got a copy. Verify that it's the same as the register we want.
999     Register CopyRHS = RegDef->getOperand(1).getReg();
1000     if (CopyRHS != PhysReg) {
1001       LLVM_DEBUG(dbgs() << "... Callee-saved register was not copied into "
1002                            "VReg, cannot tail call.\n");
1003       return false;
1004     }
1005   }
1006 
1007   return true;
1008 }
1009 
1010 bool CallLowering::resultsCompatible(CallLoweringInfo &Info,
1011                                      MachineFunction &MF,
1012                                      SmallVectorImpl<ArgInfo> &InArgs,
1013                                      ValueAssigner &CalleeAssigner,
1014                                      ValueAssigner &CallerAssigner) const {
1015   const Function &F = MF.getFunction();
1016   CallingConv::ID CalleeCC = Info.CallConv;
1017   CallingConv::ID CallerCC = F.getCallingConv();
1018 
1019   if (CallerCC == CalleeCC)
1020     return true;
1021 
1022   SmallVector<CCValAssign, 16> ArgLocs1;
1023   CCState CCInfo1(CalleeCC, Info.IsVarArg, MF, ArgLocs1, F.getContext());
1024   if (!determineAssignments(CalleeAssigner, InArgs, CCInfo1))
1025     return false;
1026 
1027   SmallVector<CCValAssign, 16> ArgLocs2;
1028   CCState CCInfo2(CallerCC, F.isVarArg(), MF, ArgLocs2, F.getContext());
1029   if (!determineAssignments(CallerAssigner, InArgs, CCInfo2))
1030     return false;
1031 
1032   // We need the argument locations to match up exactly. If there's more in
1033   // one than the other, then we are done.
1034   if (ArgLocs1.size() != ArgLocs2.size())
1035     return false;
1036 
1037   // Make sure that each location is passed in exactly the same way.
1038   for (unsigned i = 0, e = ArgLocs1.size(); i < e; ++i) {
1039     const CCValAssign &Loc1 = ArgLocs1[i];
1040     const CCValAssign &Loc2 = ArgLocs2[i];
1041 
1042     // We need both of them to be the same. So if one is a register and one
1043     // isn't, we're done.
1044     if (Loc1.isRegLoc() != Loc2.isRegLoc())
1045       return false;
1046 
1047     if (Loc1.isRegLoc()) {
1048       // If they don't have the same register location, we're done.
1049       if (Loc1.getLocReg() != Loc2.getLocReg())
1050         return false;
1051 
1052       // They matched, so we can move to the next ArgLoc.
1053       continue;
1054     }
1055 
1056     // Loc1 wasn't a RegLoc, so they both must be MemLocs. Check if they match.
1057     if (Loc1.getLocMemOffset() != Loc2.getLocMemOffset())
1058       return false;
1059   }
1060 
1061   return true;
1062 }
1063 
1064 LLT CallLowering::ValueHandler::getStackValueStoreType(
1065     const DataLayout &DL, const CCValAssign &VA, ISD::ArgFlagsTy Flags) const {
1066   const MVT ValVT = VA.getValVT();
1067   if (ValVT != MVT::iPTR) {
1068     LLT ValTy(ValVT);
1069 
1070     // We lost the pointeriness going through CCValAssign, so try to restore it
1071     // based on the flags.
1072     if (Flags.isPointer()) {
1073       LLT PtrTy = LLT::pointer(Flags.getPointerAddrSpace(),
1074                                ValTy.getScalarSizeInBits());
1075       if (ValVT.isVector())
1076         return LLT::vector(ValTy.getElementCount(), PtrTy);
1077       return PtrTy;
1078     }
1079 
1080     return ValTy;
1081   }
1082 
1083   unsigned AddrSpace = Flags.getPointerAddrSpace();
1084   return LLT::pointer(AddrSpace, DL.getPointerSize(AddrSpace));
1085 }
1086 
1087 void CallLowering::ValueHandler::copyArgumentMemory(
1088     const ArgInfo &Arg, Register DstPtr, Register SrcPtr,
1089     const MachinePointerInfo &DstPtrInfo, Align DstAlign,
1090     const MachinePointerInfo &SrcPtrInfo, Align SrcAlign, uint64_t MemSize,
1091     CCValAssign &VA) const {
1092   MachineFunction &MF = MIRBuilder.getMF();
1093   MachineMemOperand *SrcMMO = MF.getMachineMemOperand(
1094       SrcPtrInfo,
1095       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable, MemSize,
1096       SrcAlign);
1097 
1098   MachineMemOperand *DstMMO = MF.getMachineMemOperand(
1099       DstPtrInfo,
1100       MachineMemOperand::MOStore | MachineMemOperand::MODereferenceable,
1101       MemSize, DstAlign);
1102 
1103   const LLT PtrTy = MRI.getType(DstPtr);
1104   const LLT SizeTy = LLT::scalar(PtrTy.getSizeInBits());
1105 
1106   auto SizeConst = MIRBuilder.buildConstant(SizeTy, MemSize);
1107   MIRBuilder.buildMemCpy(DstPtr, SrcPtr, SizeConst, *DstMMO, *SrcMMO);
1108 }
1109 
1110 Register CallLowering::ValueHandler::extendRegister(Register ValReg,
1111                                                     CCValAssign &VA,
1112                                                     unsigned MaxSizeBits) {
1113   LLT LocTy{VA.getLocVT()};
1114   LLT ValTy{VA.getValVT()};
1115 
1116   if (LocTy.getSizeInBits() == ValTy.getSizeInBits())
1117     return ValReg;
1118 
1119   if (LocTy.isScalar() && MaxSizeBits && MaxSizeBits < LocTy.getSizeInBits()) {
1120     if (MaxSizeBits <= ValTy.getSizeInBits())
1121       return ValReg;
1122     LocTy = LLT::scalar(MaxSizeBits);
1123   }
1124 
1125   const LLT ValRegTy = MRI.getType(ValReg);
1126   if (ValRegTy.isPointer()) {
1127     // The x32 ABI wants to zero extend 32-bit pointers to 64-bit registers, so
1128     // we have to cast to do the extension.
1129     LLT IntPtrTy = LLT::scalar(ValRegTy.getSizeInBits());
1130     ValReg = MIRBuilder.buildPtrToInt(IntPtrTy, ValReg).getReg(0);
1131   }
1132 
1133   switch (VA.getLocInfo()) {
1134   default: break;
1135   case CCValAssign::Full:
1136   case CCValAssign::BCvt:
1137     // FIXME: bitconverting between vector types may or may not be a
1138     // nop in big-endian situations.
1139     return ValReg;
1140   case CCValAssign::AExt: {
1141     auto MIB = MIRBuilder.buildAnyExt(LocTy, ValReg);
1142     return MIB.getReg(0);
1143   }
1144   case CCValAssign::SExt: {
1145     Register NewReg = MRI.createGenericVirtualRegister(LocTy);
1146     MIRBuilder.buildSExt(NewReg, ValReg);
1147     return NewReg;
1148   }
1149   case CCValAssign::ZExt: {
1150     Register NewReg = MRI.createGenericVirtualRegister(LocTy);
1151     MIRBuilder.buildZExt(NewReg, ValReg);
1152     return NewReg;
1153   }
1154   }
1155   llvm_unreachable("unable to extend register");
1156 }
1157 
1158 void CallLowering::ValueAssigner::anchor() {}
1159 
1160 Register CallLowering::IncomingValueHandler::buildExtensionHint(CCValAssign &VA,
1161                                                                 Register SrcReg,
1162                                                                 LLT NarrowTy) {
1163   switch (VA.getLocInfo()) {
1164   case CCValAssign::LocInfo::ZExt: {
1165     return MIRBuilder
1166         .buildAssertZExt(MRI.cloneVirtualRegister(SrcReg), SrcReg,
1167                          NarrowTy.getScalarSizeInBits())
1168         .getReg(0);
1169   }
1170   case CCValAssign::LocInfo::SExt: {
1171     return MIRBuilder
1172         .buildAssertSExt(MRI.cloneVirtualRegister(SrcReg), SrcReg,
1173                          NarrowTy.getScalarSizeInBits())
1174         .getReg(0);
1175     break;
1176   }
1177   default:
1178     return SrcReg;
1179   }
1180 }
1181 
1182 /// Check if we can use a basic COPY instruction between the two types.
1183 ///
1184 /// We're currently building on top of the infrastructure using MVT, which loses
1185 /// pointer information in the CCValAssign. We accept copies from physical
1186 /// registers that have been reported as integers if it's to an equivalent sized
1187 /// pointer LLT.
1188 static bool isCopyCompatibleType(LLT SrcTy, LLT DstTy) {
1189   if (SrcTy == DstTy)
1190     return true;
1191 
1192   if (SrcTy.getSizeInBits() != DstTy.getSizeInBits())
1193     return false;
1194 
1195   SrcTy = SrcTy.getScalarType();
1196   DstTy = DstTy.getScalarType();
1197 
1198   return (SrcTy.isPointer() && DstTy.isScalar()) ||
1199          (DstTy.isScalar() && SrcTy.isPointer());
1200 }
1201 
1202 void CallLowering::IncomingValueHandler::assignValueToReg(Register ValVReg,
1203                                                           Register PhysReg,
1204                                                           CCValAssign VA) {
1205   const MVT LocVT = VA.getLocVT();
1206   const LLT LocTy(LocVT);
1207   const LLT RegTy = MRI.getType(ValVReg);
1208 
1209   if (isCopyCompatibleType(RegTy, LocTy)) {
1210     MIRBuilder.buildCopy(ValVReg, PhysReg);
1211     return;
1212   }
1213 
1214   auto Copy = MIRBuilder.buildCopy(LocTy, PhysReg);
1215   auto Hint = buildExtensionHint(VA, Copy.getReg(0), RegTy);
1216   MIRBuilder.buildTrunc(ValVReg, Hint);
1217 }
1218