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