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