LLVM 19.0.0git
CallLowering.cpp
Go to the documentation of this file.
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
23#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/LLVMContext.h"
26#include "llvm/IR/Module.h"
28
29#define DEBUG_TYPE "call-lowering"
30
31using namespace llvm;
32
33void CallLowering::anchor() {}
34
35/// Helper function which updates \p Flags when \p AttrFn returns true.
36static void
38 const std::function<bool(Attribute::AttrKind)> &AttrFn) {
39 // TODO: There are missing flags. Add them here.
40 if (AttrFn(Attribute::SExt))
41 Flags.setSExt();
42 if (AttrFn(Attribute::ZExt))
43 Flags.setZExt();
44 if (AttrFn(Attribute::InReg))
45 Flags.setInReg();
46 if (AttrFn(Attribute::StructRet))
47 Flags.setSRet();
48 if (AttrFn(Attribute::Nest))
49 Flags.setNest();
50 if (AttrFn(Attribute::ByVal))
51 Flags.setByVal();
52 if (AttrFn(Attribute::ByRef))
53 Flags.setByRef();
54 if (AttrFn(Attribute::Preallocated))
55 Flags.setPreallocated();
56 if (AttrFn(Attribute::InAlloca))
57 Flags.setInAlloca();
58 if (AttrFn(Attribute::Returned))
59 Flags.setReturned();
60 if (AttrFn(Attribute::SwiftSelf))
61 Flags.setSwiftSelf();
62 if (AttrFn(Attribute::SwiftAsync))
63 Flags.setSwiftAsync();
64 if (AttrFn(Attribute::SwiftError))
65 Flags.setSwiftError();
66}
67
69 unsigned ArgIdx) const {
70 ISD::ArgFlagsTy Flags;
71 addFlagsUsingAttrFn(Flags, [&Call, &ArgIdx](Attribute::AttrKind Attr) {
72 return Call.paramHasAttr(ArgIdx, Attr);
73 });
74 return Flags;
75}
76
79 ISD::ArgFlagsTy Flags;
80 addFlagsUsingAttrFn(Flags, [&Call](Attribute::AttrKind Attr) {
81 return Call.hasRetAttr(Attr);
82 });
83 return Flags;
84}
85
87 const AttributeList &Attrs,
88 unsigned OpIdx) const {
89 addFlagsUsingAttrFn(Flags, [&Attrs, &OpIdx](Attribute::AttrKind Attr) {
90 return Attrs.hasAttributeAtIndex(OpIdx, Attr);
91 });
92}
93
95 ArrayRef<Register> ResRegs,
97 Register SwiftErrorVReg,
98 std::optional<PtrAuthInfo> PAI,
99 Register ConvergenceCtrlToken,
100 std::function<unsigned()> GetCalleeReg) const {
102 const DataLayout &DL = MIRBuilder.getDataLayout();
103 MachineFunction &MF = MIRBuilder.getMF();
105 bool CanBeTailCalled = CB.isTailCall() &&
107 (MF.getFunction()
108 .getFnAttribute("disable-tail-calls")
109 .getValueAsString() != "true");
110
111 CallingConv::ID CallConv = CB.getCallingConv();
112 Type *RetTy = CB.getType();
113 bool IsVarArg = CB.getFunctionType()->isVarArg();
114
116 getReturnInfo(CallConv, RetTy, CB.getAttributes(), SplitArgs, DL);
117 Info.CanLowerReturn = canLowerReturn(MF, CallConv, SplitArgs, IsVarArg);
118
119 Info.IsConvergent = CB.isConvergent();
120
121 if (!Info.CanLowerReturn) {
122 // Callee requires sret demotion.
123 insertSRetOutgoingArgument(MIRBuilder, CB, Info);
124
125 // The sret demotion isn't compatible with tail-calls, since the sret
126 // argument points into the caller's stack frame.
127 CanBeTailCalled = false;
128 }
129
130 // First step is to marshall all the function's parameters into the correct
131 // physregs and memory locations. Gather the sequence of argument types that
132 // we'll pass to the assigner function.
133 unsigned i = 0;
134 unsigned NumFixedArgs = CB.getFunctionType()->getNumParams();
135 for (const auto &Arg : CB.args()) {
136 ArgInfo OrigArg{ArgRegs[i], *Arg.get(), i, getAttributesForArgIdx(CB, i),
137 i < NumFixedArgs};
139
140 // If we have an explicit sret argument that is an Instruction, (i.e., it
141 // might point to function-local memory), we can't meaningfully tail-call.
142 if (OrigArg.Flags[0].isSRet() && isa<Instruction>(&Arg))
143 CanBeTailCalled = false;
144
145 Info.OrigArgs.push_back(OrigArg);
146 ++i;
147 }
148
149 // Try looking through a bitcast from one function type to another.
150 // Commonly happens with calls to objc_msgSend().
151 const Value *CalleeV = CB.getCalledOperand()->stripPointerCasts();
152 if (const Function *F = dyn_cast<Function>(CalleeV)) {
153 if (F->hasFnAttribute(Attribute::NonLazyBind)) {
154 LLT Ty = getLLTForType(*F->getType(), DL);
155 Register Reg = MIRBuilder.buildGlobalValue(Ty, F).getReg(0);
156 Info.Callee = MachineOperand::CreateReg(Reg, false);
157 } else {
158 Info.Callee = MachineOperand::CreateGA(F, 0);
159 }
160 } else if (isa<GlobalIFunc>(CalleeV) || isa<GlobalAlias>(CalleeV)) {
161 // IR IFuncs and Aliases can't be forward declared (only defined), so the
162 // callee must be in the same TU and therefore we can direct-call it without
163 // worrying about it being out of range.
164 Info.Callee = MachineOperand::CreateGA(cast<GlobalValue>(CalleeV), 0);
165 } else
166 Info.Callee = MachineOperand::CreateReg(GetCalleeReg(), false);
167
168 Register ReturnHintAlignReg;
169 Align ReturnHintAlign;
170
171 Info.OrigRet = ArgInfo{ResRegs, RetTy, 0, getAttributesForReturn(CB)};
172
173 if (!Info.OrigRet.Ty->isVoidTy()) {
175
176 if (MaybeAlign Alignment = CB.getRetAlign()) {
177 if (*Alignment > Align(1)) {
178 ReturnHintAlignReg = MRI.cloneVirtualRegister(ResRegs[0]);
179 Info.OrigRet.Regs[0] = ReturnHintAlignReg;
180 ReturnHintAlign = *Alignment;
181 }
182 }
183 }
184
185 auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi);
186 if (Bundle && CB.isIndirectCall()) {
187 Info.CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
188 assert(Info.CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
189 }
190
191 Info.CB = &CB;
192 Info.KnownCallees = CB.getMetadata(LLVMContext::MD_callees);
193 Info.CallConv = CallConv;
194 Info.SwiftErrorVReg = SwiftErrorVReg;
195 Info.PAI = PAI;
196 Info.ConvergenceCtrlToken = ConvergenceCtrlToken;
197 Info.IsMustTailCall = CB.isMustTailCall();
198 Info.IsTailCall = CanBeTailCalled;
199 Info.IsVarArg = IsVarArg;
200 if (!lowerCall(MIRBuilder, Info))
201 return false;
202
203 if (ReturnHintAlignReg && !Info.LoweredTailCall) {
204 MIRBuilder.buildAssertAlign(ResRegs[0], ReturnHintAlignReg,
205 ReturnHintAlign);
206 }
207
208 return true;
209}
210
211template <typename FuncInfoTy>
213 const DataLayout &DL,
214 const FuncInfoTy &FuncInfo) const {
215 auto &Flags = Arg.Flags[0];
216 const AttributeList &Attrs = FuncInfo.getAttributes();
217 addArgFlagsFromAttributes(Flags, Attrs, OpIdx);
218
219 PointerType *PtrTy = dyn_cast<PointerType>(Arg.Ty->getScalarType());
220 if (PtrTy) {
221 Flags.setPointer();
222 Flags.setPointerAddrSpace(PtrTy->getPointerAddressSpace());
223 }
224
225 Align MemAlign = DL.getABITypeAlign(Arg.Ty);
226 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
227 Flags.isByRef()) {
229 unsigned ParamIdx = OpIdx - AttributeList::FirstArgIndex;
230
231 Type *ElementTy = FuncInfo.getParamByValType(ParamIdx);
232 if (!ElementTy)
233 ElementTy = FuncInfo.getParamByRefType(ParamIdx);
234 if (!ElementTy)
235 ElementTy = FuncInfo.getParamInAllocaType(ParamIdx);
236 if (!ElementTy)
237 ElementTy = FuncInfo.getParamPreallocatedType(ParamIdx);
238
239 assert(ElementTy && "Must have byval, inalloca or preallocated type");
240
241 uint64_t MemSize = DL.getTypeAllocSize(ElementTy);
242 if (Flags.isByRef())
243 Flags.setByRefSize(MemSize);
244 else
245 Flags.setByValSize(MemSize);
246
247 // For ByVal, alignment should be passed from FE. BE will guess if
248 // this info is not there but there are cases it cannot get right.
249 if (auto ParamAlign = FuncInfo.getParamStackAlign(ParamIdx))
250 MemAlign = *ParamAlign;
251 else if ((ParamAlign = FuncInfo.getParamAlign(ParamIdx)))
252 MemAlign = *ParamAlign;
253 else
254 MemAlign = Align(getTLI()->getByValTypeAlignment(ElementTy, DL));
255 } else if (OpIdx >= AttributeList::FirstArgIndex) {
256 if (auto ParamAlign =
257 FuncInfo.getParamStackAlign(OpIdx - AttributeList::FirstArgIndex))
258 MemAlign = *ParamAlign;
259 }
260 Flags.setMemAlign(MemAlign);
261 Flags.setOrigAlign(DL.getABITypeAlign(Arg.Ty));
262
263 // Don't try to use the returned attribute if the argument is marked as
264 // swiftself, since it won't be passed in x0.
265 if (Flags.isSwiftSelf())
266 Flags.setReturned(false);
267}
268
269template void
270CallLowering::setArgFlags<Function>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
271 const DataLayout &DL,
272 const Function &FuncInfo) const;
273
274template void
275CallLowering::setArgFlags<CallBase>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
276 const DataLayout &DL,
277 const CallBase &FuncInfo) const;
278
280 SmallVectorImpl<ArgInfo> &SplitArgs,
281 const DataLayout &DL,
282 CallingConv::ID CallConv,
283 SmallVectorImpl<uint64_t> *Offsets) const {
284 LLVMContext &Ctx = OrigArg.Ty->getContext();
285
286 SmallVector<EVT, 4> SplitVTs;
287 ComputeValueVTs(*TLI, DL, OrigArg.Ty, SplitVTs, Offsets, 0);
288
289 if (SplitVTs.size() == 0)
290 return;
291
292 if (SplitVTs.size() == 1) {
293 // No splitting to do, but we want to replace the original type (e.g. [1 x
294 // double] -> double).
295 SplitArgs.emplace_back(OrigArg.Regs[0], SplitVTs[0].getTypeForEVT(Ctx),
296 OrigArg.OrigArgIndex, OrigArg.Flags[0],
297 OrigArg.IsFixed, OrigArg.OrigValue);
298 return;
299 }
300
301 // Create one ArgInfo for each virtual register in the original ArgInfo.
302 assert(OrigArg.Regs.size() == SplitVTs.size() && "Regs / types mismatch");
303
304 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
305 OrigArg.Ty, CallConv, false, DL);
306 for (unsigned i = 0, e = SplitVTs.size(); i < e; ++i) {
307 Type *SplitTy = SplitVTs[i].getTypeForEVT(Ctx);
308 SplitArgs.emplace_back(OrigArg.Regs[i], SplitTy, OrigArg.OrigArgIndex,
309 OrigArg.Flags[0], OrigArg.IsFixed);
310 if (NeedsRegBlock)
311 SplitArgs.back().Flags[0].setInConsecutiveRegs();
312 }
313
314 SplitArgs.back().Flags[0].setInConsecutiveRegsLast();
315}
316
317/// Pack values \p SrcRegs to cover the vector type result \p DstRegs.
320 ArrayRef<Register> SrcRegs) {
321 MachineRegisterInfo &MRI = *B.getMRI();
322 LLT LLTy = MRI.getType(DstRegs[0]);
323 LLT PartLLT = MRI.getType(SrcRegs[0]);
324
325 // Deal with v3s16 split into v2s16
326 LLT LCMTy = getCoverTy(LLTy, PartLLT);
327 if (LCMTy == LLTy) {
328 // Common case where no padding is needed.
329 assert(DstRegs.size() == 1);
330 return B.buildConcatVectors(DstRegs[0], SrcRegs);
331 }
332
333 // We need to create an unmerge to the result registers, which may require
334 // widening the original value.
335 Register UnmergeSrcReg;
336 if (LCMTy != PartLLT) {
337 assert(DstRegs.size() == 1);
338 return B.buildDeleteTrailingVectorElements(
339 DstRegs[0], B.buildMergeLikeInstr(LCMTy, SrcRegs));
340 } else {
341 // We don't need to widen anything if we're extracting a scalar which was
342 // promoted to a vector e.g. s8 -> v4s8 -> s8
343 assert(SrcRegs.size() == 1);
344 UnmergeSrcReg = SrcRegs[0];
345 }
346
347 int NumDst = LCMTy.getSizeInBits() / LLTy.getSizeInBits();
348
349 SmallVector<Register, 8> PadDstRegs(NumDst);
350 std::copy(DstRegs.begin(), DstRegs.end(), PadDstRegs.begin());
351
352 // Create the excess dead defs for the unmerge.
353 for (int I = DstRegs.size(); I != NumDst; ++I)
354 PadDstRegs[I] = MRI.createGenericVirtualRegister(LLTy);
355
356 if (PadDstRegs.size() == 1)
357 return B.buildDeleteTrailingVectorElements(DstRegs[0], UnmergeSrcReg);
358 return B.buildUnmerge(PadDstRegs, UnmergeSrcReg);
359}
360
361/// Create a sequence of instructions to combine pieces split into register
362/// typed values to the original IR value. \p OrigRegs contains the destination
363/// value registers of type \p LLTy, and \p Regs contains the legalized pieces
364/// with type \p PartLLT. This is used for incoming values (physregs to vregs).
366 ArrayRef<Register> Regs, LLT LLTy, LLT PartLLT,
367 const ISD::ArgFlagsTy Flags) {
368 MachineRegisterInfo &MRI = *B.getMRI();
369
370 if (PartLLT == LLTy) {
371 // We should have avoided introducing a new virtual register, and just
372 // directly assigned here.
373 assert(OrigRegs[0] == Regs[0]);
374 return;
375 }
376
377 if (PartLLT.getSizeInBits() == LLTy.getSizeInBits() && OrigRegs.size() == 1 &&
378 Regs.size() == 1) {
379 B.buildBitcast(OrigRegs[0], Regs[0]);
380 return;
381 }
382
383 // A vector PartLLT needs extending to LLTy's element size.
384 // E.g. <2 x s64> = G_SEXT <2 x s32>.
385 if (PartLLT.isVector() == LLTy.isVector() &&
386 PartLLT.getScalarSizeInBits() > LLTy.getScalarSizeInBits() &&
387 (!PartLLT.isVector() ||
388 PartLLT.getElementCount() == LLTy.getElementCount()) &&
389 OrigRegs.size() == 1 && Regs.size() == 1) {
390 Register SrcReg = Regs[0];
391
392 LLT LocTy = MRI.getType(SrcReg);
393
394 if (Flags.isSExt()) {
395 SrcReg = B.buildAssertSExt(LocTy, SrcReg, LLTy.getScalarSizeInBits())
396 .getReg(0);
397 } else if (Flags.isZExt()) {
398 SrcReg = B.buildAssertZExt(LocTy, SrcReg, LLTy.getScalarSizeInBits())
399 .getReg(0);
400 }
401
402 // Sometimes pointers are passed zero extended.
403 LLT OrigTy = MRI.getType(OrigRegs[0]);
404 if (OrigTy.isPointer()) {
405 LLT IntPtrTy = LLT::scalar(OrigTy.getSizeInBits());
406 B.buildIntToPtr(OrigRegs[0], B.buildTrunc(IntPtrTy, SrcReg));
407 return;
408 }
409
410 B.buildTrunc(OrigRegs[0], SrcReg);
411 return;
412 }
413
414 if (!LLTy.isVector() && !PartLLT.isVector()) {
415 assert(OrigRegs.size() == 1);
416 LLT OrigTy = MRI.getType(OrigRegs[0]);
417
418 unsigned SrcSize = PartLLT.getSizeInBits().getFixedValue() * Regs.size();
419 if (SrcSize == OrigTy.getSizeInBits())
420 B.buildMergeValues(OrigRegs[0], Regs);
421 else {
422 auto Widened = B.buildMergeLikeInstr(LLT::scalar(SrcSize), Regs);
423 B.buildTrunc(OrigRegs[0], Widened);
424 }
425
426 return;
427 }
428
429 if (PartLLT.isVector()) {
430 assert(OrigRegs.size() == 1);
431 SmallVector<Register> CastRegs(Regs.begin(), Regs.end());
432
433 // If PartLLT is a mismatched vector in both number of elements and element
434 // size, e.g. PartLLT == v2s64 and LLTy is v3s32, then first coerce it to
435 // have the same elt type, i.e. v4s32.
436 // TODO: Extend this coersion to element multiples other than just 2.
437 if (TypeSize::isKnownGT(PartLLT.getSizeInBits(), LLTy.getSizeInBits()) &&
438 PartLLT.getScalarSizeInBits() == LLTy.getScalarSizeInBits() * 2 &&
439 Regs.size() == 1) {
440 LLT NewTy = PartLLT.changeElementType(LLTy.getElementType())
441 .changeElementCount(PartLLT.getElementCount() * 2);
442 CastRegs[0] = B.buildBitcast(NewTy, Regs[0]).getReg(0);
443 PartLLT = NewTy;
444 }
445
446 if (LLTy.getScalarType() == PartLLT.getElementType()) {
447 mergeVectorRegsToResultRegs(B, OrigRegs, CastRegs);
448 } else {
449 unsigned I = 0;
450 LLT GCDTy = getGCDType(LLTy, PartLLT);
451
452 // We are both splitting a vector, and bitcasting its element types. Cast
453 // the source pieces into the appropriate number of pieces with the result
454 // element type.
455 for (Register SrcReg : CastRegs)
456 CastRegs[I++] = B.buildBitcast(GCDTy, SrcReg).getReg(0);
457 mergeVectorRegsToResultRegs(B, OrigRegs, CastRegs);
458 }
459
460 return;
461 }
462
463 assert(LLTy.isVector() && !PartLLT.isVector());
464
465 LLT DstEltTy = LLTy.getElementType();
466
467 // Pointer information was discarded. We'll need to coerce some register types
468 // to avoid violating type constraints.
469 LLT RealDstEltTy = MRI.getType(OrigRegs[0]).getElementType();
470
471 assert(DstEltTy.getSizeInBits() == RealDstEltTy.getSizeInBits());
472
473 if (DstEltTy == PartLLT) {
474 // Vector was trivially scalarized.
475
476 if (RealDstEltTy.isPointer()) {
477 for (Register Reg : Regs)
478 MRI.setType(Reg, RealDstEltTy);
479 }
480
481 B.buildBuildVector(OrigRegs[0], Regs);
482 } else if (DstEltTy.getSizeInBits() > PartLLT.getSizeInBits()) {
483 // Deal with vector with 64-bit elements decomposed to 32-bit
484 // registers. Need to create intermediate 64-bit elements.
485 SmallVector<Register, 8> EltMerges;
486 int PartsPerElt =
487 divideCeil(DstEltTy.getSizeInBits(), PartLLT.getSizeInBits());
488 LLT ExtendedPartTy = LLT::scalar(PartLLT.getSizeInBits() * PartsPerElt);
489
490 for (int I = 0, NumElts = LLTy.getNumElements(); I != NumElts; ++I) {
491 auto Merge =
492 B.buildMergeLikeInstr(ExtendedPartTy, Regs.take_front(PartsPerElt));
493 if (ExtendedPartTy.getSizeInBits() > RealDstEltTy.getSizeInBits())
494 Merge = B.buildTrunc(RealDstEltTy, Merge);
495 // Fix the type in case this is really a vector of pointers.
496 MRI.setType(Merge.getReg(0), RealDstEltTy);
497 EltMerges.push_back(Merge.getReg(0));
498 Regs = Regs.drop_front(PartsPerElt);
499 }
500
501 B.buildBuildVector(OrigRegs[0], EltMerges);
502 } else {
503 // Vector was split, and elements promoted to a wider type.
504 // FIXME: Should handle floating point promotions.
505 unsigned NumElts = LLTy.getNumElements();
506 LLT BVType = LLT::fixed_vector(NumElts, PartLLT);
507
508 Register BuildVec;
509 if (NumElts == Regs.size())
510 BuildVec = B.buildBuildVector(BVType, Regs).getReg(0);
511 else {
512 // Vector elements are packed in the inputs.
513 // e.g. we have a <4 x s16> but 2 x s32 in regs.
514 assert(NumElts > Regs.size());
515 LLT SrcEltTy = MRI.getType(Regs[0]);
516
517 LLT OriginalEltTy = MRI.getType(OrigRegs[0]).getElementType();
518
519 // Input registers contain packed elements.
520 // Determine how many elements per reg.
521 assert((SrcEltTy.getSizeInBits() % OriginalEltTy.getSizeInBits()) == 0);
522 unsigned EltPerReg =
523 (SrcEltTy.getSizeInBits() / OriginalEltTy.getSizeInBits());
524
526 BVRegs.reserve(Regs.size() * EltPerReg);
527 for (Register R : Regs) {
528 auto Unmerge = B.buildUnmerge(OriginalEltTy, R);
529 for (unsigned K = 0; K < EltPerReg; ++K)
530 BVRegs.push_back(B.buildAnyExt(PartLLT, Unmerge.getReg(K)).getReg(0));
531 }
532
533 // We may have some more elements in BVRegs, e.g. if we have 2 s32 pieces
534 // for a <3 x s16> vector. We should have less than EltPerReg extra items.
535 if (BVRegs.size() > NumElts) {
536 assert((BVRegs.size() - NumElts) < EltPerReg);
537 BVRegs.truncate(NumElts);
538 }
539 BuildVec = B.buildBuildVector(BVType, BVRegs).getReg(0);
540 }
541 B.buildTrunc(OrigRegs[0], BuildVec);
542 }
543}
544
545/// Create a sequence of instructions to expand the value in \p SrcReg (of type
546/// \p SrcTy) to the types in \p DstRegs (of type \p PartTy). \p ExtendOp should
547/// contain the type of scalar value extension if necessary.
548///
549/// This is used for outgoing values (vregs to physregs)
551 Register SrcReg, LLT SrcTy, LLT PartTy,
552 unsigned ExtendOp = TargetOpcode::G_ANYEXT) {
553 // We could just insert a regular copy, but this is unreachable at the moment.
554 assert(SrcTy != PartTy && "identical part types shouldn't reach here");
555
556 const TypeSize PartSize = PartTy.getSizeInBits();
557
558 if (PartTy.isVector() == SrcTy.isVector() &&
559 PartTy.getScalarSizeInBits() > SrcTy.getScalarSizeInBits()) {
560 assert(DstRegs.size() == 1);
561 B.buildInstr(ExtendOp, {DstRegs[0]}, {SrcReg});
562 return;
563 }
564
565 if (SrcTy.isVector() && !PartTy.isVector() &&
566 TypeSize::isKnownGT(PartSize, SrcTy.getElementType().getSizeInBits())) {
567 // Vector was scalarized, and the elements extended.
568 auto UnmergeToEltTy = B.buildUnmerge(SrcTy.getElementType(), SrcReg);
569 for (int i = 0, e = DstRegs.size(); i != e; ++i)
570 B.buildAnyExt(DstRegs[i], UnmergeToEltTy.getReg(i));
571 return;
572 }
573
574 if (SrcTy.isVector() && PartTy.isVector() &&
575 PartTy.getSizeInBits() == SrcTy.getSizeInBits() &&
577 PartTy.getElementCount())) {
578 // A coercion like: v2f32 -> v4f32 or nxv2f32 -> nxv4f32
579 Register DstReg = DstRegs.front();
580 B.buildPadVectorWithUndefElements(DstReg, SrcReg);
581 return;
582 }
583
584 LLT GCDTy = getGCDType(SrcTy, PartTy);
585 if (GCDTy == PartTy) {
586 // If this already evenly divisible, we can create a simple unmerge.
587 B.buildUnmerge(DstRegs, SrcReg);
588 return;
589 }
590
591 if (SrcTy.isVector() && !PartTy.isVector() &&
592 SrcTy.getScalarSizeInBits() > PartTy.getSizeInBits()) {
593 LLT ExtTy =
595 LLT::scalar(PartTy.getScalarSizeInBits() * DstRegs.size() /
596 SrcTy.getNumElements()));
597 auto Ext = B.buildAnyExt(ExtTy, SrcReg);
598 B.buildUnmerge(DstRegs, Ext);
599 return;
600 }
601
602 MachineRegisterInfo &MRI = *B.getMRI();
603 LLT DstTy = MRI.getType(DstRegs[0]);
604 LLT LCMTy = getCoverTy(SrcTy, PartTy);
605
606 if (PartTy.isVector() && LCMTy == PartTy) {
607 assert(DstRegs.size() == 1);
608 B.buildPadVectorWithUndefElements(DstRegs[0], SrcReg);
609 return;
610 }
611
612 const unsigned DstSize = DstTy.getSizeInBits();
613 const unsigned SrcSize = SrcTy.getSizeInBits();
614 unsigned CoveringSize = LCMTy.getSizeInBits();
615
616 Register UnmergeSrc = SrcReg;
617
618 if (!LCMTy.isVector() && CoveringSize != SrcSize) {
619 // For scalars, it's common to be able to use a simple extension.
620 if (SrcTy.isScalar() && DstTy.isScalar()) {
621 CoveringSize = alignTo(SrcSize, DstSize);
622 LLT CoverTy = LLT::scalar(CoveringSize);
623 UnmergeSrc = B.buildInstr(ExtendOp, {CoverTy}, {SrcReg}).getReg(0);
624 } else {
625 // Widen to the common type.
626 // FIXME: This should respect the extend type
627 Register Undef = B.buildUndef(SrcTy).getReg(0);
628 SmallVector<Register, 8> MergeParts(1, SrcReg);
629 for (unsigned Size = SrcSize; Size != CoveringSize; Size += SrcSize)
630 MergeParts.push_back(Undef);
631 UnmergeSrc = B.buildMergeLikeInstr(LCMTy, MergeParts).getReg(0);
632 }
633 }
634
635 if (LCMTy.isVector() && CoveringSize != SrcSize)
636 UnmergeSrc = B.buildPadVectorWithUndefElements(LCMTy, SrcReg).getReg(0);
637
638 B.buildUnmerge(DstRegs, UnmergeSrc);
639}
640
642 ValueHandler &Handler, ValueAssigner &Assigner,
644 CallingConv::ID CallConv, bool IsVarArg,
645 ArrayRef<Register> ThisReturnRegs) const {
646 MachineFunction &MF = MIRBuilder.getMF();
647 const Function &F = MF.getFunction();
649
650 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, F.getContext());
651 if (!determineAssignments(Assigner, Args, CCInfo))
652 return false;
653
654 return handleAssignments(Handler, Args, CCInfo, ArgLocs, MIRBuilder,
655 ThisReturnRegs);
656}
657
659 if (Flags.isSExt())
660 return TargetOpcode::G_SEXT;
661 if (Flags.isZExt())
662 return TargetOpcode::G_ZEXT;
663 return TargetOpcode::G_ANYEXT;
664}
665
668 CCState &CCInfo) const {
669 LLVMContext &Ctx = CCInfo.getContext();
670 const CallingConv::ID CallConv = CCInfo.getCallingConv();
671
672 unsigned NumArgs = Args.size();
673 for (unsigned i = 0; i != NumArgs; ++i) {
674 EVT CurVT = EVT::getEVT(Args[i].Ty);
675
676 MVT NewVT = TLI->getRegisterTypeForCallingConv(Ctx, CallConv, CurVT);
677
678 // If we need to split the type over multiple regs, check it's a scenario
679 // we currently support.
680 unsigned NumParts =
681 TLI->getNumRegistersForCallingConv(Ctx, CallConv, CurVT);
682
683 if (NumParts == 1) {
684 // Try to use the register type if we couldn't assign the VT.
685 if (Assigner.assignArg(i, CurVT, NewVT, NewVT, CCValAssign::Full, Args[i],
686 Args[i].Flags[0], CCInfo))
687 return false;
688 continue;
689 }
690
691 // For incoming arguments (physregs to vregs), we could have values in
692 // physregs (or memlocs) which we want to extract and copy to vregs.
693 // During this, we might have to deal with the LLT being split across
694 // multiple regs, so we have to record this information for later.
695 //
696 // If we have outgoing args, then we have the opposite case. We have a
697 // vreg with an LLT which we want to assign to a physical location, and
698 // we might have to record that the value has to be split later.
699
700 // We're handling an incoming arg which is split over multiple regs.
701 // E.g. passing an s128 on AArch64.
702 ISD::ArgFlagsTy OrigFlags = Args[i].Flags[0];
703 Args[i].Flags.clear();
704
705 for (unsigned Part = 0; Part < NumParts; ++Part) {
706 ISD::ArgFlagsTy Flags = OrigFlags;
707 if (Part == 0) {
708 Flags.setSplit();
709 } else {
710 Flags.setOrigAlign(Align(1));
711 if (Part == NumParts - 1)
712 Flags.setSplitEnd();
713 }
714
715 Args[i].Flags.push_back(Flags);
716 if (Assigner.assignArg(i, CurVT, NewVT, NewVT, CCValAssign::Full, Args[i],
717 Args[i].Flags[Part], CCInfo)) {
718 // Still couldn't assign this smaller part type for some reason.
719 return false;
720 }
721 }
722 }
723
724 return true;
725}
726
729 CCState &CCInfo,
731 MachineIRBuilder &MIRBuilder,
732 ArrayRef<Register> ThisReturnRegs) const {
733 MachineFunction &MF = MIRBuilder.getMF();
735 const Function &F = MF.getFunction();
736 const DataLayout &DL = F.getDataLayout();
737
738 const unsigned NumArgs = Args.size();
739
740 // Stores thunks for outgoing register assignments. This is used so we delay
741 // generating register copies until mem loc assignments are done. We do this
742 // so that if the target is using the delayed stack protector feature, we can
743 // find the split point of the block accurately. E.g. if we have:
744 // G_STORE %val, %memloc
745 // $x0 = COPY %foo
746 // $x1 = COPY %bar
747 // CALL func
748 // ... then the split point for the block will correctly be at, and including,
749 // the copy to $x0. If instead the G_STORE instruction immediately precedes
750 // the CALL, then we'd prematurely choose the CALL as the split point, thus
751 // generating a split block with a CALL that uses undefined physregs.
752 SmallVector<std::function<void()>> DelayedOutgoingRegAssignments;
753
754 for (unsigned i = 0, j = 0; i != NumArgs; ++i, ++j) {
755 assert(j < ArgLocs.size() && "Skipped too many arg locs");
756 CCValAssign &VA = ArgLocs[j];
757 assert(VA.getValNo() == i && "Location doesn't correspond to current arg");
758
759 if (VA.needsCustom()) {
760 std::function<void()> Thunk;
761 unsigned NumArgRegs = Handler.assignCustomValue(
762 Args[i], ArrayRef(ArgLocs).slice(j), &Thunk);
763 if (Thunk)
764 DelayedOutgoingRegAssignments.emplace_back(Thunk);
765 if (!NumArgRegs)
766 return false;
767 j += (NumArgRegs - 1);
768 continue;
769 }
770
771 auto AllocaAddressSpace = MF.getDataLayout().getAllocaAddrSpace();
772
773 const MVT ValVT = VA.getValVT();
774 const MVT LocVT = VA.getLocVT();
775
776 const LLT LocTy(LocVT);
777 const LLT ValTy(ValVT);
778 const LLT NewLLT = Handler.isIncomingArgumentHandler() ? LocTy : ValTy;
779 const EVT OrigVT = EVT::getEVT(Args[i].Ty);
780 const LLT OrigTy = getLLTForType(*Args[i].Ty, DL);
781 const LLT PointerTy = LLT::pointer(
782 AllocaAddressSpace, DL.getPointerSizeInBits(AllocaAddressSpace));
783
784 // Expected to be multiple regs for a single incoming arg.
785 // There should be Regs.size() ArgLocs per argument.
786 // This should be the same as getNumRegistersForCallingConv
787 const unsigned NumParts = Args[i].Flags.size();
788
789 // Now split the registers into the assigned types.
790 Args[i].OrigRegs.assign(Args[i].Regs.begin(), Args[i].Regs.end());
791
792 if (NumParts != 1 || NewLLT != OrigTy) {
793 // If we can't directly assign the register, we need one or more
794 // intermediate values.
795 Args[i].Regs.resize(NumParts);
796
797 // When we have indirect parameter passing we are receiving a pointer,
798 // that points to the actual value, so we need one "temporary" pointer.
799 if (VA.getLocInfo() == CCValAssign::Indirect) {
800 if (Handler.isIncomingArgumentHandler())
801 Args[i].Regs[0] = MRI.createGenericVirtualRegister(PointerTy);
802 } else {
803 // For each split register, create and assign a vreg that will store
804 // the incoming component of the larger value. These will later be
805 // merged to form the final vreg.
806 for (unsigned Part = 0; Part < NumParts; ++Part)
807 Args[i].Regs[Part] = MRI.createGenericVirtualRegister(NewLLT);
808 }
809 }
810
811 assert((j + (NumParts - 1)) < ArgLocs.size() &&
812 "Too many regs for number of args");
813
814 // Coerce into outgoing value types before register assignment.
815 if (!Handler.isIncomingArgumentHandler() && OrigTy != ValTy &&
817 assert(Args[i].OrigRegs.size() == 1);
818 buildCopyToRegs(MIRBuilder, Args[i].Regs, Args[i].OrigRegs[0], OrigTy,
819 ValTy, extendOpFromFlags(Args[i].Flags[0]));
820 }
821
822 bool IndirectParameterPassingHandled = false;
823 bool BigEndianPartOrdering = TLI->hasBigEndianPartOrdering(OrigVT, DL);
824 for (unsigned Part = 0; Part < NumParts; ++Part) {
825 assert((VA.getLocInfo() != CCValAssign::Indirect || Part == 0) &&
826 "Only the first parameter should be processed when "
827 "handling indirect passing!");
828 Register ArgReg = Args[i].Regs[Part];
829 // There should be Regs.size() ArgLocs per argument.
830 unsigned Idx = BigEndianPartOrdering ? NumParts - 1 - Part : Part;
831 CCValAssign &VA = ArgLocs[j + Idx];
832 const ISD::ArgFlagsTy Flags = Args[i].Flags[Part];
833
834 // We found an indirect parameter passing, and we have an
835 // OutgoingValueHandler as our handler (so we are at the call site or the
836 // return value). In this case, start the construction of the following
837 // GMIR, that is responsible for the preparation of indirect parameter
838 // passing:
839 //
840 // %1(indirectly passed type) = The value to pass
841 // %3(pointer) = G_FRAME_INDEX %stack.0
842 // G_STORE %1, %3 :: (store (s128), align 8)
843 //
844 // After this GMIR, the remaining part of the loop body will decide how
845 // to get the value to the caller and we break out of the loop.
846 if (VA.getLocInfo() == CCValAssign::Indirect &&
847 !Handler.isIncomingArgumentHandler()) {
848 Align AlignmentForStored = DL.getPrefTypeAlign(Args[i].Ty);
849 MachineFrameInfo &MFI = MF.getFrameInfo();
850 // Get some space on the stack for the value, so later we can pass it
851 // as a reference.
852 int FrameIdx = MFI.CreateStackObject(OrigTy.getScalarSizeInBits(),
853 AlignmentForStored, false);
854 Register PointerToStackReg =
855 MIRBuilder.buildFrameIndex(PointerTy, FrameIdx).getReg(0);
856 MachinePointerInfo StackPointerMPO =
858 // Store the value in the previously created stack space.
859 MIRBuilder.buildStore(Args[i].OrigRegs[Part], PointerToStackReg,
860 StackPointerMPO,
861 inferAlignFromPtrInfo(MF, StackPointerMPO));
862
863 ArgReg = PointerToStackReg;
864 IndirectParameterPassingHandled = true;
865 }
866
867 if (VA.isMemLoc() && !Flags.isByVal()) {
868 // Individual pieces may have been spilled to the stack and others
869 // passed in registers.
870
871 // TODO: The memory size may be larger than the value we need to
872 // store. We may need to adjust the offset for big endian targets.
873 LLT MemTy = Handler.getStackValueStoreType(DL, VA, Flags);
874
876 Register StackAddr =
878 ? PointerTy.getSizeInBytes()
879 : MemTy.getSizeInBytes(),
880 VA.getLocMemOffset(), MPO, Flags);
881
882 // Finish the handling of indirect passing from the passers
883 // (OutgoingParameterHandler) side.
884 // This branch is needed, so the pointer to the value is loaded onto the
885 // stack.
887 Handler.assignValueToAddress(ArgReg, StackAddr, PointerTy, MPO, VA);
888 else
889 Handler.assignValueToAddress(Args[i], Part, StackAddr, MemTy, MPO,
890 VA);
891 } else if (VA.isMemLoc() && Flags.isByVal()) {
892 assert(Args[i].Regs.size() == 1 && "didn't expect split byval pointer");
893
894 if (Handler.isIncomingArgumentHandler()) {
895 // We just need to copy the frame index value to the pointer.
897 Register StackAddr = Handler.getStackAddress(
898 Flags.getByValSize(), VA.getLocMemOffset(), MPO, Flags);
899 MIRBuilder.buildCopy(Args[i].Regs[0], StackAddr);
900 } else {
901 // For outgoing byval arguments, insert the implicit copy byval
902 // implies, such that writes in the callee do not modify the caller's
903 // value.
904 uint64_t MemSize = Flags.getByValSize();
905 int64_t Offset = VA.getLocMemOffset();
906
907 MachinePointerInfo DstMPO;
908 Register StackAddr =
909 Handler.getStackAddress(MemSize, Offset, DstMPO, Flags);
910
911 MachinePointerInfo SrcMPO(Args[i].OrigValue);
912 if (!Args[i].OrigValue) {
913 // We still need to accurately track the stack address space if we
914 // don't know the underlying value.
915 const LLT PtrTy = MRI.getType(StackAddr);
916 SrcMPO = MachinePointerInfo(PtrTy.getAddressSpace());
917 }
918
919 Align DstAlign = std::max(Flags.getNonZeroByValAlign(),
920 inferAlignFromPtrInfo(MF, DstMPO));
921
922 Align SrcAlign = std::max(Flags.getNonZeroByValAlign(),
923 inferAlignFromPtrInfo(MF, SrcMPO));
924
925 Handler.copyArgumentMemory(Args[i], StackAddr, Args[i].Regs[0],
926 DstMPO, DstAlign, SrcMPO, SrcAlign,
927 MemSize, VA);
928 }
929 } else if (i == 0 && !ThisReturnRegs.empty() &&
930 Handler.isIncomingArgumentHandler() &&
932 Handler.assignValueToReg(ArgReg, ThisReturnRegs[Part], VA);
933 } else if (Handler.isIncomingArgumentHandler()) {
934 Handler.assignValueToReg(ArgReg, VA.getLocReg(), VA);
935 } else {
936 DelayedOutgoingRegAssignments.emplace_back([=, &Handler]() {
937 Handler.assignValueToReg(ArgReg, VA.getLocReg(), VA);
938 });
939 }
940
941 // Finish the handling of indirect parameter passing when receiving
942 // the value (we are in the called function or the caller when receiving
943 // the return value).
944 if (VA.getLocInfo() == CCValAssign::Indirect &&
945 Handler.isIncomingArgumentHandler()) {
946 Align Alignment = DL.getABITypeAlign(Args[i].Ty);
948
949 // Since we are doing indirect parameter passing, we know that the value
950 // in the temporary register is not the value passed to the function,
951 // but rather a pointer to that value. Let's load that value into the
952 // virtual register where the parameter should go.
953 MIRBuilder.buildLoad(Args[i].OrigRegs[0], Args[i].Regs[0], MPO,
954 Alignment);
955
956 IndirectParameterPassingHandled = true;
957 }
958
959 if (IndirectParameterPassingHandled)
960 break;
961 }
962
963 // Now that all pieces have been assigned, re-pack the register typed values
964 // into the original value typed registers. This is only necessary, when
965 // the value was passed in multiple registers, not indirectly.
966 if (Handler.isIncomingArgumentHandler() && OrigVT != LocVT &&
967 !IndirectParameterPassingHandled) {
968 // Merge the split registers into the expected larger result vregs of
969 // the original call.
970 buildCopyFromRegs(MIRBuilder, Args[i].OrigRegs, Args[i].Regs, OrigTy,
971 LocTy, Args[i].Flags[0]);
972 }
973
974 j += NumParts - 1;
975 }
976 for (auto &Fn : DelayedOutgoingRegAssignments)
977 Fn();
978
979 return true;
980}
981
983 ArrayRef<Register> VRegs, Register DemoteReg,
984 int FI) const {
985 MachineFunction &MF = MIRBuilder.getMF();
987 const DataLayout &DL = MF.getDataLayout();
988
989 SmallVector<EVT, 4> SplitVTs;
991 ComputeValueVTs(*TLI, DL, RetTy, SplitVTs, &Offsets, 0);
992
993 assert(VRegs.size() == SplitVTs.size());
994
995 unsigned NumValues = SplitVTs.size();
996 Align BaseAlign = DL.getPrefTypeAlign(RetTy);
997 Type *RetPtrTy =
998 PointerType::get(RetTy->getContext(), DL.getAllocaAddrSpace());
999 LLT OffsetLLTy = getLLTForType(*DL.getIndexType(RetPtrTy), DL);
1000
1002
1003 for (unsigned I = 0; I < NumValues; ++I) {
1004 Register Addr;
1005 MIRBuilder.materializePtrAdd(Addr, DemoteReg, OffsetLLTy, Offsets[I]);
1006 auto *MMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
1007 MRI.getType(VRegs[I]),
1008 commonAlignment(BaseAlign, Offsets[I]));
1009 MIRBuilder.buildLoad(VRegs[I], Addr, *MMO);
1010 }
1011}
1012
1014 ArrayRef<Register> VRegs,
1015 Register DemoteReg) const {
1016 MachineFunction &MF = MIRBuilder.getMF();
1018 const DataLayout &DL = MF.getDataLayout();
1019
1020 SmallVector<EVT, 4> SplitVTs;
1022 ComputeValueVTs(*TLI, DL, RetTy, SplitVTs, &Offsets, 0);
1023
1024 assert(VRegs.size() == SplitVTs.size());
1025
1026 unsigned NumValues = SplitVTs.size();
1027 Align BaseAlign = DL.getPrefTypeAlign(RetTy);
1028 unsigned AS = DL.getAllocaAddrSpace();
1029 LLT OffsetLLTy = getLLTForType(*DL.getIndexType(RetTy->getPointerTo(AS)), DL);
1030
1031 MachinePointerInfo PtrInfo(AS);
1032
1033 for (unsigned I = 0; I < NumValues; ++I) {
1034 Register Addr;
1035 MIRBuilder.materializePtrAdd(Addr, DemoteReg, OffsetLLTy, Offsets[I]);
1036 auto *MMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
1037 MRI.getType(VRegs[I]),
1038 commonAlignment(BaseAlign, Offsets[I]));
1039 MIRBuilder.buildStore(VRegs[I], Addr, *MMO);
1040 }
1041}
1042
1044 const Function &F, SmallVectorImpl<ArgInfo> &SplitArgs, Register &DemoteReg,
1045 MachineRegisterInfo &MRI, const DataLayout &DL) const {
1046 unsigned AS = DL.getAllocaAddrSpace();
1047 DemoteReg = MRI.createGenericVirtualRegister(
1048 LLT::pointer(AS, DL.getPointerSizeInBits(AS)));
1049
1050 Type *PtrTy = PointerType::get(F.getReturnType(), AS);
1051
1052 SmallVector<EVT, 1> ValueVTs;
1053 ComputeValueVTs(*TLI, DL, PtrTy, ValueVTs);
1054
1055 // NOTE: Assume that a pointer won't get split into more than one VT.
1056 assert(ValueVTs.size() == 1);
1057
1058 ArgInfo DemoteArg(DemoteReg, ValueVTs[0].getTypeForEVT(PtrTy->getContext()),
1061 DemoteArg.Flags[0].setSRet();
1062 SplitArgs.insert(SplitArgs.begin(), DemoteArg);
1063}
1064
1066 const CallBase &CB,
1067 CallLoweringInfo &Info) const {
1068 const DataLayout &DL = MIRBuilder.getDataLayout();
1069 Type *RetTy = CB.getType();
1070 unsigned AS = DL.getAllocaAddrSpace();
1071 LLT FramePtrTy = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
1072
1073 int FI = MIRBuilder.getMF().getFrameInfo().CreateStackObject(
1074 DL.getTypeAllocSize(RetTy), DL.getPrefTypeAlign(RetTy), false);
1075
1076 Register DemoteReg = MIRBuilder.buildFrameIndex(FramePtrTy, FI).getReg(0);
1077 ArgInfo DemoteArg(DemoteReg, PointerType::get(RetTy, AS),
1079 setArgFlags(DemoteArg, AttributeList::ReturnIndex, DL, CB);
1080 DemoteArg.Flags[0].setSRet();
1081
1082 Info.OrigArgs.insert(Info.OrigArgs.begin(), DemoteArg);
1083 Info.DemoteStackIndex = FI;
1084 Info.DemoteRegister = DemoteReg;
1085}
1086
1089 CCAssignFn *Fn) const {
1090 for (unsigned I = 0, E = Outs.size(); I < E; ++I) {
1091 MVT VT = MVT::getVT(Outs[I].Ty);
1092 if (Fn(I, VT, VT, CCValAssign::Full, Outs[I].Flags[0], CCInfo))
1093 return false;
1094 }
1095 return true;
1096}
1097
1099 AttributeList Attrs,
1101 const DataLayout &DL) const {
1102 LLVMContext &Context = RetTy->getContext();
1104
1105 SmallVector<EVT, 4> SplitVTs;
1106 ComputeValueVTs(*TLI, DL, RetTy, SplitVTs);
1108
1109 for (EVT VT : SplitVTs) {
1110 unsigned NumParts =
1111 TLI->getNumRegistersForCallingConv(Context, CallConv, VT);
1112 MVT RegVT = TLI->getRegisterTypeForCallingConv(Context, CallConv, VT);
1113 Type *PartTy = EVT(RegVT).getTypeForEVT(Context);
1114
1115 for (unsigned I = 0; I < NumParts; ++I) {
1116 Outs.emplace_back(PartTy, Flags);
1117 }
1118 }
1119}
1120
1122 const auto &F = MF.getFunction();
1123 Type *ReturnType = F.getReturnType();
1124 CallingConv::ID CallConv = F.getCallingConv();
1125
1127 getReturnInfo(CallConv, ReturnType, F.getAttributes(), SplitArgs,
1128 MF.getDataLayout());
1129 return canLowerReturn(MF, CallConv, SplitArgs, F.isVarArg());
1130}
1131
1133 const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask,
1134 const SmallVectorImpl<CCValAssign> &OutLocs,
1135 const SmallVectorImpl<ArgInfo> &OutArgs) const {
1136 for (unsigned i = 0; i < OutLocs.size(); ++i) {
1137 const auto &ArgLoc = OutLocs[i];
1138 // If it's not a register, it's fine.
1139 if (!ArgLoc.isRegLoc())
1140 continue;
1141
1142 MCRegister PhysReg = ArgLoc.getLocReg();
1143
1144 // Only look at callee-saved registers.
1145 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, PhysReg))
1146 continue;
1147
1148 LLVM_DEBUG(
1149 dbgs()
1150 << "... Call has an argument passed in a callee-saved register.\n");
1151
1152 // Check if it was copied from.
1153 const ArgInfo &OutInfo = OutArgs[i];
1154
1155 if (OutInfo.Regs.size() > 1) {
1156 LLVM_DEBUG(
1157 dbgs() << "... Cannot handle arguments in multiple registers.\n");
1158 return false;
1159 }
1160
1161 // Check if we copy the register, walking through copies from virtual
1162 // registers. Note that getDefIgnoringCopies does not ignore copies from
1163 // physical registers.
1164 MachineInstr *RegDef = getDefIgnoringCopies(OutInfo.Regs[0], MRI);
1165 if (!RegDef || RegDef->getOpcode() != TargetOpcode::COPY) {
1166 LLVM_DEBUG(
1167 dbgs()
1168 << "... Parameter was not copied into a VReg, cannot tail call.\n");
1169 return false;
1170 }
1171
1172 // Got a copy. Verify that it's the same as the register we want.
1173 Register CopyRHS = RegDef->getOperand(1).getReg();
1174 if (CopyRHS != PhysReg) {
1175 LLVM_DEBUG(dbgs() << "... Callee-saved register was not copied into "
1176 "VReg, cannot tail call.\n");
1177 return false;
1178 }
1179 }
1180
1181 return true;
1182}
1183
1185 MachineFunction &MF,
1187 ValueAssigner &CalleeAssigner,
1188 ValueAssigner &CallerAssigner) const {
1189 const Function &F = MF.getFunction();
1190 CallingConv::ID CalleeCC = Info.CallConv;
1191 CallingConv::ID CallerCC = F.getCallingConv();
1192
1193 if (CallerCC == CalleeCC)
1194 return true;
1195
1197 CCState CCInfo1(CalleeCC, Info.IsVarArg, MF, ArgLocs1, F.getContext());
1198 if (!determineAssignments(CalleeAssigner, InArgs, CCInfo1))
1199 return false;
1200
1202 CCState CCInfo2(CallerCC, F.isVarArg(), MF, ArgLocs2, F.getContext());
1203 if (!determineAssignments(CallerAssigner, InArgs, CCInfo2))
1204 return false;
1205
1206 // We need the argument locations to match up exactly. If there's more in
1207 // one than the other, then we are done.
1208 if (ArgLocs1.size() != ArgLocs2.size())
1209 return false;
1210
1211 // Make sure that each location is passed in exactly the same way.
1212 for (unsigned i = 0, e = ArgLocs1.size(); i < e; ++i) {
1213 const CCValAssign &Loc1 = ArgLocs1[i];
1214 const CCValAssign &Loc2 = ArgLocs2[i];
1215
1216 // We need both of them to be the same. So if one is a register and one
1217 // isn't, we're done.
1218 if (Loc1.isRegLoc() != Loc2.isRegLoc())
1219 return false;
1220
1221 if (Loc1.isRegLoc()) {
1222 // If they don't have the same register location, we're done.
1223 if (Loc1.getLocReg() != Loc2.getLocReg())
1224 return false;
1225
1226 // They matched, so we can move to the next ArgLoc.
1227 continue;
1228 }
1229
1230 // Loc1 wasn't a RegLoc, so they both must be MemLocs. Check if they match.
1231 if (Loc1.getLocMemOffset() != Loc2.getLocMemOffset())
1232 return false;
1233 }
1234
1235 return true;
1236}
1237
1239 const DataLayout &DL, const CCValAssign &VA, ISD::ArgFlagsTy Flags) const {
1240 const MVT ValVT = VA.getValVT();
1241 if (ValVT != MVT::iPTR) {
1242 LLT ValTy(ValVT);
1243
1244 // We lost the pointeriness going through CCValAssign, so try to restore it
1245 // based on the flags.
1246 if (Flags.isPointer()) {
1247 LLT PtrTy = LLT::pointer(Flags.getPointerAddrSpace(),
1248 ValTy.getScalarSizeInBits());
1249 if (ValVT.isVector())
1250 return LLT::vector(ValTy.getElementCount(), PtrTy);
1251 return PtrTy;
1252 }
1253
1254 return ValTy;
1255 }
1256
1257 unsigned AddrSpace = Flags.getPointerAddrSpace();
1258 return LLT::pointer(AddrSpace, DL.getPointerSize(AddrSpace));
1259}
1260
1262 const ArgInfo &Arg, Register DstPtr, Register SrcPtr,
1263 const MachinePointerInfo &DstPtrInfo, Align DstAlign,
1264 const MachinePointerInfo &SrcPtrInfo, Align SrcAlign, uint64_t MemSize,
1265 CCValAssign &VA) const {
1266 MachineFunction &MF = MIRBuilder.getMF();
1268 SrcPtrInfo,
1270 SrcAlign);
1271
1273 DstPtrInfo,
1275 MemSize, DstAlign);
1276
1277 const LLT PtrTy = MRI.getType(DstPtr);
1278 const LLT SizeTy = LLT::scalar(PtrTy.getSizeInBits());
1279
1280 auto SizeConst = MIRBuilder.buildConstant(SizeTy, MemSize);
1281 MIRBuilder.buildMemCpy(DstPtr, SrcPtr, SizeConst, *DstMMO, *SrcMMO);
1282}
1283
1285 const CCValAssign &VA,
1286 unsigned MaxSizeBits) {
1287 LLT LocTy{VA.getLocVT()};
1288 LLT ValTy{VA.getValVT()};
1289
1290 if (LocTy.getSizeInBits() == ValTy.getSizeInBits())
1291 return ValReg;
1292
1293 if (LocTy.isScalar() && MaxSizeBits && MaxSizeBits < LocTy.getSizeInBits()) {
1294 if (MaxSizeBits <= ValTy.getSizeInBits())
1295 return ValReg;
1296 LocTy = LLT::scalar(MaxSizeBits);
1297 }
1298
1299 const LLT ValRegTy = MRI.getType(ValReg);
1300 if (ValRegTy.isPointer()) {
1301 // The x32 ABI wants to zero extend 32-bit pointers to 64-bit registers, so
1302 // we have to cast to do the extension.
1303 LLT IntPtrTy = LLT::scalar(ValRegTy.getSizeInBits());
1304 ValReg = MIRBuilder.buildPtrToInt(IntPtrTy, ValReg).getReg(0);
1305 }
1306
1307 switch (VA.getLocInfo()) {
1308 default:
1309 break;
1310 case CCValAssign::Full:
1311 case CCValAssign::BCvt:
1312 // FIXME: bitconverting between vector types may or may not be a
1313 // nop in big-endian situations.
1314 return ValReg;
1315 case CCValAssign::AExt: {
1316 auto MIB = MIRBuilder.buildAnyExt(LocTy, ValReg);
1317 return MIB.getReg(0);
1318 }
1319 case CCValAssign::SExt: {
1320 Register NewReg = MRI.createGenericVirtualRegister(LocTy);
1321 MIRBuilder.buildSExt(NewReg, ValReg);
1322 return NewReg;
1323 }
1324 case CCValAssign::ZExt: {
1325 Register NewReg = MRI.createGenericVirtualRegister(LocTy);
1326 MIRBuilder.buildZExt(NewReg, ValReg);
1327 return NewReg;
1328 }
1329 }
1330 llvm_unreachable("unable to extend register");
1331}
1332
1333void CallLowering::ValueAssigner::anchor() {}
1334
1336 const CCValAssign &VA, Register SrcReg, LLT NarrowTy) {
1337 switch (VA.getLocInfo()) {
1339 return MIRBuilder
1340 .buildAssertZExt(MRI.cloneVirtualRegister(SrcReg), SrcReg,
1341 NarrowTy.getScalarSizeInBits())
1342 .getReg(0);
1343 }
1345 return MIRBuilder
1346 .buildAssertSExt(MRI.cloneVirtualRegister(SrcReg), SrcReg,
1347 NarrowTy.getScalarSizeInBits())
1348 .getReg(0);
1349 break;
1350 }
1351 default:
1352 return SrcReg;
1353 }
1354}
1355
1356/// Check if we can use a basic COPY instruction between the two types.
1357///
1358/// We're currently building on top of the infrastructure using MVT, which loses
1359/// pointer information in the CCValAssign. We accept copies from physical
1360/// registers that have been reported as integers if it's to an equivalent sized
1361/// pointer LLT.
1362static bool isCopyCompatibleType(LLT SrcTy, LLT DstTy) {
1363 if (SrcTy == DstTy)
1364 return true;
1365
1366 if (SrcTy.getSizeInBits() != DstTy.getSizeInBits())
1367 return false;
1368
1369 SrcTy = SrcTy.getScalarType();
1370 DstTy = DstTy.getScalarType();
1371
1372 return (SrcTy.isPointer() && DstTy.isScalar()) ||
1373 (DstTy.isPointer() && SrcTy.isScalar());
1374}
1375
1377 Register ValVReg, Register PhysReg, const CCValAssign &VA) {
1378 const MVT LocVT = VA.getLocVT();
1379 const LLT LocTy(LocVT);
1380 const LLT RegTy = MRI.getType(ValVReg);
1381
1382 if (isCopyCompatibleType(RegTy, LocTy)) {
1383 MIRBuilder.buildCopy(ValVReg, PhysReg);
1384 return;
1385 }
1386
1387 auto Copy = MIRBuilder.buildCopy(LocTy, PhysReg);
1388 auto Hint = buildExtensionHint(VA, Copy.getReg(0), RegTy);
1389 MIRBuilder.buildTrunc(ValVReg, Hint);
1390}
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
static void addFlagsUsingAttrFn(ISD::ArgFlagsTy &Flags, const std::function< bool(Attribute::AttrKind)> &AttrFn)
Helper function which updates Flags when AttrFn returns true.
static void buildCopyToRegs(MachineIRBuilder &B, ArrayRef< Register > DstRegs, Register SrcReg, LLT SrcTy, LLT PartTy, unsigned ExtendOp=TargetOpcode::G_ANYEXT)
Create a sequence of instructions to expand the value in SrcReg (of type SrcTy) to the types in DstRe...
static MachineInstrBuilder mergeVectorRegsToResultRegs(MachineIRBuilder &B, ArrayRef< Register > DstRegs, ArrayRef< Register > SrcRegs)
Pack values SrcRegs to cover the vector type result DstRegs.
static void buildCopyFromRegs(MachineIRBuilder &B, ArrayRef< Register > OrigRegs, ArrayRef< Register > Regs, LLT LLTy, LLT PartLLT, const ISD::ArgFlagsTy Flags)
Create a sequence of instructions to combine pieces split into register typed values to the original ...
static bool isCopyCompatibleType(LLT SrcTy, LLT DstTy)
Check if we can use a basic COPY instruction between the two types.
static unsigned extendOpFromFlags(llvm::ISD::ArgFlagsTy Flags)
This file describes how to lower LLVM calls to machine code calls.
return RetTy
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Addr
uint64_t Size
static unsigned NumFixedArgs
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file declares the MachineIRBuilder class.
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
Module.h This file contains the declarations for the Module class.
R600 Clause Merge
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file describes how to lower LLVM code to machine code.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition: ArrayRef.h:228
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:204
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:168
iterator end() const
Definition: ArrayRef.h:154
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
iterator begin() const
Definition: ArrayRef.h:153
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
StringRef getValueAsString() const
Return the attribute's value as a string.
Definition: Attributes.cpp:391
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:86
CCState - This class holds information needed while lowering arguments and return values.
CallingConv::ID getCallingConv() const
LLVMContext & getContext() const
CCValAssign - Represent assignment of one arg/retval to a location.
bool isRegLoc() const
Register getLocReg() const
LocInfo getLocInfo() const
bool needsCustom() const
bool isMemLoc() const
int64_t getLocMemOffset() const
unsigned getValNo() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1236
MaybeAlign getRetAlign() const
Extract the alignment of the return value.
Definition: InstrTypes.h:1829
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Definition: InstrTypes.h:2143
CallingConv::ID getCallingConv() const
Definition: InstrTypes.h:1523
bool isMustTailCall() const
Tests if this call site must be tail call optimized.
bool isIndirectCall() const
Return true if the callsite is an indirect call.
Value * getCalledOperand() const
Definition: InstrTypes.h:1458
bool isConvergent() const
Determine if the invoke is convergent.
Definition: InstrTypes.h:2027
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1323
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition: InstrTypes.h:1401
AttributeList getAttributes() const
Return the parameter attributes for this call.
Definition: InstrTypes.h:1542
bool isTailCall() const
Tests if this call site is marked as a tail call.
bool handleAssignments(ValueHandler &Handler, SmallVectorImpl< ArgInfo > &Args, CCState &CCState, SmallVectorImpl< CCValAssign > &ArgLocs, MachineIRBuilder &MIRBuilder, ArrayRef< Register > ThisReturnRegs=std::nullopt) const
Use Handler to insert code to handle the argument/return values represented by Args.
void insertSRetOutgoingArgument(MachineIRBuilder &MIRBuilder, const CallBase &CB, CallLoweringInfo &Info) const
For the call-base described by CB, insert the hidden sret ArgInfo to the OrigArgs field of Info.
void insertSRetLoads(MachineIRBuilder &MIRBuilder, Type *RetTy, ArrayRef< Register > VRegs, Register DemoteReg, int FI) const
Load the returned value from the stack into virtual registers in VRegs.
bool checkReturnTypeForCallConv(MachineFunction &MF) const
Toplevel function to check the return type based on the target calling convention.
bool determineAndHandleAssignments(ValueHandler &Handler, ValueAssigner &Assigner, SmallVectorImpl< ArgInfo > &Args, MachineIRBuilder &MIRBuilder, CallingConv::ID CallConv, bool IsVarArg, ArrayRef< Register > ThisReturnRegs=std::nullopt) const
Invoke ValueAssigner::assignArg on each of the given Args and then use Handler to move them to the as...
bool resultsCompatible(CallLoweringInfo &Info, MachineFunction &MF, SmallVectorImpl< ArgInfo > &InArgs, ValueAssigner &CalleeAssigner, ValueAssigner &CallerAssigner) const
void splitToValueTypes(const ArgInfo &OrigArgInfo, SmallVectorImpl< ArgInfo > &SplitArgs, const DataLayout &DL, CallingConv::ID CallConv, SmallVectorImpl< uint64_t > *Offsets=nullptr) const
Break OrigArgInfo into one or more pieces the calling convention can process, returned in SplitArgs.
virtual bool canLowerReturn(MachineFunction &MF, CallingConv::ID CallConv, SmallVectorImpl< BaseArgInfo > &Outs, bool IsVarArg) const
This hook must be implemented to check whether the return values described by Outs can fit into the r...
Definition: CallLowering.h:506
virtual bool isTypeIsValidForThisReturn(EVT Ty) const
For targets which support the "returned" parameter attribute, returns true if the given type is a val...
Definition: CallLowering.h:607
void insertSRetIncomingArgument(const Function &F, SmallVectorImpl< ArgInfo > &SplitArgs, Register &DemoteReg, MachineRegisterInfo &MRI, const DataLayout &DL) const
Insert the hidden sret ArgInfo to the beginning of SplitArgs.
ISD::ArgFlagsTy getAttributesForArgIdx(const CallBase &Call, unsigned ArgIdx) const
void insertSRetStores(MachineIRBuilder &MIRBuilder, Type *RetTy, ArrayRef< Register > VRegs, Register DemoteReg) const
Store the return value given by VRegs into stack starting at the offset specified in DemoteReg.
void addArgFlagsFromAttributes(ISD::ArgFlagsTy &Flags, const AttributeList &Attrs, unsigned OpIdx) const
Adds flags to Flags based off of the attributes in Attrs.
bool parametersInCSRMatch(const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< ArgInfo > &OutVals) const
Check whether parameters to a call that are passed in callee saved registers are the same as from the...
void getReturnInfo(CallingConv::ID CallConv, Type *RetTy, AttributeList Attrs, SmallVectorImpl< BaseArgInfo > &Outs, const DataLayout &DL) const
Get the type and the ArgFlags for the split components of RetTy as returned by ComputeValueVTs.
bool determineAssignments(ValueAssigner &Assigner, SmallVectorImpl< ArgInfo > &Args, CCState &CCInfo) const
Analyze the argument list in Args, using Assigner to populate CCInfo.
bool checkReturn(CCState &CCInfo, SmallVectorImpl< BaseArgInfo > &Outs, CCAssignFn *Fn) const
const TargetLowering * getTLI() const
Getter for generic TargetLowering class.
Definition: CallLowering.h:354
virtual bool lowerCall(MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info) const
This hook must be implemented to lower the given call instruction, including argument and return valu...
Definition: CallLowering.h:566
void setArgFlags(ArgInfo &Arg, unsigned OpIdx, const DataLayout &DL, const FuncInfoTy &FuncInfo) const
ISD::ArgFlagsTy getAttributesForReturn(const CallBase &Call) const
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
unsigned getAllocaAddrSpace() const
Definition: DataLayout.h:276
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:142
bool isVarArg() const
Definition: DerivedTypes.h:123
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.cpp:716
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:381
constexpr unsigned getScalarSizeInBits() const
Definition: LowLevelType.h:267
constexpr bool isScalar() const
Definition: LowLevelType.h:146
constexpr LLT changeElementType(LLT NewEltTy) const
If this type is a vector, return a vector with the same number of elements but the new element type.
Definition: LowLevelType.h:214
static constexpr LLT vector(ElementCount EC, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
Definition: LowLevelType.h:64
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
Definition: LowLevelType.h:42
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
Definition: LowLevelType.h:159
constexpr bool isVector() const
Definition: LowLevelType.h:148
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
Definition: LowLevelType.h:57
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
Definition: LowLevelType.h:193
constexpr bool isPointer() const
Definition: LowLevelType.h:149
constexpr LLT getElementType() const
Returns the vector's element type. Only valid for vector types.
Definition: LowLevelType.h:290
constexpr ElementCount getElementCount() const
Definition: LowLevelType.h:184
constexpr unsigned getAddressSpace() const
Definition: LowLevelType.h:280
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
Definition: LowLevelType.h:100
constexpr LLT changeElementCount(ElementCount EC) const
Return a vector or scalar with the same element type and the new element count.
Definition: LowLevelType.h:230
constexpr LLT getScalarType() const
Definition: LowLevelType.h:208
constexpr TypeSize getSizeInBytes() const
Returns the total size of the type in bytes, i.e.
Definition: LowLevelType.h:203
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
Machine Value Type.
bool isVector() const
Return true if this is a vector value type.
static MVT getVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
Definition: ValueTypes.cpp:230
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy, Align base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Helper class to build MachineInstr.
MachineInstrBuilder buildGlobalValue(const DstOp &Res, const GlobalValue *GV)
Build and insert Res = G_GLOBAL_VALUE GV.
std::optional< MachineInstrBuilder > materializePtrAdd(Register &Res, Register Op0, const LLT ValueTy, uint64_t Value)
Materialize and insert Res = G_PTR_ADD Op0, (G_CONSTANT Value)
MachineInstrBuilder buildSExt(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_SEXT Op.
MachineInstrBuilder buildZExt(const DstOp &Res, const SrcOp &Op, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_ZEXT Op.
MachineInstrBuilder buildAssertZExt(const DstOp &Res, const SrcOp &Op, unsigned Size)
Build and insert Res = G_ASSERT_ZEXT Op, Size.
MachineInstrBuilder buildLoad(const DstOp &Res, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert Res = G_LOAD Addr, MMO.
MachineInstrBuilder buildStore(const SrcOp &Val, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert G_STORE Val, Addr, MMO.
MachineInstrBuilder buildFrameIndex(const DstOp &Res, int Idx)
Build and insert Res = G_FRAME_INDEX Idx.
MachineFunction & getMF()
Getter for the function we currently build.
MachineInstrBuilder buildMemCpy(const SrcOp &DstPtr, const SrcOp &SrcPtr, const SrcOp &Size, MachineMemOperand &DstMMO, MachineMemOperand &SrcMMO)
MachineInstrBuilder buildAssertAlign(const DstOp &Res, const SrcOp &Op, Align AlignVal)
Build and insert Res = G_ASSERT_ALIGN Op, AlignVal.
MachineInstrBuilder buildTrunc(const DstOp &Res, const SrcOp &Op, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_TRUNC Op.
MachineInstrBuilder buildAnyExt(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_ANYEXT Op0.
MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op)
Build and insert Res = COPY Op.
const DataLayout & getDataLayout() const
MachineInstrBuilder buildAssertSExt(const DstOp &Res, const SrcOp &Op, unsigned Size)
Build and insert Res = G_ASSERT_SEXT Op, Size.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
MachineInstrBuilder buildPtrToInt(const DstOp &Dst, const SrcOp &Src)
Build and insert a G_PTRTOINT instruction.
Register getReg(unsigned Idx) const
Get the register for the operand index.
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:569
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:579
A description of a memory reference used in the backend.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Class to represent pointers.
Definition: DerivedTypes.h:646
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void reserve(size_type N)
Definition: SmallVector.h:676
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:818
void truncate(size_type N)
Like resize, but requires that N is less than size().
Definition: SmallVector.h:657
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const
When splitting a value of the specified type into parts, does the Lo or Hi part come first?...
virtual bool functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv, bool isVarArg, const DataLayout &DL) const
For some targets, an LLVM struct type must be broken down into multiple simple types,...
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:348
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:693
constexpr ScalarTy getFixedValue() const
Definition: TypeSize.h:199
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition: TypeSize.h:215
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition: TypeSize.h:222
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition: MathExtras.h:431
void * PointerTy
Definition: GenericValue.h:21
MachineInstr * getDefIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the def instruction for Reg, folding away any trivial copies.
Definition: Utils.cpp:479
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
LLVM_READNONE LLT getCoverTy(LLT OrigTy, LLT TargetTy)
Return smallest type that covers both OrigTy and TargetTy and is multiple of TargetTy.
Definition: Utils.cpp:1226
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
void ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, Type *Ty, SmallVectorImpl< EVT > &ValueVTs, SmallVectorImpl< EVT > *MemVTs, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
ComputeValueVTs - Given an LLVM IR type, compute a sequence of EVTs that represent all the individual...
Definition: Analysis.cpp:79
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition: Alignment.h:212
bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition: Analysis.cpp:535
LLVM_READNONE LLT getGCDType(LLT OrigTy, LLT TargetTy)
Return a type where the total size is the greatest common divisor of OrigTy and TargetTy.
Definition: Utils.cpp:1247
LLT getLLTForType(Type &Ty, const DataLayout &DL)
Construct a low-level type based on an LLVM type.
Align inferAlignFromPtrInfo(MachineFunction &MF, const MachinePointerInfo &MPO)
Definition: Utils.cpp:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
const Value * OrigValue
Optionally track the original IR value for the argument.
Definition: CallLowering.h:73
SmallVector< Register, 4 > Regs
Definition: CallLowering.h:63
unsigned OrigArgIndex
Index original Function's argument.
Definition: CallLowering.h:76
static const unsigned NoArgIndex
Sentinel value for implicit machine-level input arguments.
Definition: CallLowering.h:79
SmallVector< ISD::ArgFlagsTy, 4 > Flags
Definition: CallLowering.h:51
void assignValueToReg(Register ValVReg, Register PhysReg, const CCValAssign &VA) override
Provides a default implementation for argument handling.
Register buildExtensionHint(const CCValAssign &VA, Register SrcReg, LLT NarrowTy)
Insert G_ASSERT_ZEXT/G_ASSERT_SEXT or other hint instruction based on VA, returning the new register ...
Argument handling is mostly uniform between the four places that make these decisions: function forma...
Definition: CallLowering.h:175
virtual bool assignArg(unsigned ValNo, EVT OrigVT, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, const ArgInfo &Info, ISD::ArgFlagsTy Flags, CCState &State)
Wrap call to (typically tablegenerated CCAssignFn).
Definition: CallLowering.h:199
void copyArgumentMemory(const ArgInfo &Arg, Register DstPtr, Register SrcPtr, const MachinePointerInfo &DstPtrInfo, Align DstAlign, const MachinePointerInfo &SrcPtrInfo, Align SrcAlign, uint64_t MemSize, CCValAssign &VA) const
Do a memory copy of MemSize bytes from SrcPtr to DstPtr.
virtual Register getStackAddress(uint64_t MemSize, int64_t Offset, MachinePointerInfo &MPO, ISD::ArgFlagsTy Flags)=0
Materialize a VReg containing the address of the specified stack-based object.
virtual LLT getStackValueStoreType(const DataLayout &DL, const CCValAssign &VA, ISD::ArgFlagsTy Flags) const
Return the in-memory size to write for the argument at VA.
bool isIncomingArgumentHandler() const
Returns true if the handler is dealing with incoming arguments, i.e.
Definition: CallLowering.h:256
virtual void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy, const MachinePointerInfo &MPO, const CCValAssign &VA)=0
The specified value has been assigned to a stack location.
Register extendRegister(Register ValReg, const CCValAssign &VA, unsigned MaxSizeBits=0)
Extend a register to the location type given in VA, capped at extending to at most MaxSize bits.
virtual unsigned assignCustomValue(ArgInfo &Arg, ArrayRef< CCValAssign > VAs, std::function< void()> *Thunk=nullptr)
Handle custom values, which may be passed into one or more of VAs.
Definition: CallLowering.h:308
virtual void assignValueToReg(Register ValVReg, Register PhysReg, const CCValAssign &VA)=0
The specified value has been assigned to a physical register, handle the appropriate COPY (either to ...
Extended Value Type.
Definition: ValueTypes.h:34
static EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
Definition: ValueTypes.cpp:274
Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
Definition: ValueTypes.cpp:203
This class contains a discriminated union of information about pointers in memory operands,...
static MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117