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