1 //===- llvm/CallingConvLower.h - Calling Conventions ------------*- C++ -*-===//
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 // This file declares the CCState and CCValAssign classes, used for lowering
10 // and implementing calling conventions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CODEGEN_CALLINGCONVLOWER_H
15 #define LLVM_CODEGEN_CALLINGCONVLOWER_H
16 
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/Register.h"
20 #include "llvm/CodeGen/TargetCallingConv.h"
21 #include "llvm/IR/CallingConv.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/Support/Alignment.h"
24 
25 namespace llvm {
26 
27 class CCState;
28 class MachineFunction;
29 class MVT;
30 class TargetRegisterInfo;
31 
32 /// CCValAssign - Represent assignment of one arg/retval to a location.
33 class CCValAssign {
34 public:
35   enum LocInfo {
36     Full,      // The value fills the full location.
37     SExt,      // The value is sign extended in the location.
38     ZExt,      // The value is zero extended in the location.
39     AExt,      // The value is extended with undefined upper bits.
40     SExtUpper, // The value is in the upper bits of the location and should be
41                // sign extended when retrieved.
42     ZExtUpper, // The value is in the upper bits of the location and should be
43                // zero extended when retrieved.
44     AExtUpper, // The value is in the upper bits of the location and should be
45                // extended with undefined upper bits when retrieved.
46     BCvt,      // The value is bit-converted in the location.
47     Trunc,     // The value is truncated in the location.
48     VExt,      // The value is vector-widened in the location.
49                // FIXME: Not implemented yet. Code that uses AExt to mean
50                // vector-widen should be fixed to use VExt instead.
51     FPExt,     // The floating-point value is fp-extended in the location.
52     Indirect   // The location contains pointer to the value.
53     // TODO: a subset of the value is in the location.
54   };
55 
56 private:
57   /// ValNo - This is the value number being assigned (e.g. an argument number).
58   unsigned ValNo;
59 
60   /// Loc is either a stack offset or a register number.
61   unsigned Loc;
62 
63   /// isMem - True if this is a memory loc, false if it is a register loc.
64   unsigned isMem : 1;
65 
66   /// isCustom - True if this arg/retval requires special handling.
67   unsigned isCustom : 1;
68 
69   /// Information about how the value is assigned.
70   LocInfo HTP : 6;
71 
72   /// ValVT - The type of the value being assigned.
73   MVT ValVT;
74 
75   /// LocVT - The type of the location being assigned to.
76   MVT LocVT;
77 public:
78 
79   static CCValAssign getReg(unsigned ValNo, MVT ValVT,
80                             unsigned RegNo, MVT LocVT,
81                             LocInfo HTP) {
82     CCValAssign Ret;
83     Ret.ValNo = ValNo;
84     Ret.Loc = RegNo;
85     Ret.isMem = false;
86     Ret.isCustom = false;
87     Ret.HTP = HTP;
88     Ret.ValVT = ValVT;
89     Ret.LocVT = LocVT;
90     return Ret;
91   }
92 
93   static CCValAssign getCustomReg(unsigned ValNo, MVT ValVT,
94                                   unsigned RegNo, MVT LocVT,
95                                   LocInfo HTP) {
96     CCValAssign Ret;
97     Ret = getReg(ValNo, ValVT, RegNo, LocVT, HTP);
98     Ret.isCustom = true;
99     return Ret;
100   }
101 
102   static CCValAssign getMem(unsigned ValNo, MVT ValVT,
103                             unsigned Offset, MVT LocVT,
104                             LocInfo HTP) {
105     CCValAssign Ret;
106     Ret.ValNo = ValNo;
107     Ret.Loc = Offset;
108     Ret.isMem = true;
109     Ret.isCustom = false;
110     Ret.HTP = HTP;
111     Ret.ValVT = ValVT;
112     Ret.LocVT = LocVT;
113     return Ret;
114   }
115 
116   static CCValAssign getCustomMem(unsigned ValNo, MVT ValVT,
117                                   unsigned Offset, MVT LocVT,
118                                   LocInfo HTP) {
119     CCValAssign Ret;
120     Ret = getMem(ValNo, ValVT, Offset, LocVT, HTP);
121     Ret.isCustom = true;
122     return Ret;
123   }
124 
125   // There is no need to differentiate between a pending CCValAssign and other
126   // kinds, as they are stored in a different list.
127   static CCValAssign getPending(unsigned ValNo, MVT ValVT, MVT LocVT,
128                                 LocInfo HTP, unsigned ExtraInfo = 0) {
129     return getReg(ValNo, ValVT, ExtraInfo, LocVT, HTP);
130   }
131 
132   void convertToReg(unsigned RegNo) {
133     Loc = RegNo;
134     isMem = false;
135   }
136 
137   void convertToMem(unsigned Offset) {
138     Loc = Offset;
139     isMem = true;
140   }
141 
142   unsigned getValNo() const { return ValNo; }
143   MVT getValVT() const { return ValVT; }
144 
145   bool isRegLoc() const { return !isMem; }
146   bool isMemLoc() const { return isMem; }
147 
148   bool needsCustom() const { return isCustom; }
149 
150   Register getLocReg() const { assert(isRegLoc()); return Loc; }
151   unsigned getLocMemOffset() const { assert(isMemLoc()); return Loc; }
152   unsigned getExtraInfo() const { return Loc; }
153   MVT getLocVT() const { return LocVT; }
154 
155   LocInfo getLocInfo() const { return HTP; }
156   bool isExtInLoc() const {
157     return (HTP == AExt || HTP == SExt || HTP == ZExt);
158   }
159 
160   bool isUpperBitsInLoc() const {
161     return HTP == AExtUpper || HTP == SExtUpper || HTP == ZExtUpper;
162   }
163 };
164 
165 /// Describes a register that needs to be forwarded from the prologue to a
166 /// musttail call.
167 struct ForwardedRegister {
168   ForwardedRegister(Register VReg, MCPhysReg PReg, MVT VT)
169       : VReg(VReg), PReg(PReg), VT(VT) {}
170   Register VReg;
171   MCPhysReg PReg;
172   MVT VT;
173 };
174 
175 /// CCAssignFn - This function assigns a location for Val, updating State to
176 /// reflect the change.  It returns 'true' if it failed to handle Val.
177 typedef bool CCAssignFn(unsigned ValNo, MVT ValVT,
178                         MVT LocVT, CCValAssign::LocInfo LocInfo,
179                         ISD::ArgFlagsTy ArgFlags, CCState &State);
180 
181 /// CCCustomFn - This function assigns a location for Val, possibly updating
182 /// all args to reflect changes and indicates if it handled it. It must set
183 /// isCustom if it handles the arg and returns true.
184 typedef bool CCCustomFn(unsigned &ValNo, MVT &ValVT,
185                         MVT &LocVT, CCValAssign::LocInfo &LocInfo,
186                         ISD::ArgFlagsTy &ArgFlags, CCState &State);
187 
188 /// CCState - This class holds information needed while lowering arguments and
189 /// return values.  It captures which registers are already assigned and which
190 /// stack slots are used.  It provides accessors to allocate these values.
191 class CCState {
192 private:
193   CallingConv::ID CallingConv;
194   bool IsVarArg;
195   bool AnalyzingMustTailForwardedRegs = false;
196   MachineFunction &MF;
197   const TargetRegisterInfo &TRI;
198   SmallVectorImpl<CCValAssign> &Locs;
199   LLVMContext &Context;
200 
201   unsigned StackOffset;
202   Align MaxStackArgAlign;
203   SmallVector<uint32_t, 16> UsedRegs;
204   SmallVector<CCValAssign, 4> PendingLocs;
205   SmallVector<ISD::ArgFlagsTy, 4> PendingArgFlags;
206 
207   // ByValInfo and SmallVector<ByValInfo, 4> ByValRegs:
208   //
209   // Vector of ByValInfo instances (ByValRegs) is introduced for byval registers
210   // tracking.
211   // Or, in another words it tracks byval parameters that are stored in
212   // general purpose registers.
213   //
214   // For 4 byte stack alignment,
215   // instance index means byval parameter number in formal
216   // arguments set. Assume, we have some "struct_type" with size = 4 bytes,
217   // then, for function "foo":
218   //
219   // i32 foo(i32 %p, %struct_type* %r, i32 %s, %struct_type* %t)
220   //
221   // ByValRegs[0] describes how "%r" is stored (Begin == r1, End == r2)
222   // ByValRegs[1] describes how "%t" is stored (Begin == r3, End == r4).
223   //
224   // In case of 8 bytes stack alignment,
225   // In function shown above, r3 would be wasted according to AAPCS rules.
226   // ByValRegs vector size still would be 2,
227   // while "%t" goes to the stack: it wouldn't be described in ByValRegs.
228   //
229   // Supposed use-case for this collection:
230   // 1. Initially ByValRegs is empty, InRegsParamsProcessed is 0.
231   // 2. HandleByVal fills up ByValRegs.
232   // 3. Argument analysis (LowerFormatArguments, for example). After
233   // some byval argument was analyzed, InRegsParamsProcessed is increased.
234   struct ByValInfo {
235     ByValInfo(unsigned B, unsigned E) : Begin(B), End(E) {}
236 
237     // First register allocated for current parameter.
238     unsigned Begin;
239 
240     // First after last register allocated for current parameter.
241     unsigned End;
242   };
243   SmallVector<ByValInfo, 4 > ByValRegs;
244 
245   // InRegsParamsProcessed - shows how many instances of ByValRegs was proceed
246   // during argument analysis.
247   unsigned InRegsParamsProcessed;
248 
249 public:
250   CCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
251           SmallVectorImpl<CCValAssign> &locs, LLVMContext &C);
252 
253   void addLoc(const CCValAssign &V) {
254     Locs.push_back(V);
255   }
256 
257   LLVMContext &getContext() const { return Context; }
258   MachineFunction &getMachineFunction() const { return MF; }
259   CallingConv::ID getCallingConv() const { return CallingConv; }
260   bool isVarArg() const { return IsVarArg; }
261 
262   /// getNextStackOffset - Return the next stack offset such that all stack
263   /// slots satisfy their alignment requirements.
264   unsigned getNextStackOffset() const {
265     return StackOffset;
266   }
267 
268   /// getAlignedCallFrameSize - Return the size of the call frame needed to
269   /// be able to store all arguments and such that the alignment requirement
270   /// of each of the arguments is satisfied.
271   unsigned getAlignedCallFrameSize() const {
272     return alignTo(StackOffset, MaxStackArgAlign);
273   }
274 
275   /// isAllocated - Return true if the specified register (or an alias) is
276   /// allocated.
277   bool isAllocated(MCRegister Reg) const {
278     return UsedRegs[Reg / 32] & (1 << (Reg & 31));
279   }
280 
281   /// AnalyzeFormalArguments - Analyze an array of argument values,
282   /// incorporating info about the formals into this state.
283   void AnalyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
284                               CCAssignFn Fn);
285 
286   /// The function will invoke AnalyzeFormalArguments.
287   void AnalyzeArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
288                         CCAssignFn Fn) {
289     AnalyzeFormalArguments(Ins, Fn);
290   }
291 
292   /// AnalyzeReturn - Analyze the returned values of a return,
293   /// incorporating info about the result values into this state.
294   void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
295                      CCAssignFn Fn);
296 
297   /// CheckReturn - Analyze the return values of a function, returning
298   /// true if the return can be performed without sret-demotion, and
299   /// false otherwise.
300   bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
301                    CCAssignFn Fn);
302 
303   /// AnalyzeCallOperands - Analyze the outgoing arguments to a call,
304   /// incorporating info about the passed values into this state.
305   void AnalyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Outs,
306                            CCAssignFn Fn);
307 
308   /// AnalyzeCallOperands - Same as above except it takes vectors of types
309   /// and argument flags.
310   void AnalyzeCallOperands(SmallVectorImpl<MVT> &ArgVTs,
311                            SmallVectorImpl<ISD::ArgFlagsTy> &Flags,
312                            CCAssignFn Fn);
313 
314   /// The function will invoke AnalyzeCallOperands.
315   void AnalyzeArguments(const SmallVectorImpl<ISD::OutputArg> &Outs,
316                         CCAssignFn Fn) {
317     AnalyzeCallOperands(Outs, Fn);
318   }
319 
320   /// AnalyzeCallResult - Analyze the return values of a call,
321   /// incorporating info about the passed values into this state.
322   void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
323                          CCAssignFn Fn);
324 
325   /// A shadow allocated register is a register that was allocated
326   /// but wasn't added to the location list (Locs).
327   /// \returns true if the register was allocated as shadow or false otherwise.
328   bool IsShadowAllocatedReg(MCRegister Reg) const;
329 
330   /// AnalyzeCallResult - Same as above except it's specialized for calls which
331   /// produce a single value.
332   void AnalyzeCallResult(MVT VT, CCAssignFn Fn);
333 
334   /// getFirstUnallocated - Return the index of the first unallocated register
335   /// in the set, or Regs.size() if they are all allocated.
336   unsigned getFirstUnallocated(ArrayRef<MCPhysReg> Regs) const {
337     for (unsigned i = 0; i < Regs.size(); ++i)
338       if (!isAllocated(Regs[i]))
339         return i;
340     return Regs.size();
341   }
342 
343   void DeallocateReg(MCPhysReg Reg) {
344     assert(isAllocated(Reg) && "Trying to deallocate an unallocated register");
345     MarkUnallocated(Reg);
346   }
347 
348   /// AllocateReg - Attempt to allocate one register.  If it is not available,
349   /// return zero.  Otherwise, return the register, marking it and any aliases
350   /// as allocated.
351   MCRegister AllocateReg(MCPhysReg Reg) {
352     if (isAllocated(Reg))
353       return MCRegister();
354     MarkAllocated(Reg);
355     return Reg;
356   }
357 
358   /// Version of AllocateReg with extra register to be shadowed.
359   MCRegister AllocateReg(MCPhysReg Reg, MCPhysReg ShadowReg) {
360     if (isAllocated(Reg))
361       return MCRegister();
362     MarkAllocated(Reg);
363     MarkAllocated(ShadowReg);
364     return Reg;
365   }
366 
367   /// AllocateReg - Attempt to allocate one of the specified registers.  If none
368   /// are available, return zero.  Otherwise, return the first one available,
369   /// marking it and any aliases as allocated.
370   MCPhysReg AllocateReg(ArrayRef<MCPhysReg> Regs) {
371     unsigned FirstUnalloc = getFirstUnallocated(Regs);
372     if (FirstUnalloc == Regs.size())
373       return MCRegister();    // Didn't find the reg.
374 
375     // Mark the register and any aliases as allocated.
376     MCPhysReg Reg = Regs[FirstUnalloc];
377     MarkAllocated(Reg);
378     return Reg;
379   }
380 
381   /// AllocateRegBlock - Attempt to allocate a block of RegsRequired consecutive
382   /// registers. If this is not possible, return zero. Otherwise, return the first
383   /// register of the block that were allocated, marking the entire block as allocated.
384   MCPhysReg AllocateRegBlock(ArrayRef<MCPhysReg> Regs, unsigned RegsRequired) {
385     if (RegsRequired > Regs.size())
386       return 0;
387 
388     for (unsigned StartIdx = 0; StartIdx <= Regs.size() - RegsRequired;
389          ++StartIdx) {
390       bool BlockAvailable = true;
391       // Check for already-allocated regs in this block
392       for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) {
393         if (isAllocated(Regs[StartIdx + BlockIdx])) {
394           BlockAvailable = false;
395           break;
396         }
397       }
398       if (BlockAvailable) {
399         // Mark the entire block as allocated
400         for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) {
401           MarkAllocated(Regs[StartIdx + BlockIdx]);
402         }
403         return Regs[StartIdx];
404       }
405     }
406     // No block was available
407     return 0;
408   }
409 
410   /// Version of AllocateReg with list of registers to be shadowed.
411   MCRegister AllocateReg(ArrayRef<MCPhysReg> Regs, const MCPhysReg *ShadowRegs) {
412     unsigned FirstUnalloc = getFirstUnallocated(Regs);
413     if (FirstUnalloc == Regs.size())
414       return MCRegister();    // Didn't find the reg.
415 
416     // Mark the register and any aliases as allocated.
417     MCRegister Reg = Regs[FirstUnalloc], ShadowReg = ShadowRegs[FirstUnalloc];
418     MarkAllocated(Reg);
419     MarkAllocated(ShadowReg);
420     return Reg;
421   }
422 
423   /// AllocateStack - Allocate a chunk of stack space with the specified size
424   /// and alignment.
425   unsigned AllocateStack(unsigned Size, Align Alignment) {
426     StackOffset = alignTo(StackOffset, Alignment);
427     unsigned Result = StackOffset;
428     StackOffset += Size;
429     MaxStackArgAlign = std::max(Alignment, MaxStackArgAlign);
430     ensureMaxAlignment(Alignment);
431     return Result;
432   }
433 
434   void ensureMaxAlignment(Align Alignment);
435 
436   /// Version of AllocateStack with list of extra registers to be shadowed.
437   /// Note that, unlike AllocateReg, this shadows ALL of the shadow registers.
438   unsigned AllocateStack(unsigned Size, Align Alignment,
439                          ArrayRef<MCPhysReg> ShadowRegs) {
440     for (unsigned i = 0; i < ShadowRegs.size(); ++i)
441       MarkAllocated(ShadowRegs[i]);
442     return AllocateStack(Size, Alignment);
443   }
444 
445   // HandleByVal - Allocate a stack slot large enough to pass an argument by
446   // value. The size and alignment information of the argument is encoded in its
447   // parameter attribute.
448   void HandleByVal(unsigned ValNo, MVT ValVT, MVT LocVT,
449                    CCValAssign::LocInfo LocInfo, int MinSize, Align MinAlign,
450                    ISD::ArgFlagsTy ArgFlags);
451 
452   // Returns count of byval arguments that are to be stored (even partly)
453   // in registers.
454   unsigned getInRegsParamsCount() const { return ByValRegs.size(); }
455 
456   // Returns count of byval in-regs arguments processed.
457   unsigned getInRegsParamsProcessed() const { return InRegsParamsProcessed; }
458 
459   // Get information about N-th byval parameter that is stored in registers.
460   // Here "ByValParamIndex" is N.
461   void getInRegsParamInfo(unsigned InRegsParamRecordIndex,
462                           unsigned& BeginReg, unsigned& EndReg) const {
463     assert(InRegsParamRecordIndex < ByValRegs.size() &&
464            "Wrong ByVal parameter index");
465 
466     const ByValInfo& info = ByValRegs[InRegsParamRecordIndex];
467     BeginReg = info.Begin;
468     EndReg = info.End;
469   }
470 
471   // Add information about parameter that is kept in registers.
472   void addInRegsParamInfo(unsigned RegBegin, unsigned RegEnd) {
473     ByValRegs.push_back(ByValInfo(RegBegin, RegEnd));
474   }
475 
476   // Goes either to next byval parameter (excluding "waste" record), or
477   // to the end of collection.
478   // Returns false, if end is reached.
479   bool nextInRegsParam() {
480     unsigned e = ByValRegs.size();
481     if (InRegsParamsProcessed < e)
482       ++InRegsParamsProcessed;
483     return InRegsParamsProcessed < e;
484   }
485 
486   // Clear byval registers tracking info.
487   void clearByValRegsInfo() {
488     InRegsParamsProcessed = 0;
489     ByValRegs.clear();
490   }
491 
492   // Rewind byval registers tracking info.
493   void rewindByValRegsInfo() {
494     InRegsParamsProcessed = 0;
495   }
496 
497   // Get list of pending assignments
498   SmallVectorImpl<CCValAssign> &getPendingLocs() {
499     return PendingLocs;
500   }
501 
502   // Get a list of argflags for pending assignments.
503   SmallVectorImpl<ISD::ArgFlagsTy> &getPendingArgFlags() {
504     return PendingArgFlags;
505   }
506 
507   /// Compute the remaining unused register parameters that would be used for
508   /// the given value type. This is useful when varargs are passed in the
509   /// registers that normal prototyped parameters would be passed in, or for
510   /// implementing perfect forwarding.
511   void getRemainingRegParmsForType(SmallVectorImpl<MCPhysReg> &Regs, MVT VT,
512                                    CCAssignFn Fn);
513 
514   /// Compute the set of registers that need to be preserved and forwarded to
515   /// any musttail calls.
516   void analyzeMustTailForwardedRegisters(
517       SmallVectorImpl<ForwardedRegister> &Forwards, ArrayRef<MVT> RegParmTypes,
518       CCAssignFn Fn);
519 
520   /// Returns true if the results of the two calling conventions are compatible.
521   /// This is usually part of the check for tailcall eligibility.
522   static bool resultsCompatible(CallingConv::ID CalleeCC,
523                                 CallingConv::ID CallerCC, MachineFunction &MF,
524                                 LLVMContext &C,
525                                 const SmallVectorImpl<ISD::InputArg> &Ins,
526                                 CCAssignFn CalleeFn, CCAssignFn CallerFn);
527 
528   /// The function runs an additional analysis pass over function arguments.
529   /// It will mark each argument with the attribute flag SecArgPass.
530   /// After running, it will sort the locs list.
531   template <class T>
532   void AnalyzeArgumentsSecondPass(const SmallVectorImpl<T> &Args,
533                                   CCAssignFn Fn) {
534     unsigned NumFirstPassLocs = Locs.size();
535 
536     /// Creates similar argument list to \p Args in which each argument is
537     /// marked using SecArgPass flag.
538     SmallVector<T, 16> SecPassArg;
539     // SmallVector<ISD::InputArg, 16> SecPassArg;
540     for (auto Arg : Args) {
541       Arg.Flags.setSecArgPass();
542       SecPassArg.push_back(Arg);
543     }
544 
545     // Run the second argument pass
546     AnalyzeArguments(SecPassArg, Fn);
547 
548     // Sort the locations of the arguments according to their original position.
549     SmallVector<CCValAssign, 16> TmpArgLocs;
550     TmpArgLocs.swap(Locs);
551     auto B = TmpArgLocs.begin(), E = TmpArgLocs.end();
552     std::merge(B, B + NumFirstPassLocs, B + NumFirstPassLocs, E,
553                std::back_inserter(Locs),
554                [](const CCValAssign &A, const CCValAssign &B) -> bool {
555                  return A.getValNo() < B.getValNo();
556                });
557   }
558 
559 private:
560   /// MarkAllocated - Mark a register and all of its aliases as allocated.
561   void MarkAllocated(MCPhysReg Reg);
562 
563   void MarkUnallocated(MCPhysReg Reg);
564 };
565 
566 } // end namespace llvm
567 
568 #endif // LLVM_CODEGEN_CALLINGCONVLOWER_H
569