LLVM  mainline
CallingConvLower.h
Go to the documentation of this file.
00001 //===-- llvm/CallingConvLower.h - Calling Conventions -----------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file declares the CCState and CCValAssign classes, used for lowering
00011 // and implementing calling conventions.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_CODEGEN_CALLINGCONVLOWER_H
00016 #define LLVM_CODEGEN_CALLINGCONVLOWER_H
00017 
00018 #include "llvm/ADT/SmallVector.h"
00019 #include "llvm/CodeGen/MachineFrameInfo.h"
00020 #include "llvm/CodeGen/MachineFunction.h"
00021 #include "llvm/IR/CallingConv.h"
00022 #include "llvm/MC/MCRegisterInfo.h"
00023 #include "llvm/Target/TargetCallingConv.h"
00024 
00025 namespace llvm {
00026 class CCState;
00027 class MVT;
00028 class TargetMachine;
00029 class TargetRegisterInfo;
00030 
00031 /// CCValAssign - Represent assignment of one arg/retval to a location.
00032 class CCValAssign {
00033 public:
00034   enum LocInfo {
00035     Full,      // The value fills the full location.
00036     SExt,      // The value is sign extended in the location.
00037     ZExt,      // The value is zero extended in the location.
00038     AExt,      // The value is extended with undefined upper bits.
00039     SExtUpper, // The value is in the upper bits of the location and should be
00040                // sign extended when retrieved.
00041     ZExtUpper, // The value is in the upper bits of the location and should be
00042                // zero extended when retrieved.
00043     AExtUpper, // The value is in the upper bits of the location and should be
00044                // extended with undefined upper bits when retrieved.
00045     BCvt,      // The value is bit-converted in the location.
00046     VExt,      // The value is vector-widened in the location.
00047                // FIXME: Not implemented yet. Code that uses AExt to mean
00048                // vector-widen should be fixed to use VExt instead.
00049     FPExt,     // The floating-point value is fp-extended in the location.
00050     Indirect   // The location contains pointer to the value.
00051     // TODO: a subset of the value is in the location.
00052   };
00053 
00054 private:
00055   /// ValNo - This is the value number begin assigned (e.g. an argument number).
00056   unsigned ValNo;
00057 
00058   /// Loc is either a stack offset or a register number.
00059   unsigned Loc;
00060 
00061   /// isMem - True if this is a memory loc, false if it is a register loc.
00062   unsigned isMem : 1;
00063 
00064   /// isCustom - True if this arg/retval requires special handling.
00065   unsigned isCustom : 1;
00066 
00067   /// Information about how the value is assigned.
00068   LocInfo HTP : 6;
00069 
00070   /// ValVT - The type of the value being assigned.
00071   MVT ValVT;
00072 
00073   /// LocVT - The type of the location being assigned to.
00074   MVT LocVT;
00075 public:
00076 
00077   static CCValAssign getReg(unsigned ValNo, MVT ValVT,
00078                             unsigned RegNo, MVT LocVT,
00079                             LocInfo HTP) {
00080     CCValAssign Ret;
00081     Ret.ValNo = ValNo;
00082     Ret.Loc = RegNo;
00083     Ret.isMem = false;
00084     Ret.isCustom = false;
00085     Ret.HTP = HTP;
00086     Ret.ValVT = ValVT;
00087     Ret.LocVT = LocVT;
00088     return Ret;
00089   }
00090 
00091   static CCValAssign getCustomReg(unsigned ValNo, MVT ValVT,
00092                                   unsigned RegNo, MVT LocVT,
00093                                   LocInfo HTP) {
00094     CCValAssign Ret;
00095     Ret = getReg(ValNo, ValVT, RegNo, LocVT, HTP);
00096     Ret.isCustom = true;
00097     return Ret;
00098   }
00099 
00100   static CCValAssign getMem(unsigned ValNo, MVT ValVT,
00101                             unsigned Offset, MVT LocVT,
00102                             LocInfo HTP) {
00103     CCValAssign Ret;
00104     Ret.ValNo = ValNo;
00105     Ret.Loc = Offset;
00106     Ret.isMem = true;
00107     Ret.isCustom = false;
00108     Ret.HTP = HTP;
00109     Ret.ValVT = ValVT;
00110     Ret.LocVT = LocVT;
00111     return Ret;
00112   }
00113 
00114   static CCValAssign getCustomMem(unsigned ValNo, MVT ValVT,
00115                                   unsigned Offset, MVT LocVT,
00116                                   LocInfo HTP) {
00117     CCValAssign Ret;
00118     Ret = getMem(ValNo, ValVT, Offset, LocVT, HTP);
00119     Ret.isCustom = true;
00120     return Ret;
00121   }
00122 
00123   // There is no need to differentiate between a pending CCValAssign and other
00124   // kinds, as they are stored in a different list.
00125   static CCValAssign getPending(unsigned ValNo, MVT ValVT, MVT LocVT,
00126                                 LocInfo HTP, unsigned ExtraInfo = 0) {
00127     return getReg(ValNo, ValVT, ExtraInfo, LocVT, HTP);
00128   }
00129 
00130   void convertToReg(unsigned RegNo) {
00131     Loc = RegNo;
00132     isMem = false;
00133   }
00134 
00135   void convertToMem(unsigned Offset) {
00136     Loc = Offset;
00137     isMem = true;
00138   }
00139 
00140   unsigned getValNo() const { return ValNo; }
00141   MVT getValVT() const { return ValVT; }
00142 
00143   bool isRegLoc() const { return !isMem; }
00144   bool isMemLoc() const { return isMem; }
00145 
00146   bool needsCustom() const { return isCustom; }
00147 
00148   unsigned getLocReg() const { assert(isRegLoc()); return Loc; }
00149   unsigned getLocMemOffset() const { assert(isMemLoc()); return Loc; }
00150   unsigned getExtraInfo() const { return Loc; }
00151   MVT getLocVT() const { return LocVT; }
00152 
00153   LocInfo getLocInfo() const { return HTP; }
00154   bool isExtInLoc() const {
00155     return (HTP == AExt || HTP == SExt || HTP == ZExt);
00156   }
00157 
00158   bool isUpperBitsInLoc() const {
00159     return HTP == AExtUpper || HTP == SExtUpper || HTP == ZExtUpper;
00160   }
00161 };
00162 
00163 /// Describes a register that needs to be forwarded from the prologue to a
00164 /// musttail call.
00165 struct ForwardedRegister {
00166   ForwardedRegister(unsigned VReg, MCPhysReg PReg, MVT VT)
00167       : VReg(VReg), PReg(PReg), VT(VT) {}
00168   unsigned VReg;
00169   MCPhysReg PReg;
00170   MVT VT;
00171 };
00172 
00173 /// CCAssignFn - This function assigns a location for Val, updating State to
00174 /// reflect the change.  It returns 'true' if it failed to handle Val.
00175 typedef bool CCAssignFn(unsigned ValNo, MVT ValVT,
00176                         MVT LocVT, CCValAssign::LocInfo LocInfo,
00177                         ISD::ArgFlagsTy ArgFlags, CCState &State);
00178 
00179 /// CCCustomFn - This function assigns a location for Val, possibly updating
00180 /// all args to reflect changes and indicates if it handled it. It must set
00181 /// isCustom if it handles the arg and returns true.
00182 typedef bool CCCustomFn(unsigned &ValNo, MVT &ValVT,
00183                         MVT &LocVT, CCValAssign::LocInfo &LocInfo,
00184                         ISD::ArgFlagsTy &ArgFlags, CCState &State);
00185 
00186 /// ParmContext - This enum tracks whether calling convention lowering is in
00187 /// the context of prologue or call generation. Not all backends make use of
00188 /// this information.
00189 typedef enum { Unknown, Prologue, Call } ParmContext;
00190 
00191 /// CCState - This class holds information needed while lowering arguments and
00192 /// return values.  It captures which registers are already assigned and which
00193 /// stack slots are used.  It provides accessors to allocate these values.
00194 class CCState {
00195 private:
00196   CallingConv::ID CallingConv;
00197   bool IsVarArg;
00198   bool AnalyzingMustTailForwardedRegs = false;
00199   MachineFunction &MF;
00200   const TargetRegisterInfo &TRI;
00201   SmallVectorImpl<CCValAssign> &Locs;
00202   LLVMContext &Context;
00203 
00204   unsigned StackOffset;
00205   unsigned MaxStackArgAlign;
00206   SmallVector<uint32_t, 16> UsedRegs;
00207   SmallVector<CCValAssign, 4> PendingLocs;
00208 
00209   // ByValInfo and SmallVector<ByValInfo, 4> ByValRegs:
00210   //
00211   // Vector of ByValInfo instances (ByValRegs) is introduced for byval registers
00212   // tracking.
00213   // Or, in another words it tracks byval parameters that are stored in
00214   // general purpose registers.
00215   //
00216   // For 4 byte stack alignment,
00217   // instance index means byval parameter number in formal
00218   // arguments set. Assume, we have some "struct_type" with size = 4 bytes,
00219   // then, for function "foo":
00220   //
00221   // i32 foo(i32 %p, %struct_type* %r, i32 %s, %struct_type* %t)
00222   //
00223   // ByValRegs[0] describes how "%r" is stored (Begin == r1, End == r2)
00224   // ByValRegs[1] describes how "%t" is stored (Begin == r3, End == r4).
00225   //
00226   // In case of 8 bytes stack alignment,
00227   // ByValRegs may also contain information about wasted registers.
00228   // In function shown above, r3 would be wasted according to AAPCS rules.
00229   // And in that case ByValRegs[1].Waste would be "true".
00230   // ByValRegs vector size still would be 2,
00231   // while "%t" goes to the stack: it wouldn't be described in ByValRegs.
00232   //
00233   // Supposed use-case for this collection:
00234   // 1. Initially ByValRegs is empty, InRegsParamsProcessed is 0.
00235   // 2. HandleByVal fillups ByValRegs.
00236   // 3. Argument analysis (LowerFormatArguments, for example). After
00237   // some byval argument was analyzed, InRegsParamsProcessed is increased.
00238   struct ByValInfo {
00239     ByValInfo(unsigned B, unsigned E, bool IsWaste = false) :
00240       Begin(B), End(E), Waste(IsWaste) {}
00241     // First register allocated for current parameter.
00242     unsigned Begin;
00243 
00244     // First after last register allocated for current parameter.
00245     unsigned End;
00246 
00247     // Means that current range of registers doesn't belong to any
00248     // parameters. It was wasted due to stack alignment rules.
00249     // For more information see:
00250     // AAPCS, 5.5 Parameter Passing, Stage C, C.3.
00251     bool Waste;
00252   };
00253   SmallVector<ByValInfo, 4 > ByValRegs;
00254 
00255   // InRegsParamsProcessed - shows how many instances of ByValRegs was proceed
00256   // during argument analysis.
00257   unsigned InRegsParamsProcessed;
00258 
00259 protected:
00260   ParmContext CallOrPrologue;
00261 
00262 public:
00263   CCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
00264           SmallVectorImpl<CCValAssign> &locs, LLVMContext &C);
00265 
00266   void addLoc(const CCValAssign &V) {
00267     Locs.push_back(V);
00268   }
00269 
00270   LLVMContext &getContext() const { return Context; }
00271   MachineFunction &getMachineFunction() const { return MF; }
00272   CallingConv::ID getCallingConv() const { return CallingConv; }
00273   bool isVarArg() const { return IsVarArg; }
00274 
00275   /// getNextStackOffset - Return the next stack offset such that all stack
00276   /// slots satisfy their alignment requirements.
00277   unsigned getNextStackOffset() const {
00278     return StackOffset;
00279   }
00280 
00281   /// getAlignedCallFrameSize - Return the size of the call frame needed to
00282   /// be able to store all arguments and such that the alignment requirement
00283   /// of each of the arguments is satisfied.
00284   unsigned getAlignedCallFrameSize() const {
00285     return alignTo(StackOffset, MaxStackArgAlign);
00286   }
00287 
00288   /// isAllocated - Return true if the specified register (or an alias) is
00289   /// allocated.
00290   bool isAllocated(unsigned Reg) const {
00291     return UsedRegs[Reg/32] & (1 << (Reg&31));
00292   }
00293 
00294   /// AnalyzeFormalArguments - Analyze an array of argument values,
00295   /// incorporating info about the formals into this state.
00296   void AnalyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
00297                               CCAssignFn Fn);
00298 
00299   /// AnalyzeReturn - Analyze the returned values of a return,
00300   /// incorporating info about the result values into this state.
00301   void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
00302                      CCAssignFn Fn);
00303 
00304   /// CheckReturn - Analyze the return values of a function, returning
00305   /// true if the return can be performed without sret-demotion, and
00306   /// false otherwise.
00307   bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags,
00308                    CCAssignFn Fn);
00309 
00310   /// AnalyzeCallOperands - Analyze the outgoing arguments to a call,
00311   /// incorporating info about the passed values into this state.
00312   void AnalyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Outs,
00313                            CCAssignFn Fn);
00314 
00315   /// AnalyzeCallOperands - Same as above except it takes vectors of types
00316   /// and argument flags.
00317   void AnalyzeCallOperands(SmallVectorImpl<MVT> &ArgVTs,
00318                            SmallVectorImpl<ISD::ArgFlagsTy> &Flags,
00319                            CCAssignFn Fn);
00320 
00321   /// AnalyzeCallResult - Analyze the return values of a call,
00322   /// incorporating info about the passed values into this state.
00323   void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
00324                          CCAssignFn Fn);
00325 
00326   /// AnalyzeCallResult - Same as above except it's specialized for calls which
00327   /// produce a single value.
00328   void AnalyzeCallResult(MVT VT, CCAssignFn Fn);
00329 
00330   /// getFirstUnallocated - Return the index of the first unallocated register
00331   /// in the set, or Regs.size() if they are all allocated.
00332   unsigned getFirstUnallocated(ArrayRef<MCPhysReg> Regs) const {
00333     for (unsigned i = 0; i < Regs.size(); ++i)
00334       if (!isAllocated(Regs[i]))
00335         return i;
00336     return Regs.size();
00337   }
00338 
00339   /// AllocateReg - Attempt to allocate one register.  If it is not available,
00340   /// return zero.  Otherwise, return the register, marking it and any aliases
00341   /// as allocated.
00342   unsigned AllocateReg(unsigned Reg) {
00343     if (isAllocated(Reg)) return 0;
00344     MarkAllocated(Reg);
00345     return Reg;
00346   }
00347 
00348   /// Version of AllocateReg with extra register to be shadowed.
00349   unsigned AllocateReg(unsigned Reg, unsigned ShadowReg) {
00350     if (isAllocated(Reg)) return 0;
00351     MarkAllocated(Reg);
00352     MarkAllocated(ShadowReg);
00353     return Reg;
00354   }
00355 
00356   /// AllocateReg - Attempt to allocate one of the specified registers.  If none
00357   /// are available, return zero.  Otherwise, return the first one available,
00358   /// marking it and any aliases as allocated.
00359   unsigned AllocateReg(ArrayRef<MCPhysReg> Regs) {
00360     unsigned FirstUnalloc = getFirstUnallocated(Regs);
00361     if (FirstUnalloc == Regs.size())
00362       return 0;    // Didn't find the reg.
00363 
00364     // Mark the register and any aliases as allocated.
00365     unsigned Reg = Regs[FirstUnalloc];
00366     MarkAllocated(Reg);
00367     return Reg;
00368   }
00369 
00370   /// AllocateRegBlock - Attempt to allocate a block of RegsRequired consecutive
00371   /// registers. If this is not possible, return zero. Otherwise, return the first
00372   /// register of the block that were allocated, marking the entire block as allocated.
00373   unsigned AllocateRegBlock(ArrayRef<MCPhysReg> Regs, unsigned RegsRequired) {
00374     if (RegsRequired > Regs.size())
00375       return 0;
00376 
00377     for (unsigned StartIdx = 0; StartIdx <= Regs.size() - RegsRequired;
00378          ++StartIdx) {
00379       bool BlockAvailable = true;
00380       // Check for already-allocated regs in this block
00381       for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) {
00382         if (isAllocated(Regs[StartIdx + BlockIdx])) {
00383           BlockAvailable = false;
00384           break;
00385         }
00386       }
00387       if (BlockAvailable) {
00388         // Mark the entire block as allocated
00389         for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) {
00390           MarkAllocated(Regs[StartIdx + BlockIdx]);
00391         }
00392         return Regs[StartIdx];
00393       }
00394     }
00395     // No block was available
00396     return 0;
00397   }
00398 
00399   /// Version of AllocateReg with list of registers to be shadowed.
00400   unsigned AllocateReg(ArrayRef<MCPhysReg> Regs, const MCPhysReg *ShadowRegs) {
00401     unsigned FirstUnalloc = getFirstUnallocated(Regs);
00402     if (FirstUnalloc == Regs.size())
00403       return 0;    // Didn't find the reg.
00404 
00405     // Mark the register and any aliases as allocated.
00406     unsigned Reg = Regs[FirstUnalloc], ShadowReg = ShadowRegs[FirstUnalloc];
00407     MarkAllocated(Reg);
00408     MarkAllocated(ShadowReg);
00409     return Reg;
00410   }
00411 
00412   /// AllocateStack - Allocate a chunk of stack space with the specified size
00413   /// and alignment.
00414   unsigned AllocateStack(unsigned Size, unsigned Align) {
00415     assert(Align && ((Align - 1) & Align) == 0); // Align is power of 2.
00416     StackOffset = alignTo(StackOffset, Align);
00417     unsigned Result = StackOffset;
00418     StackOffset += Size;
00419     MaxStackArgAlign = std::max(Align, MaxStackArgAlign);
00420     ensureMaxAlignment(Align);
00421     return Result;
00422   }
00423 
00424   void ensureMaxAlignment(unsigned Align) {
00425     if (!AnalyzingMustTailForwardedRegs)
00426       MF.getFrameInfo()->ensureMaxAlignment(Align);
00427   }
00428 
00429   /// Version of AllocateStack with extra register to be shadowed.
00430   unsigned AllocateStack(unsigned Size, unsigned Align, unsigned ShadowReg) {
00431     MarkAllocated(ShadowReg);
00432     return AllocateStack(Size, Align);
00433   }
00434 
00435   /// Version of AllocateStack with list of extra registers to be shadowed.
00436   /// Note that, unlike AllocateReg, this shadows ALL of the shadow registers.
00437   unsigned AllocateStack(unsigned Size, unsigned Align,
00438                          ArrayRef<MCPhysReg> ShadowRegs) {
00439     for (unsigned i = 0; i < ShadowRegs.size(); ++i)
00440       MarkAllocated(ShadowRegs[i]);
00441     return AllocateStack(Size, Align);
00442   }
00443 
00444   // HandleByVal - Allocate a stack slot large enough to pass an argument by
00445   // value. The size and alignment information of the argument is encoded in its
00446   // parameter attribute.
00447   void HandleByVal(unsigned ValNo, MVT ValVT,
00448                    MVT LocVT, CCValAssign::LocInfo LocInfo,
00449                    int MinSize, int MinAlign, ISD::ArgFlagsTy ArgFlags);
00450 
00451   // Returns count of byval arguments that are to be stored (even partly)
00452   // in registers.
00453   unsigned getInRegsParamsCount() const { return ByValRegs.size(); }
00454 
00455   // Returns count of byval in-regs arguments proceed.
00456   unsigned getInRegsParamsProcessed() const { return InRegsParamsProcessed; }
00457 
00458   // Get information about N-th byval parameter that is stored in registers.
00459   // Here "ByValParamIndex" is N.
00460   void getInRegsParamInfo(unsigned InRegsParamRecordIndex,
00461                           unsigned& BeginReg, unsigned& EndReg) const {
00462     assert(InRegsParamRecordIndex < ByValRegs.size() &&
00463            "Wrong ByVal parameter index");
00464 
00465     const ByValInfo& info = ByValRegs[InRegsParamRecordIndex];
00466     BeginReg = info.Begin;
00467     EndReg = info.End;
00468   }
00469 
00470   // Add information about parameter that is kept in registers.
00471   void addInRegsParamInfo(unsigned RegBegin, unsigned RegEnd) {
00472     ByValRegs.push_back(ByValInfo(RegBegin, RegEnd));
00473   }
00474 
00475   // Goes either to next byval parameter (excluding "waste" record), or
00476   // to the end of collection.
00477   // Returns false, if end is reached.
00478   bool nextInRegsParam() {
00479     unsigned e = ByValRegs.size();
00480     if (InRegsParamsProcessed < e)
00481       ++InRegsParamsProcessed;
00482     return InRegsParamsProcessed < e;
00483   }
00484 
00485   // Clear byval registers tracking info.
00486   void clearByValRegsInfo() {
00487     InRegsParamsProcessed = 0;
00488     ByValRegs.clear();
00489   }
00490 
00491   // Rewind byval registers tracking info.
00492   void rewindByValRegsInfo() {
00493     InRegsParamsProcessed = 0;
00494   }
00495 
00496   ParmContext getCallOrPrologue() const { return CallOrPrologue; }
00497 
00498   // Get list of pending assignments
00499   SmallVectorImpl<llvm::CCValAssign> &getPendingLocs() {
00500     return PendingLocs;
00501   }
00502 
00503   /// Compute the remaining unused register parameters that would be used for
00504   /// the given value type. This is useful when varargs are passed in the
00505   /// registers that normal prototyped parameters would be passed in, or for
00506   /// implementing perfect forwarding.
00507   void getRemainingRegParmsForType(SmallVectorImpl<MCPhysReg> &Regs, MVT VT,
00508                                    CCAssignFn Fn);
00509 
00510   /// Compute the set of registers that need to be preserved and forwarded to
00511   /// any musttail calls.
00512   void analyzeMustTailForwardedRegisters(
00513       SmallVectorImpl<ForwardedRegister> &Forwards, ArrayRef<MVT> RegParmTypes,
00514       CCAssignFn Fn);
00515 
00516 private:
00517   /// MarkAllocated - Mark a register and all of its aliases as allocated.
00518   void MarkAllocated(unsigned Reg);
00519 };
00520 
00521 
00522 
00523 } // end namespace llvm
00524 
00525 #endif