[Alignment][NFC] Migrate Instructions to Align
[llvm-core.git] / include / llvm / CodeGen / CallingConvLower.h
blob56da9b198017d32b3d02301d74a03704fe5173eb
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.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CODEGEN_CALLINGCONVLOWER_H
15 #define LLVM_CODEGEN_CALLINGCONVLOWER_H
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.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"
25 namespace llvm {
27 class CCState;
28 class MVT;
29 class TargetMachine;
30 class TargetRegisterInfo;
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.
56 private:
57 /// ValNo - This is the value number begin assigned (e.g. an argument number).
58 unsigned ValNo;
60 /// Loc is either a stack offset or a register number.
61 unsigned Loc;
63 /// isMem - True if this is a memory loc, false if it is a register loc.
64 unsigned isMem : 1;
66 /// isCustom - True if this arg/retval requires special handling.
67 unsigned isCustom : 1;
69 /// Information about how the value is assigned.
70 LocInfo HTP : 6;
72 /// ValVT - The type of the value being assigned.
73 MVT ValVT;
75 /// LocVT - The type of the location being assigned to.
76 MVT LocVT;
77 public:
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;
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;
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;
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;
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);
132 void convertToReg(unsigned RegNo) {
133 Loc = RegNo;
134 isMem = false;
137 void convertToMem(unsigned Offset) {
138 Loc = Offset;
139 isMem = true;
142 unsigned getValNo() const { return ValNo; }
143 MVT getValVT() const { return ValVT; }
145 bool isRegLoc() const { return !isMem; }
146 bool isMemLoc() const { return isMem; }
148 bool needsCustom() const { return isCustom; }
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; }
155 LocInfo getLocInfo() const { return HTP; }
156 bool isExtInLoc() const {
157 return (HTP == AExt || HTP == SExt || HTP == ZExt);
160 bool isUpperBitsInLoc() const {
161 return HTP == AExtUpper || HTP == SExtUpper || HTP == ZExtUpper;
165 /// Describes a register that needs to be forwarded from the prologue to a
166 /// musttail call.
167 struct ForwardedRegister {
168 ForwardedRegister(unsigned VReg, MCPhysReg PReg, MVT VT)
169 : VReg(VReg), PReg(PReg), VT(VT) {}
170 unsigned VReg;
171 MCPhysReg PReg;
172 MVT VT;
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);
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);
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;
201 unsigned StackOffset;
202 Align MaxStackArgAlign;
203 SmallVector<uint32_t, 16> UsedRegs;
204 SmallVector<CCValAssign, 4> PendingLocs;
205 SmallVector<ISD::ArgFlagsTy, 4> PendingArgFlags;
207 // ByValInfo and SmallVector<ByValInfo, 4> ByValRegs:
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.
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":
219 // i32 foo(i32 %p, %struct_type* %r, i32 %s, %struct_type* %t)
221 // ByValRegs[0] describes how "%r" is stored (Begin == r1, End == r2)
222 // ByValRegs[1] describes how "%t" is stored (Begin == r3, End == r4).
224 // In case of 8 bytes stack alignment,
225 // ByValRegs may also contain information about wasted registers.
226 // In function shown above, r3 would be wasted according to AAPCS rules.
227 // And in that case ByValRegs[1].Waste would be "true".
228 // ByValRegs vector size still would be 2,
229 // while "%t" goes to the stack: it wouldn't be described in ByValRegs.
231 // Supposed use-case for this collection:
232 // 1. Initially ByValRegs is empty, InRegsParamsProcessed is 0.
233 // 2. HandleByVal fillups ByValRegs.
234 // 3. Argument analysis (LowerFormatArguments, for example). After
235 // some byval argument was analyzed, InRegsParamsProcessed is increased.
236 struct ByValInfo {
237 ByValInfo(unsigned B, unsigned E, bool IsWaste = false) :
238 Begin(B), End(E), Waste(IsWaste) {}
239 // First register allocated for current parameter.
240 unsigned Begin;
242 // First after last register allocated for current parameter.
243 unsigned End;
245 // Means that current range of registers doesn't belong to any
246 // parameters. It was wasted due to stack alignment rules.
247 // For more information see:
248 // AAPCS, 5.5 Parameter Passing, Stage C, C.3.
249 bool Waste;
251 SmallVector<ByValInfo, 4 > ByValRegs;
253 // InRegsParamsProcessed - shows how many instances of ByValRegs was proceed
254 // during argument analysis.
255 unsigned InRegsParamsProcessed;
257 public:
258 CCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
259 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C);
261 void addLoc(const CCValAssign &V) {
262 Locs.push_back(V);
265 LLVMContext &getContext() const { return Context; }
266 MachineFunction &getMachineFunction() const { return MF; }
267 CallingConv::ID getCallingConv() const { return CallingConv; }
268 bool isVarArg() const { return IsVarArg; }
270 /// getNextStackOffset - Return the next stack offset such that all stack
271 /// slots satisfy their alignment requirements.
272 unsigned getNextStackOffset() const {
273 return StackOffset;
276 /// getAlignedCallFrameSize - Return the size of the call frame needed to
277 /// be able to store all arguments and such that the alignment requirement
278 /// of each of the arguments is satisfied.
279 unsigned getAlignedCallFrameSize() const {
280 return alignTo(StackOffset, MaxStackArgAlign);
283 /// isAllocated - Return true if the specified register (or an alias) is
284 /// allocated.
285 bool isAllocated(unsigned Reg) const {
286 return UsedRegs[Reg/32] & (1 << (Reg&31));
289 /// AnalyzeFormalArguments - Analyze an array of argument values,
290 /// incorporating info about the formals into this state.
291 void AnalyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
292 CCAssignFn Fn);
294 /// The function will invoke AnalyzeFormalArguments.
295 void AnalyzeArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
296 CCAssignFn Fn) {
297 AnalyzeFormalArguments(Ins, Fn);
300 /// AnalyzeReturn - Analyze the returned values of a return,
301 /// incorporating info about the result values into this state.
302 void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
303 CCAssignFn Fn);
305 /// CheckReturn - Analyze the return values of a function, returning
306 /// true if the return can be performed without sret-demotion, and
307 /// false otherwise.
308 bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
309 CCAssignFn Fn);
311 /// AnalyzeCallOperands - Analyze the outgoing arguments to a call,
312 /// incorporating info about the passed values into this state.
313 void AnalyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Outs,
314 CCAssignFn Fn);
316 /// AnalyzeCallOperands - Same as above except it takes vectors of types
317 /// and argument flags.
318 void AnalyzeCallOperands(SmallVectorImpl<MVT> &ArgVTs,
319 SmallVectorImpl<ISD::ArgFlagsTy> &Flags,
320 CCAssignFn Fn);
322 /// The function will invoke AnalyzeCallOperands.
323 void AnalyzeArguments(const SmallVectorImpl<ISD::OutputArg> &Outs,
324 CCAssignFn Fn) {
325 AnalyzeCallOperands(Outs, Fn);
328 /// AnalyzeCallResult - Analyze the return values of a call,
329 /// incorporating info about the passed values into this state.
330 void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
331 CCAssignFn Fn);
333 /// A shadow allocated register is a register that was allocated
334 /// but wasn't added to the location list (Locs).
335 /// \returns true if the register was allocated as shadow or false otherwise.
336 bool IsShadowAllocatedReg(unsigned Reg) const;
338 /// AnalyzeCallResult - Same as above except it's specialized for calls which
339 /// produce a single value.
340 void AnalyzeCallResult(MVT VT, CCAssignFn Fn);
342 /// getFirstUnallocated - Return the index of the first unallocated register
343 /// in the set, or Regs.size() if they are all allocated.
344 unsigned getFirstUnallocated(ArrayRef<MCPhysReg> Regs) const {
345 for (unsigned i = 0; i < Regs.size(); ++i)
346 if (!isAllocated(Regs[i]))
347 return i;
348 return Regs.size();
351 /// AllocateReg - Attempt to allocate one register. If it is not available,
352 /// return zero. Otherwise, return the register, marking it and any aliases
353 /// as allocated.
354 unsigned AllocateReg(unsigned Reg) {
355 if (isAllocated(Reg)) return 0;
356 MarkAllocated(Reg);
357 return Reg;
360 /// Version of AllocateReg with extra register to be shadowed.
361 unsigned AllocateReg(unsigned Reg, unsigned ShadowReg) {
362 if (isAllocated(Reg)) return 0;
363 MarkAllocated(Reg);
364 MarkAllocated(ShadowReg);
365 return Reg;
368 /// AllocateReg - Attempt to allocate one of the specified registers. If none
369 /// are available, return zero. Otherwise, return the first one available,
370 /// marking it and any aliases as allocated.
371 unsigned AllocateReg(ArrayRef<MCPhysReg> Regs) {
372 unsigned FirstUnalloc = getFirstUnallocated(Regs);
373 if (FirstUnalloc == Regs.size())
374 return 0; // Didn't find the reg.
376 // Mark the register and any aliases as allocated.
377 unsigned Reg = Regs[FirstUnalloc];
378 MarkAllocated(Reg);
379 return Reg;
382 /// AllocateRegBlock - Attempt to allocate a block of RegsRequired consecutive
383 /// registers. If this is not possible, return zero. Otherwise, return the first
384 /// register of the block that were allocated, marking the entire block as allocated.
385 unsigned AllocateRegBlock(ArrayRef<MCPhysReg> Regs, unsigned RegsRequired) {
386 if (RegsRequired > Regs.size())
387 return 0;
389 for (unsigned StartIdx = 0; StartIdx <= Regs.size() - RegsRequired;
390 ++StartIdx) {
391 bool BlockAvailable = true;
392 // Check for already-allocated regs in this block
393 for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) {
394 if (isAllocated(Regs[StartIdx + BlockIdx])) {
395 BlockAvailable = false;
396 break;
399 if (BlockAvailable) {
400 // Mark the entire block as allocated
401 for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) {
402 MarkAllocated(Regs[StartIdx + BlockIdx]);
404 return Regs[StartIdx];
407 // No block was available
408 return 0;
411 /// Version of AllocateReg with list of registers to be shadowed.
412 unsigned AllocateReg(ArrayRef<MCPhysReg> Regs, const MCPhysReg *ShadowRegs) {
413 unsigned FirstUnalloc = getFirstUnallocated(Regs);
414 if (FirstUnalloc == Regs.size())
415 return 0; // Didn't find the reg.
417 // Mark the register and any aliases as allocated.
418 unsigned Reg = Regs[FirstUnalloc], ShadowReg = ShadowRegs[FirstUnalloc];
419 MarkAllocated(Reg);
420 MarkAllocated(ShadowReg);
421 return Reg;
424 /// AllocateStack - Allocate a chunk of stack space with the specified size
425 /// and alignment.
426 unsigned AllocateStack(unsigned Size, unsigned Alignment) {
427 const llvm::Align Align(Alignment);
428 StackOffset = alignTo(StackOffset, Align);
429 unsigned Result = StackOffset;
430 StackOffset += Size;
431 MaxStackArgAlign = std::max(Align, MaxStackArgAlign);
432 ensureMaxAlignment(Align);
433 return Result;
436 void ensureMaxAlignment(llvm::Align Align) {
437 if (!AnalyzingMustTailForwardedRegs)
438 MF.getFrameInfo().ensureMaxAlignment(Align.value());
441 /// Version of AllocateStack with extra register to be shadowed.
442 unsigned AllocateStack(unsigned Size, unsigned Align, unsigned ShadowReg) {
443 MarkAllocated(ShadowReg);
444 return AllocateStack(Size, Align);
447 /// Version of AllocateStack with list of extra registers to be shadowed.
448 /// Note that, unlike AllocateReg, this shadows ALL of the shadow registers.
449 unsigned AllocateStack(unsigned Size, unsigned Align,
450 ArrayRef<MCPhysReg> ShadowRegs) {
451 for (unsigned i = 0; i < ShadowRegs.size(); ++i)
452 MarkAllocated(ShadowRegs[i]);
453 return AllocateStack(Size, Align);
456 // HandleByVal - Allocate a stack slot large enough to pass an argument by
457 // value. The size and alignment information of the argument is encoded in its
458 // parameter attribute.
459 void HandleByVal(unsigned ValNo, MVT ValVT,
460 MVT LocVT, CCValAssign::LocInfo LocInfo,
461 int MinSize, int MinAlign, ISD::ArgFlagsTy ArgFlags);
463 // Returns count of byval arguments that are to be stored (even partly)
464 // in registers.
465 unsigned getInRegsParamsCount() const { return ByValRegs.size(); }
467 // Returns count of byval in-regs arguments proceed.
468 unsigned getInRegsParamsProcessed() const { return InRegsParamsProcessed; }
470 // Get information about N-th byval parameter that is stored in registers.
471 // Here "ByValParamIndex" is N.
472 void getInRegsParamInfo(unsigned InRegsParamRecordIndex,
473 unsigned& BeginReg, unsigned& EndReg) const {
474 assert(InRegsParamRecordIndex < ByValRegs.size() &&
475 "Wrong ByVal parameter index");
477 const ByValInfo& info = ByValRegs[InRegsParamRecordIndex];
478 BeginReg = info.Begin;
479 EndReg = info.End;
482 // Add information about parameter that is kept in registers.
483 void addInRegsParamInfo(unsigned RegBegin, unsigned RegEnd) {
484 ByValRegs.push_back(ByValInfo(RegBegin, RegEnd));
487 // Goes either to next byval parameter (excluding "waste" record), or
488 // to the end of collection.
489 // Returns false, if end is reached.
490 bool nextInRegsParam() {
491 unsigned e = ByValRegs.size();
492 if (InRegsParamsProcessed < e)
493 ++InRegsParamsProcessed;
494 return InRegsParamsProcessed < e;
497 // Clear byval registers tracking info.
498 void clearByValRegsInfo() {
499 InRegsParamsProcessed = 0;
500 ByValRegs.clear();
503 // Rewind byval registers tracking info.
504 void rewindByValRegsInfo() {
505 InRegsParamsProcessed = 0;
508 // Get list of pending assignments
509 SmallVectorImpl<CCValAssign> &getPendingLocs() {
510 return PendingLocs;
513 // Get a list of argflags for pending assignments.
514 SmallVectorImpl<ISD::ArgFlagsTy> &getPendingArgFlags() {
515 return PendingArgFlags;
518 /// Compute the remaining unused register parameters that would be used for
519 /// the given value type. This is useful when varargs are passed in the
520 /// registers that normal prototyped parameters would be passed in, or for
521 /// implementing perfect forwarding.
522 void getRemainingRegParmsForType(SmallVectorImpl<MCPhysReg> &Regs, MVT VT,
523 CCAssignFn Fn);
525 /// Compute the set of registers that need to be preserved and forwarded to
526 /// any musttail calls.
527 void analyzeMustTailForwardedRegisters(
528 SmallVectorImpl<ForwardedRegister> &Forwards, ArrayRef<MVT> RegParmTypes,
529 CCAssignFn Fn);
531 /// Returns true if the results of the two calling conventions are compatible.
532 /// This is usually part of the check for tailcall eligibility.
533 static bool resultsCompatible(CallingConv::ID CalleeCC,
534 CallingConv::ID CallerCC, MachineFunction &MF,
535 LLVMContext &C,
536 const SmallVectorImpl<ISD::InputArg> &Ins,
537 CCAssignFn CalleeFn, CCAssignFn CallerFn);
539 /// The function runs an additional analysis pass over function arguments.
540 /// It will mark each argument with the attribute flag SecArgPass.
541 /// After running, it will sort the locs list.
542 template <class T>
543 void AnalyzeArgumentsSecondPass(const SmallVectorImpl<T> &Args,
544 CCAssignFn Fn) {
545 unsigned NumFirstPassLocs = Locs.size();
547 /// Creates similar argument list to \p Args in which each argument is
548 /// marked using SecArgPass flag.
549 SmallVector<T, 16> SecPassArg;
550 // SmallVector<ISD::InputArg, 16> SecPassArg;
551 for (auto Arg : Args) {
552 Arg.Flags.setSecArgPass();
553 SecPassArg.push_back(Arg);
556 // Run the second argument pass
557 AnalyzeArguments(SecPassArg, Fn);
559 // Sort the locations of the arguments according to their original position.
560 SmallVector<CCValAssign, 16> TmpArgLocs;
561 TmpArgLocs.swap(Locs);
562 auto B = TmpArgLocs.begin(), E = TmpArgLocs.end();
563 std::merge(B, B + NumFirstPassLocs, B + NumFirstPassLocs, E,
564 std::back_inserter(Locs),
565 [](const CCValAssign &A, const CCValAssign &B) -> bool {
566 return A.getValNo() < B.getValNo();
570 private:
571 /// MarkAllocated - Mark a register and all of its aliases as allocated.
572 void MarkAllocated(unsigned Reg);
575 } // end namespace llvm
577 #endif // LLVM_CODEGEN_CALLINGCONVLOWER_H