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   MachineFunction &MF;
00199   const TargetRegisterInfo &TRI;
00200   SmallVectorImpl<CCValAssign> &Locs;
00201   LLVMContext &Context;
00202 
00203   unsigned StackOffset;
00204   SmallVector<uint32_t, 16> UsedRegs;
00205   SmallVector<CCValAssign, 4> PendingLocs;
00206 
00207   // ByValInfo and SmallVector<ByValInfo, 4> ByValRegs:
00208   //
00209   // Vector of ByValInfo instances (ByValRegs) is introduced for byval registers
00210   // tracking.
00211   // Or, in another words it tracks byval parameters that are stored in
00212   // general purpose registers.
00213   //
00214   // For 4 byte stack alignment,
00215   // instance index means byval parameter number in formal
00216   // arguments set. Assume, we have some "struct_type" with size = 4 bytes,
00217   // then, for function "foo":
00218   //
00219   // i32 foo(i32 %p, %struct_type* %r, i32 %s, %struct_type* %t)
00220   //
00221   // ByValRegs[0] describes how "%r" is stored (Begin == r1, End == r2)
00222   // ByValRegs[1] describes how "%t" is stored (Begin == r3, End == r4).
00223   //
00224   // In case of 8 bytes stack alignment,
00225   // ByValRegs may also contain information about wasted registers.
00226   // In function shown above, r3 would be wasted according to AAPCS rules.
00227   // And in that case ByValRegs[1].Waste would be "true".
00228   // ByValRegs vector size still would be 2,
00229   // while "%t" goes to the stack: it wouldn't be described in ByValRegs.
00230   //
00231   // Supposed use-case for this collection:
00232   // 1. Initially ByValRegs is empty, InRegsParamsProcessed is 0.
00233   // 2. HandleByVal fillups ByValRegs.
00234   // 3. Argument analysis (LowerFormatArguments, for example). After
00235   // some byval argument was analyzed, InRegsParamsProcessed is increased.
00236   struct ByValInfo {
00237     ByValInfo(unsigned B, unsigned E, bool IsWaste = false) :
00238       Begin(B), End(E), Waste(IsWaste) {}
00239     // First register allocated for current parameter.
00240     unsigned Begin;
00241 
00242     // First after last register allocated for current parameter.
00243     unsigned End;
00244 
00245     // Means that current range of registers doesn't belong to any
00246     // parameters. It was wasted due to stack alignment rules.
00247     // For more information see:
00248     // AAPCS, 5.5 Parameter Passing, Stage C, C.3.
00249     bool Waste;
00250   };
00251   SmallVector<ByValInfo, 4 > ByValRegs;
00252 
00253   // InRegsParamsProcessed - shows how many instances of ByValRegs was proceed
00254   // during argument analysis.
00255   unsigned InRegsParamsProcessed;
00256 
00257 protected:
00258   ParmContext CallOrPrologue;
00259 
00260 public:
00261   CCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
00262           SmallVectorImpl<CCValAssign> &locs, LLVMContext &C);
00263 
00264   void addLoc(const CCValAssign &V) {
00265     Locs.push_back(V);
00266   }
00267 
00268   LLVMContext &getContext() const { return Context; }
00269   MachineFunction &getMachineFunction() const { return MF; }
00270   CallingConv::ID getCallingConv() const { return CallingConv; }
00271   bool isVarArg() const { return IsVarArg; }
00272 
00273   unsigned getNextStackOffset() const { return StackOffset; }
00274 
00275   /// isAllocated - Return true if the specified register (or an alias) is
00276   /// allocated.
00277   bool isAllocated(unsigned Reg) const {
00278     return UsedRegs[Reg/32] & (1 << (Reg&31));
00279   }
00280 
00281   /// AnalyzeFormalArguments - Analyze an array of argument values,
00282   /// incorporating info about the formals into this state.
00283   void AnalyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
00284                               CCAssignFn Fn);
00285 
00286   /// AnalyzeReturn - Analyze the returned values of a return,
00287   /// incorporating info about the result values into this state.
00288   void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
00289                      CCAssignFn Fn);
00290 
00291   /// CheckReturn - Analyze the return values of a function, returning
00292   /// true if the return can be performed without sret-demotion, and
00293   /// false otherwise.
00294   bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags,
00295                    CCAssignFn Fn);
00296 
00297   /// AnalyzeCallOperands - Analyze the outgoing arguments to a call,
00298   /// incorporating info about the passed values into this state.
00299   void AnalyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Outs,
00300                            CCAssignFn Fn);
00301 
00302   /// AnalyzeCallOperands - Same as above except it takes vectors of types
00303   /// and argument flags.
00304   void AnalyzeCallOperands(SmallVectorImpl<MVT> &ArgVTs,
00305                            SmallVectorImpl<ISD::ArgFlagsTy> &Flags,
00306                            CCAssignFn Fn);
00307 
00308   /// AnalyzeCallResult - Analyze the return values of a call,
00309   /// incorporating info about the passed values into this state.
00310   void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
00311                          CCAssignFn Fn);
00312 
00313   /// AnalyzeCallResult - Same as above except it's specialized for calls which
00314   /// produce a single value.
00315   void AnalyzeCallResult(MVT VT, CCAssignFn Fn);
00316 
00317   /// getFirstUnallocated - Return the index of the first unallocated register
00318   /// in the set, or Regs.size() if they are all allocated.
00319   unsigned getFirstUnallocated(ArrayRef<MCPhysReg> Regs) const {
00320     for (unsigned i = 0; i < Regs.size(); ++i)
00321       if (!isAllocated(Regs[i]))
00322         return i;
00323     return Regs.size();
00324   }
00325 
00326   /// AllocateReg - Attempt to allocate one register.  If it is not available,
00327   /// return zero.  Otherwise, return the register, marking it and any aliases
00328   /// as allocated.
00329   unsigned AllocateReg(unsigned Reg) {
00330     if (isAllocated(Reg)) return 0;
00331     MarkAllocated(Reg);
00332     return Reg;
00333   }
00334 
00335   /// Version of AllocateReg with extra register to be shadowed.
00336   unsigned AllocateReg(unsigned Reg, unsigned ShadowReg) {
00337     if (isAllocated(Reg)) return 0;
00338     MarkAllocated(Reg);
00339     MarkAllocated(ShadowReg);
00340     return Reg;
00341   }
00342 
00343   /// AllocateReg - Attempt to allocate one of the specified registers.  If none
00344   /// are available, return zero.  Otherwise, return the first one available,
00345   /// marking it and any aliases as allocated.
00346   unsigned AllocateReg(ArrayRef<MCPhysReg> Regs) {
00347     unsigned FirstUnalloc = getFirstUnallocated(Regs);
00348     if (FirstUnalloc == Regs.size())
00349       return 0;    // Didn't find the reg.
00350 
00351     // Mark the register and any aliases as allocated.
00352     unsigned Reg = Regs[FirstUnalloc];
00353     MarkAllocated(Reg);
00354     return Reg;
00355   }
00356 
00357   /// AllocateRegBlock - Attempt to allocate a block of RegsRequired consecutive
00358   /// registers. If this is not possible, return zero. Otherwise, return the first
00359   /// register of the block that were allocated, marking the entire block as allocated.
00360   unsigned AllocateRegBlock(ArrayRef<uint16_t> Regs, unsigned RegsRequired) {
00361     if (RegsRequired > Regs.size())
00362       return 0;
00363 
00364     for (unsigned StartIdx = 0; StartIdx <= Regs.size() - RegsRequired;
00365          ++StartIdx) {
00366       bool BlockAvailable = true;
00367       // Check for already-allocated regs in this block
00368       for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) {
00369         if (isAllocated(Regs[StartIdx + BlockIdx])) {
00370           BlockAvailable = false;
00371           break;
00372         }
00373       }
00374       if (BlockAvailable) {
00375         // Mark the entire block as allocated
00376         for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) {
00377           MarkAllocated(Regs[StartIdx + BlockIdx]);
00378         }
00379         return Regs[StartIdx];
00380       }
00381     }
00382     // No block was available
00383     return 0;
00384   }
00385 
00386   /// Version of AllocateReg with list of registers to be shadowed.
00387   unsigned AllocateReg(ArrayRef<MCPhysReg> Regs, const MCPhysReg *ShadowRegs) {
00388     unsigned FirstUnalloc = getFirstUnallocated(Regs);
00389     if (FirstUnalloc == Regs.size())
00390       return 0;    // Didn't find the reg.
00391 
00392     // Mark the register and any aliases as allocated.
00393     unsigned Reg = Regs[FirstUnalloc], ShadowReg = ShadowRegs[FirstUnalloc];
00394     MarkAllocated(Reg);
00395     MarkAllocated(ShadowReg);
00396     return Reg;
00397   }
00398 
00399   /// AllocateStack - Allocate a chunk of stack space with the specified size
00400   /// and alignment.
00401   unsigned AllocateStack(unsigned Size, unsigned Align) {
00402     assert(Align && ((Align - 1) & Align) == 0); // Align is power of 2.
00403     StackOffset = ((StackOffset + Align - 1) & ~(Align - 1));
00404     unsigned Result = StackOffset;
00405     StackOffset += Size;
00406     MF.getFrameInfo()->ensureMaxAlignment(Align);
00407     return Result;
00408   }
00409 
00410   /// Version of AllocateStack with extra register to be shadowed.
00411   unsigned AllocateStack(unsigned Size, unsigned Align, unsigned ShadowReg) {
00412     MarkAllocated(ShadowReg);
00413     return AllocateStack(Size, Align);
00414   }
00415 
00416   /// Version of AllocateStack with list of extra registers to be shadowed.
00417   /// Note that, unlike AllocateReg, this shadows ALL of the shadow registers.
00418   unsigned AllocateStack(unsigned Size, unsigned Align,
00419                          ArrayRef<MCPhysReg> ShadowRegs) {
00420     for (unsigned i = 0; i < ShadowRegs.size(); ++i)
00421       MarkAllocated(ShadowRegs[i]);
00422     return AllocateStack(Size, Align);
00423   }
00424 
00425   // HandleByVal - Allocate a stack slot large enough to pass an argument by
00426   // value. The size and alignment information of the argument is encoded in its
00427   // parameter attribute.
00428   void HandleByVal(unsigned ValNo, MVT ValVT,
00429                    MVT LocVT, CCValAssign::LocInfo LocInfo,
00430                    int MinSize, int MinAlign, ISD::ArgFlagsTy ArgFlags);
00431 
00432   // Returns count of byval arguments that are to be stored (even partly)
00433   // in registers.
00434   unsigned getInRegsParamsCount() const { return ByValRegs.size(); }
00435 
00436   // Returns count of byval in-regs arguments proceed.
00437   unsigned getInRegsParamsProcessed() const { return InRegsParamsProcessed; }
00438 
00439   // Get information about N-th byval parameter that is stored in registers.
00440   // Here "ByValParamIndex" is N.
00441   void getInRegsParamInfo(unsigned InRegsParamRecordIndex,
00442                           unsigned& BeginReg, unsigned& EndReg) const {
00443     assert(InRegsParamRecordIndex < ByValRegs.size() &&
00444            "Wrong ByVal parameter index");
00445 
00446     const ByValInfo& info = ByValRegs[InRegsParamRecordIndex];
00447     BeginReg = info.Begin;
00448     EndReg = info.End;
00449   }
00450 
00451   // Add information about parameter that is kept in registers.
00452   void addInRegsParamInfo(unsigned RegBegin, unsigned RegEnd) {
00453     ByValRegs.push_back(ByValInfo(RegBegin, RegEnd));
00454   }
00455 
00456   // Goes either to next byval parameter (excluding "waste" record), or
00457   // to the end of collection.
00458   // Returns false, if end is reached.
00459   bool nextInRegsParam() {
00460     unsigned e = ByValRegs.size();
00461     if (InRegsParamsProcessed < e)
00462       ++InRegsParamsProcessed;
00463     return InRegsParamsProcessed < e;
00464   }
00465 
00466   // Clear byval registers tracking info.
00467   void clearByValRegsInfo() {
00468     InRegsParamsProcessed = 0;
00469     ByValRegs.clear();
00470   }
00471 
00472   // Rewind byval registers tracking info.
00473   void rewindByValRegsInfo() {
00474     InRegsParamsProcessed = 0;
00475   }
00476 
00477   ParmContext getCallOrPrologue() const { return CallOrPrologue; }
00478 
00479   // Get list of pending assignments
00480   SmallVectorImpl<llvm::CCValAssign> &getPendingLocs() {
00481     return PendingLocs;
00482   }
00483 
00484   /// Compute the remaining unused register parameters that would be used for
00485   /// the given value type. This is useful when varargs are passed in the
00486   /// registers that normal prototyped parameters would be passed in, or for
00487   /// implementing perfect forwarding.
00488   void getRemainingRegParmsForType(SmallVectorImpl<MCPhysReg> &Regs, MVT VT,
00489                                    CCAssignFn Fn);
00490 
00491   /// Compute the set of registers that need to be preserved and forwarded to
00492   /// any musttail calls.
00493   void analyzeMustTailForwardedRegisters(
00494       SmallVectorImpl<ForwardedRegister> &Forwards, ArrayRef<MVT> RegParmTypes,
00495       CCAssignFn Fn);
00496 
00497 private:
00498   /// MarkAllocated - Mark a register and all of its aliases as allocated.
00499   void MarkAllocated(unsigned Reg);
00500 };
00501 
00502 
00503 
00504 } // end namespace llvm
00505 
00506 #endif