LLVM API Documentation

MipsISelLowering.cpp

Go to the documentation of this file.
00001 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
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 defines the interfaces that Mips uses to lower LLVM code into a
00011 // selection DAG.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "mips-lower"
00016 #include "MipsISelLowering.h"
00017 #include "MipsMachineFunction.h"
00018 #include "MipsTargetMachine.h"
00019 #include "MipsTargetObjectFile.h"
00020 #include "MipsSubtarget.h"
00021 #include "llvm/DerivedTypes.h"
00022 #include "llvm/Function.h"
00023 #include "llvm/GlobalVariable.h"
00024 #include "llvm/Intrinsics.h"
00025 #include "llvm/CallingConv.h"
00026 #include "llvm/CodeGen/CallingConvLower.h"
00027 #include "llvm/CodeGen/MachineFrameInfo.h"
00028 #include "llvm/CodeGen/MachineFunction.h"
00029 #include "llvm/CodeGen/MachineInstrBuilder.h"
00030 #include "llvm/CodeGen/MachineRegisterInfo.h"
00031 #include "llvm/CodeGen/SelectionDAGISel.h"
00032 #include "llvm/CodeGen/ValueTypes.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/ErrorHandling.h"
00035 using namespace llvm;
00036 
00037 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
00038   switch (Opcode) {
00039     case MipsISD::JmpLink    : return "MipsISD::JmpLink";
00040     case MipsISD::Hi         : return "MipsISD::Hi";
00041     case MipsISD::Lo         : return "MipsISD::Lo";
00042     case MipsISD::GPRel      : return "MipsISD::GPRel";
00043     case MipsISD::Ret        : return "MipsISD::Ret";
00044     case MipsISD::CMov       : return "MipsISD::CMov";
00045     case MipsISD::SelectCC   : return "MipsISD::SelectCC";
00046     case MipsISD::FPSelectCC : return "MipsISD::FPSelectCC";
00047     case MipsISD::FPBrcond   : return "MipsISD::FPBrcond";
00048     case MipsISD::FPCmp      : return "MipsISD::FPCmp";
00049     case MipsISD::FPRound    : return "MipsISD::FPRound";
00050     default                  : return NULL;
00051   }
00052 }
00053 
00054 MipsTargetLowering::
00055 MipsTargetLowering(MipsTargetMachine &TM)
00056   : TargetLowering(TM, new MipsTargetObjectFile()) {
00057   Subtarget = &TM.getSubtarget<MipsSubtarget>();
00058 
00059   // Mips does not have i1 type, so use i32 for
00060   // setcc operations results (slt, sgt, ...). 
00061   setBooleanContents(ZeroOrOneBooleanContent);
00062 
00063   // JumpTable targets must use GOT when using PIC_
00064   setUsesGlobalOffsetTable(true);
00065 
00066   // Set up the register classes
00067   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
00068   addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
00069 
00070   // When dealing with single precision only, use libcalls
00071   if (!Subtarget->isSingleFloat())
00072     if (!Subtarget->isFP64bit())
00073       addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
00074 
00075   // Legal fp constants
00076   addLegalFPImmediate(APFloat(+0.0f));
00077 
00078   // Load extented operations for i1 types must be promoted 
00079   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
00080   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
00081   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
00082 
00083   // MIPS doesn't have extending float->double load/store
00084   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
00085   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
00086 
00087   // Used by legalize types to correctly generate the setcc result. 
00088   // Without this, every float setcc comes with a AND/OR with the result, 
00089   // we don't want this, since the fpcmp result goes to a flag register, 
00090   // which is used implicitly by brcond and select operations.
00091   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
00092 
00093   // Mips Custom Operations
00094   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
00095   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
00096   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
00097   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
00098   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
00099   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
00100   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
00101   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
00102   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
00103   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
00104   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
00105   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
00106 
00107   // We custom lower AND/OR to handle the case where the DAG contain 'ands/ors' 
00108   // with operands comming from setcc fp comparions. This is necessary since 
00109   // the result from these setcc are in a flag registers (FCR31).
00110   setOperationAction(ISD::AND,              MVT::i32,   Custom);
00111   setOperationAction(ISD::OR,               MVT::i32,   Custom);
00112 
00113   // Operations not directly supported by Mips.
00114   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
00115   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
00116   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
00117   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
00118   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
00119   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
00120   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
00121   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
00122   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
00123   setOperationAction(ISD::ROTR,              MVT::i32,   Expand);
00124   setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
00125   setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
00126   setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
00127   setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Expand);
00128   setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Expand);
00129   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
00130   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
00131   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
00132   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
00133   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
00134   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
00135   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
00136   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
00137 
00138   // We don't have line number support yet.
00139   setOperationAction(ISD::DBG_STOPPOINT,     MVT::Other, Expand);
00140   setOperationAction(ISD::DEBUG_LOC,         MVT::Other, Expand);
00141   setOperationAction(ISD::DBG_LABEL,         MVT::Other, Expand);
00142   setOperationAction(ISD::EH_LABEL,          MVT::Other, Expand);
00143 
00144   // Use the default for now
00145   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
00146   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
00147   setOperationAction(ISD::MEMBARRIER,        MVT::Other, Expand);
00148 
00149   if (Subtarget->isSingleFloat())
00150     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
00151 
00152   if (!Subtarget->hasSEInReg()) {
00153     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
00154     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
00155   }
00156 
00157   if (!Subtarget->hasBitCount())
00158     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
00159 
00160   if (!Subtarget->hasSwap())
00161     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
00162 
00163   setStackPointerRegisterToSaveRestore(Mips::SP);
00164   computeRegisterProperties();
00165 }
00166 
00167 MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(EVT VT) const {
00168   return MVT::i32;
00169 }
00170 
00171 /// getFunctionAlignment - Return the Log2 alignment of this function.
00172 unsigned MipsTargetLowering::getFunctionAlignment(const Function *) const {
00173   return 2;
00174 }
00175 
00176 SDValue MipsTargetLowering::
00177 LowerOperation(SDValue Op, SelectionDAG &DAG) 
00178 {
00179   switch (Op.getOpcode()) 
00180   {
00181     case ISD::AND:                return LowerANDOR(Op, DAG);
00182     case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
00183     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
00184     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
00185     case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
00186     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
00187     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
00188     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
00189     case ISD::OR:                 return LowerANDOR(Op, DAG);
00190     case ISD::SELECT:             return LowerSELECT(Op, DAG);
00191     case ISD::SETCC:              return LowerSETCC(Op, DAG);
00192   }
00193   return SDValue();
00194 }
00195 
00196 //===----------------------------------------------------------------------===//
00197 //  Lower helper functions
00198 //===----------------------------------------------------------------------===//
00199 
00200 // AddLiveIn - This helper function adds the specified physical register to the
00201 // MachineFunction as a live in value.  It also creates a corresponding
00202 // virtual register for it.
00203 static unsigned
00204 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC) 
00205 {
00206   assert(RC->contains(PReg) && "Not the correct regclass!");
00207   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
00208   MF.getRegInfo().addLiveIn(PReg, VReg);
00209   return VReg;
00210 }
00211 
00212 // Get fp branch code (not opcode) from condition code.
00213 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
00214   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
00215     return Mips::BRANCH_T;
00216 
00217   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
00218     return Mips::BRANCH_F;
00219 
00220   return Mips::BRANCH_INVALID;
00221 }
00222   
00223 static unsigned FPBranchCodeToOpc(Mips::FPBranchCode BC) {
00224   switch(BC) {
00225     default:
00226       llvm_unreachable("Unknown branch code");
00227     case Mips::BRANCH_T  : return Mips::BC1T;
00228     case Mips::BRANCH_F  : return Mips::BC1F;
00229     case Mips::BRANCH_TL : return Mips::BC1TL;
00230     case Mips::BRANCH_FL : return Mips::BC1FL;
00231   }
00232 }
00233 
00234 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
00235   switch (CC) {
00236   default: llvm_unreachable("Unknown fp condition code!");
00237   case ISD::SETEQ:  
00238   case ISD::SETOEQ: return Mips::FCOND_EQ;
00239   case ISD::SETUNE: return Mips::FCOND_OGL;
00240   case ISD::SETLT:  
00241   case ISD::SETOLT: return Mips::FCOND_OLT;
00242   case ISD::SETGT:  
00243   case ISD::SETOGT: return Mips::FCOND_OGT;
00244   case ISD::SETLE:  
00245   case ISD::SETOLE: return Mips::FCOND_OLE; 
00246   case ISD::SETGE:
00247   case ISD::SETOGE: return Mips::FCOND_OGE;
00248   case ISD::SETULT: return Mips::FCOND_ULT;
00249   case ISD::SETULE: return Mips::FCOND_ULE; 
00250   case ISD::SETUGT: return Mips::FCOND_UGT;
00251   case ISD::SETUGE: return Mips::FCOND_UGE;
00252   case ISD::SETUO:  return Mips::FCOND_UN; 
00253   case ISD::SETO:   return Mips::FCOND_OR;
00254   case ISD::SETNE:  
00255   case ISD::SETONE: return Mips::FCOND_NEQ;
00256   case ISD::SETUEQ: return Mips::FCOND_UEQ;
00257   }
00258 }
00259 
00260 MachineBasicBlock *
00261 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
00262                                                 MachineBasicBlock *BB) const {
00263   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
00264   bool isFPCmp = false;
00265   DebugLoc dl = MI->getDebugLoc();
00266 
00267   switch (MI->getOpcode()) {
00268   default: assert(false && "Unexpected instr type to insert");
00269   case Mips::Select_FCC:
00270   case Mips::Select_FCC_S32:
00271   case Mips::Select_FCC_D32:
00272     isFPCmp = true; // FALL THROUGH
00273   case Mips::Select_CC:
00274   case Mips::Select_CC_S32:
00275   case Mips::Select_CC_D32: {
00276     // To "insert" a SELECT_CC instruction, we actually have to insert the
00277     // diamond control-flow pattern.  The incoming instruction knows the
00278     // destination vreg to set, the condition code register to branch on, the
00279     // true/false values to select between, and a branch opcode to use.
00280     const BasicBlock *LLVM_BB = BB->getBasicBlock();
00281     MachineFunction::iterator It = BB;
00282     ++It;
00283 
00284     //  thisMBB:
00285     //  ...
00286     //   TrueVal = ...
00287     //   setcc r1, r2, r3
00288     //   bNE   r1, r0, copy1MBB
00289     //   fallthrough --> copy0MBB
00290     MachineBasicBlock *thisMBB  = BB;
00291     MachineFunction *F = BB->getParent();
00292     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
00293     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
00294 
00295     // Emit the right instruction according to the type of the operands compared
00296     if (isFPCmp) {
00297       // Find the condiction code present in the setcc operation.
00298       Mips::CondCode CC = (Mips::CondCode)MI->getOperand(4).getImm();
00299       // Get the branch opcode from the branch code.
00300       unsigned Opc = FPBranchCodeToOpc(GetFPBranchCodeFromCond(CC));
00301       BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
00302     } else
00303       BuildMI(BB, dl, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
00304         .addReg(Mips::ZERO).addMBB(sinkMBB);
00305 
00306     F->insert(It, copy0MBB);
00307     F->insert(It, sinkMBB);
00308     // Update machine-CFG edges by first adding all successors of the current
00309     // block to the new block which will contain the Phi node for the select.
00310     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
00311         e = BB->succ_end(); i != e; ++i)
00312       sinkMBB->addSuccessor(*i);
00313     // Next, remove all successors of the current block, and add the true
00314     // and fallthrough blocks as its successors.
00315     while(!BB->succ_empty())
00316       BB->removeSuccessor(BB->succ_begin());
00317     BB->addSuccessor(copy0MBB);
00318     BB->addSuccessor(sinkMBB);
00319 
00320     //  copy0MBB:
00321     //   %FalseValue = ...
00322     //   # fallthrough to sinkMBB
00323     BB = copy0MBB;
00324 
00325     // Update machine-CFG edges
00326     BB->addSuccessor(sinkMBB);
00327 
00328     //  sinkMBB:
00329     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
00330     //  ...
00331     BB = sinkMBB;
00332     BuildMI(BB, dl, TII->get(Mips::PHI), MI->getOperand(0).getReg())
00333       .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
00334       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB);
00335 
00336     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
00337     return BB;
00338   }
00339   }
00340 }
00341 
00342 //===----------------------------------------------------------------------===//
00343 //  Misc Lower Operation implementation
00344 //===----------------------------------------------------------------------===//
00345 
00346 SDValue MipsTargetLowering::
00347 LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG)
00348 {
00349   if (!Subtarget->isMips1())
00350     return Op;
00351 
00352   MachineFunction &MF = DAG.getMachineFunction();
00353   unsigned CCReg = AddLiveIn(MF, Mips::FCR31, Mips::CCRRegisterClass);
00354 
00355   SDValue Chain = DAG.getEntryNode();
00356   DebugLoc dl = Op.getDebugLoc();
00357   SDValue Src = Op.getOperand(0);
00358 
00359   // Set the condition register
00360   SDValue CondReg = DAG.getCopyFromReg(Chain, dl, CCReg, MVT::i32);
00361   CondReg = DAG.getCopyToReg(Chain, dl, Mips::AT, CondReg);
00362   CondReg = DAG.getCopyFromReg(CondReg, dl, Mips::AT, MVT::i32);
00363 
00364   SDValue Cst = DAG.getConstant(3, MVT::i32);
00365   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, CondReg, Cst);
00366   Cst = DAG.getConstant(2, MVT::i32);
00367   SDValue Xor = DAG.getNode(ISD::XOR, dl, MVT::i32, Or, Cst);
00368 
00369   SDValue InFlag(0, 0);
00370   CondReg = DAG.getCopyToReg(Chain, dl, Mips::FCR31, Xor, InFlag);
00371 
00372   // Emit the round instruction and bit convert to integer
00373   SDValue Trunc = DAG.getNode(MipsISD::FPRound, dl, MVT::f32,
00374                               Src, CondReg.getValue(1));
00375   SDValue BitCvt = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Trunc);
00376   return BitCvt;
00377 }
00378 
00379 SDValue MipsTargetLowering::
00380 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG)
00381 {
00382   SDValue Chain = Op.getOperand(0);
00383   SDValue Size = Op.getOperand(1);
00384   DebugLoc dl = Op.getDebugLoc();
00385 
00386   // Get a reference from Mips stack pointer
00387   SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
00388 
00389   // Subtract the dynamic size from the actual stack size to
00390   // obtain the new stack size.
00391   SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
00392 
00393   // The Sub result contains the new stack start address, so it 
00394   // must be placed in the stack pointer register.
00395   Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub);
00396   
00397   // This node always has two return values: a new stack pointer 
00398   // value and a chain
00399   SDValue Ops[2] = { Sub, Chain };
00400   return DAG.getMergeValues(Ops, 2, dl);
00401 }
00402 
00403 SDValue MipsTargetLowering::
00404 LowerANDOR(SDValue Op, SelectionDAG &DAG)
00405 {
00406   SDValue LHS   = Op.getOperand(0);
00407   SDValue RHS   = Op.getOperand(1);
00408   DebugLoc dl   = Op.getDebugLoc();
00409 
00410   if (LHS.getOpcode() != MipsISD::FPCmp || RHS.getOpcode() != MipsISD::FPCmp)
00411     return Op;
00412 
00413   SDValue True  = DAG.getConstant(1, MVT::i32);
00414   SDValue False = DAG.getConstant(0, MVT::i32);
00415 
00416   SDValue LSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(), 
00417                              LHS, True, False, LHS.getOperand(2));
00418   SDValue RSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(), 
00419                              RHS, True, False, RHS.getOperand(2));
00420 
00421   return DAG.getNode(Op.getOpcode(), dl, MVT::i32, LSEL, RSEL);
00422 }
00423 
00424 SDValue MipsTargetLowering::
00425 LowerBRCOND(SDValue Op, SelectionDAG &DAG)
00426 {
00427   // The first operand is the chain, the second is the condition, the third is 
00428   // the block to branch to if the condition is true.
00429   SDValue Chain = Op.getOperand(0);
00430   SDValue Dest = Op.getOperand(2);
00431   DebugLoc dl = Op.getDebugLoc();
00432 
00433   if (Op.getOperand(1).getOpcode() != MipsISD::FPCmp)
00434     return Op;
00435   
00436   SDValue CondRes = Op.getOperand(1);
00437   SDValue CCNode  = CondRes.getOperand(2);
00438   Mips::CondCode CC =
00439     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
00440   SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32); 
00441 
00442   return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode, 
00443              Dest, CondRes);
00444 }
00445 
00446 SDValue MipsTargetLowering::
00447 LowerSETCC(SDValue Op, SelectionDAG &DAG)
00448 {
00449   // The operands to this are the left and right operands to compare (ops #0, 
00450   // and #1) and the condition code to compare them with (op #2) as a 
00451   // CondCodeSDNode.
00452   SDValue LHS = Op.getOperand(0); 
00453   SDValue RHS = Op.getOperand(1);
00454   DebugLoc dl = Op.getDebugLoc();
00455 
00456   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
00457   
00458   return DAG.getNode(MipsISD::FPCmp, dl, Op.getValueType(), LHS, RHS, 
00459                  DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
00460 }
00461 
00462 SDValue MipsTargetLowering::
00463 LowerSELECT(SDValue Op, SelectionDAG &DAG) 
00464 {
00465   SDValue Cond  = Op.getOperand(0); 
00466   SDValue True  = Op.getOperand(1);
00467   SDValue False = Op.getOperand(2);
00468   DebugLoc dl = Op.getDebugLoc();
00469 
00470   // if the incomming condition comes from a integer compare, the select 
00471   // operation must be SelectCC or a conditional move if the subtarget 
00472   // supports it.
00473   if (Cond.getOpcode() != MipsISD::FPCmp) {
00474     if (Subtarget->hasCondMov() && !True.getValueType().isFloatingPoint())
00475       return Op;
00476     return DAG.getNode(MipsISD::SelectCC, dl, True.getValueType(), 
00477                        Cond, True, False);
00478   }
00479 
00480   // if the incomming condition comes from fpcmp, the select
00481   // operation must use FPSelectCC.
00482   SDValue CCNode = Cond.getOperand(2);
00483   return DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(), 
00484                      Cond, True, False, CCNode);
00485 }
00486 
00487 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
00488   // FIXME there isn't actually debug info here
00489   DebugLoc dl = Op.getDebugLoc();
00490   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
00491   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
00492 
00493   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
00494     SDVTList VTs = DAG.getVTList(MVT::i32);
00495     
00496     MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
00497     
00498     // %gp_rel relocation
00499     if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) { 
00500       SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
00501       SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
00502       return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode); 
00503     }
00504     // %hi/%lo relocation
00505     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GA, 1);
00506     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
00507     return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
00508 
00509   } else { // Abicall relocations, TODO: make this cleaner.
00510     SDValue ResNode = DAG.getLoad(MVT::i32, dl, 
00511                                   DAG.getEntryNode(), GA, NULL, 0);
00512     // On functions and global targets not internal linked only
00513     // a load from got/GP is necessary for PIC to work.
00514     if (!GV->hasLocalLinkage() || isa<Function>(GV))
00515       return ResNode;
00516     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
00517     return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
00518   }
00519 
00520   llvm_unreachable("Dont know how to handle GlobalAddress");
00521   return SDValue(0,0);
00522 }
00523 
00524 SDValue MipsTargetLowering::
00525 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
00526 {
00527   llvm_unreachable("TLS not implemented for MIPS.");
00528   return SDValue(); // Not reached
00529 }
00530 
00531 SDValue MipsTargetLowering::
00532 LowerJumpTable(SDValue Op, SelectionDAG &DAG) 
00533 {
00534   SDValue ResNode;
00535   SDValue HiPart; 
00536   // FIXME there isn't actually debug info here
00537   DebugLoc dl = Op.getDebugLoc();
00538 
00539   EVT PtrVT = Op.getValueType();
00540   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
00541   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
00542 
00543   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
00544     SDVTList VTs = DAG.getVTList(MVT::i32);
00545     SDValue Ops[] = { JTI };
00546     HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, Ops, 1);
00547   } else // Emit Load from Global Pointer
00548     HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI, NULL, 0);
00549 
00550   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTI);
00551   ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
00552 
00553   return ResNode;
00554 }
00555 
00556 SDValue MipsTargetLowering::
00557 LowerConstantPool(SDValue Op, SelectionDAG &DAG) 
00558 {
00559   SDValue ResNode;
00560   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
00561   Constant *C = N->getConstVal();
00562   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
00563   // FIXME there isn't actually debug info here
00564   DebugLoc dl = Op.getDebugLoc();
00565 
00566   // gp_rel relocation
00567   // FIXME: we should reference the constant pool using small data sections, 
00568   // but the asm printer currently doens't support this feature without
00569   // hacking it. This feature should come soon so we can uncomment the 
00570   // stuff below.
00571   //if (IsInSmallSection(C->getType())) {
00572   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
00573   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
00574   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode); 
00575   //} else { // %hi/%lo relocation
00576     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CP);
00577     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
00578     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
00579   //}
00580 
00581   return ResNode;
00582 }
00583 
00584 //===----------------------------------------------------------------------===//
00585 //                      Calling Convention Implementation
00586 //===----------------------------------------------------------------------===//
00587 
00588 #include "MipsGenCallingConv.inc"
00589 
00590 //===----------------------------------------------------------------------===//
00591 // TODO: Implement a generic logic using tblgen that can support this. 
00592 // Mips O32 ABI rules:
00593 // ---
00594 // i32 - Passed in A0, A1, A2, A3 and stack
00595 // f32 - Only passed in f32 registers if no int reg has been used yet to hold 
00596 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
00597 // f64 - Only passed in two aliased f32 registers if no int reg has been used 
00598 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is 
00599 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
00600 //       go to stack.
00601 //===----------------------------------------------------------------------===//
00602 
00603 static bool CC_MipsO32(unsigned ValNo, EVT ValVT,
00604                        EVT LocVT, CCValAssign::LocInfo LocInfo,
00605                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
00606 
00607   static const unsigned IntRegsSize=4, FloatRegsSize=2; 
00608 
00609   static const unsigned IntRegs[] = {
00610       Mips::A0, Mips::A1, Mips::A2, Mips::A3
00611   };
00612   static const unsigned F32Regs[] = {
00613       Mips::F12, Mips::F14
00614   };
00615   static const unsigned F64Regs[] = {
00616       Mips::D6, Mips::D7
00617   };
00618 
00619   unsigned Reg=0;
00620   unsigned UnallocIntReg = State.getFirstUnallocated(IntRegs, IntRegsSize);
00621   bool IntRegUsed = (IntRegs[UnallocIntReg] != (unsigned (Mips::A0)));
00622 
00623   // Promote i8 and i16
00624   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
00625     LocVT = MVT::i32;
00626     if (ArgFlags.isSExt())
00627       LocInfo = CCValAssign::SExt;
00628     else if (ArgFlags.isZExt())
00629       LocInfo = CCValAssign::ZExt;
00630     else
00631       LocInfo = CCValAssign::AExt;
00632   }
00633 
00634   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && IntRegUsed)) {
00635     Reg = State.AllocateReg(IntRegs, IntRegsSize);
00636     IntRegUsed = true;
00637     LocVT = MVT::i32;
00638   }
00639 
00640   if (ValVT.isFloatingPoint() && !IntRegUsed) {
00641     if (ValVT == MVT::f32)
00642       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
00643     else
00644       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
00645   }
00646 
00647   if (ValVT == MVT::f64 && IntRegUsed) {
00648     if (UnallocIntReg != IntRegsSize) {
00649       // If we hit register A3 as the first not allocated, we must
00650       // mark it as allocated (shadow) and use the stack instead.
00651       if (IntRegs[UnallocIntReg] != (unsigned (Mips::A3)))
00652         Reg = Mips::A2;
00653       for (;UnallocIntReg < IntRegsSize; ++UnallocIntReg)
00654         State.AllocateReg(UnallocIntReg);
00655     } 
00656     LocVT = MVT::i32;
00657   }
00658 
00659   if (!Reg) {
00660     unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
00661     unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
00662     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
00663   } else
00664     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
00665 
00666   return false; // CC must always match
00667 }
00668 
00669 //===----------------------------------------------------------------------===//
00670 //                  Call Calling Convention Implementation
00671 //===----------------------------------------------------------------------===//
00672 
00673 /// LowerCall - functions arguments are copied from virtual regs to
00674 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
00675 /// TODO: isVarArg, isTailCall.
00676 SDValue
00677 MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
00678                               unsigned CallConv, bool isVarArg,
00679                               bool isTailCall,
00680                               const SmallVectorImpl<ISD::OutputArg> &Outs,
00681                               const SmallVectorImpl<ISD::InputArg> &Ins,
00682                               DebugLoc dl, SelectionDAG &DAG,
00683                               SmallVectorImpl<SDValue> &InVals) {
00684 
00685   MachineFunction &MF = DAG.getMachineFunction();
00686   MachineFrameInfo *MFI = MF.getFrameInfo();
00687 
00688   // Analyze operands of the call, assigning locations to each operand.
00689   SmallVector<CCValAssign, 16> ArgLocs;
00690   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
00691                  *DAG.getContext());
00692 
00693   // To meet O32 ABI, Mips must always allocate 16 bytes on
00694   // the stack (even if less than 4 are used as arguments)
00695   if (Subtarget->isABI_O32()) {
00696     int VTsize = EVT(MVT::i32).getSizeInBits()/8;
00697     MFI->CreateFixedObject(VTsize, (VTsize*3));
00698     CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
00699   } else
00700     CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
00701   
00702   // Get a count of how many bytes are to be pushed on the stack.
00703   unsigned NumBytes = CCInfo.getNextStackOffset();
00704   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
00705 
00706   // With EABI is it possible to have 16 args on registers.
00707   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
00708   SmallVector<SDValue, 8> MemOpChains;
00709 
00710   // First/LastArgStackLoc contains the first/last 
00711   // "at stack" argument location.
00712   int LastArgStackLoc = 0;
00713   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
00714 
00715   // Walk the register/memloc assignments, inserting copies/loads.
00716   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
00717     SDValue Arg = Outs[i].Val;
00718     CCValAssign &VA = ArgLocs[i];
00719 
00720     // Promote the value if needed.
00721     switch (VA.getLocInfo()) {
00722     default: llvm_unreachable("Unknown loc info!");
00723     case CCValAssign::Full: 
00724       if (Subtarget->isABI_O32() && VA.isRegLoc()) {
00725         if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
00726           Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Arg);
00727         if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
00728           Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
00729           SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
00730                                    DAG.getConstant(0, getPointerTy()));
00731           SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
00732                                    DAG.getConstant(1, getPointerTy()));
00733           RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
00734           RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
00735           continue;
00736         }  
00737       }
00738       break;
00739     case CCValAssign::SExt:
00740       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
00741       break;
00742     case CCValAssign::ZExt:
00743       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
00744       break;
00745     case CCValAssign::AExt:
00746       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
00747       break;
00748     }
00749     
00750     // Arguments that can be passed on register must be kept at 
00751     // RegsToPass vector
00752     if (VA.isRegLoc()) {
00753       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
00754       continue;
00755     }
00756     
00757     // Register can't get to this point...
00758     assert(VA.isMemLoc());
00759     
00760     // Create the frame index object for this incoming parameter
00761     // This guarantees that when allocating Local Area the firsts
00762     // 16 bytes which are alwayes reserved won't be overwritten
00763     // if O32 ABI is used. For EABI the first address is zero.
00764     LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
00765     int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
00766                                     LastArgStackLoc);
00767 
00768     SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
00769 
00770     // emit ISD::STORE whichs stores the 
00771     // parameter value to a stack Location
00772     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0));
00773   }
00774 
00775   // Transform all store nodes into one single node because all store
00776   // nodes are independent of each other.
00777   if (!MemOpChains.empty())     
00778     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
00779                         &MemOpChains[0], MemOpChains.size());
00780 
00781   // Build a sequence of copy-to-reg nodes chained together with token 
00782   // chain and flag operands which copy the outgoing args into registers.
00783   // The InFlag in necessary since all emited instructions must be
00784   // stuck together.
00785   SDValue InFlag;
00786   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
00787     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 
00788                              RegsToPass[i].second, InFlag);
00789     InFlag = Chain.getValue(1);
00790   }
00791 
00792   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
00793   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 
00794   // node so that legalize doesn't hack it. 
00795   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 
00796     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
00797   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
00798     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
00799 
00800   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
00801   //             = Chain, Callee, Reg#1, Reg#2, ...  
00802   //
00803   // Returns a chain & a flag for retval copy to use.
00804   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
00805   SmallVector<SDValue, 8> Ops;
00806   Ops.push_back(Chain);
00807   Ops.push_back(Callee);
00808 
00809   // Add argument registers to the end of the list so that they are 
00810   // known live into the call.
00811   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
00812     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
00813                                   RegsToPass[i].second.getValueType()));
00814 
00815   if (InFlag.getNode())
00816     Ops.push_back(InFlag);
00817 
00818   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
00819   InFlag = Chain.getValue(1);
00820 
00821   // Create the CALLSEQ_END node.
00822   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
00823                              DAG.getIntPtrConstant(0, true), InFlag);
00824   InFlag = Chain.getValue(1);
00825 
00826   // Create a stack location to hold GP when PIC is used. This stack 
00827   // location is used on function prologue to save GP and also after all 
00828   // emited CALL's to restore GP. 
00829   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
00830       // Function can have an arbitrary number of calls, so 
00831       // hold the LastArgStackLoc with the biggest offset.
00832       int FI;
00833       MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
00834       if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
00835         LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
00836         // Create the frame index only once. SPOffset here can be anything 
00837         // (this will be fixed on processFunctionBeforeFrameFinalized)
00838         if (MipsFI->getGPStackOffset() == -1) {
00839           FI = MFI->CreateFixedObject(4, 0);
00840           MipsFI->setGPFI(FI);
00841         }
00842         MipsFI->setGPStackOffset(LastArgStackLoc);
00843       }
00844 
00845       // Reload GP value.
00846       FI = MipsFI->getGPFI();
00847       SDValue FIN = DAG.getFrameIndex(FI,getPointerTy());
00848       SDValue GPLoad = DAG.getLoad(MVT::i32, dl, Chain, FIN, NULL, 0);
00849       Chain = GPLoad.getValue(1);
00850       Chain = DAG.getCopyToReg(Chain, dl, DAG.getRegister(Mips::GP, MVT::i32), 
00851                                GPLoad, SDValue(0,0));
00852       InFlag = Chain.getValue(1);
00853   }      
00854 
00855   // Handle result values, copying them out of physregs into vregs that we
00856   // return.
00857   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
00858                          Ins, dl, DAG, InVals);
00859 }
00860 
00861 /// LowerCallResult - Lower the result values of a call into the
00862 /// appropriate copies out of appropriate physical registers.
00863 SDValue
00864 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
00865                                     unsigned CallConv, bool isVarArg,
00866                                     const SmallVectorImpl<ISD::InputArg> &Ins,
00867                                     DebugLoc dl, SelectionDAG &DAG,
00868                                     SmallVectorImpl<SDValue> &InVals) {
00869 
00870   // Assign locations to each value returned by this call.
00871   SmallVector<CCValAssign, 16> RVLocs;
00872   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
00873                  RVLocs, *DAG.getContext());
00874 
00875   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
00876 
00877   // Copy all of the result registers out of their specified physreg.
00878   for (unsigned i = 0; i != RVLocs.size(); ++i) {
00879     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
00880                                RVLocs[i].getValVT(), InFlag).getValue(1);
00881     InFlag = Chain.getValue(2);
00882     InVals.push_back(Chain.getValue(0));
00883   }
00884 
00885   return Chain;
00886 }
00887 
00888 //===----------------------------------------------------------------------===//
00889 //             Formal Arguments Calling Convention Implementation
00890 //===----------------------------------------------------------------------===//
00891 
00892 /// LowerFormalArguments - transform physical registers into
00893 /// virtual registers and generate load operations for
00894 /// arguments places on the stack.
00895 /// TODO: isVarArg
00896 SDValue
00897 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
00898                                          unsigned CallConv, bool isVarArg,
00899                                          const SmallVectorImpl<ISD::InputArg>
00900                                            &Ins,
00901                                          DebugLoc dl, SelectionDAG &DAG,
00902                                          SmallVectorImpl<SDValue> &InVals) {
00903 
00904   MachineFunction &MF = DAG.getMachineFunction();
00905   MachineFrameInfo *MFI = MF.getFrameInfo();
00906   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
00907 
00908   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
00909 
00910   // Assign locations to all of the incoming arguments.
00911   SmallVector<CCValAssign, 16> ArgLocs;
00912   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
00913                  ArgLocs, *DAG.getContext());
00914 
00915   if (Subtarget->isABI_O32())
00916     CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
00917   else
00918     CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
00919 
00920   SDValue StackPtr;
00921 
00922   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
00923 
00924   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
00925     CCValAssign &VA = ArgLocs[i];
00926 
00927     // Arguments stored on registers
00928     if (VA.isRegLoc()) {
00929       EVT RegVT = VA.getLocVT();
00930       TargetRegisterClass *RC = 0;
00931 
00932       if (RegVT == MVT::i32)
00933         RC = Mips::CPURegsRegisterClass; 
00934       else if (RegVT == MVT::f32) 
00935         RC = Mips::FGR32RegisterClass;
00936       else if (RegVT == MVT::f64) {
00937         if (!Subtarget->isSingleFloat()) 
00938           RC = Mips::AFGR64RegisterClass;
00939       } else  
00940         llvm_unreachable("RegVT not supported by LowerFormalArguments Lowering");
00941 
00942       // Transform the arguments stored on 
00943       // physical registers into virtual ones
00944       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
00945       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
00946       
00947       // If this is an 8 or 16-bit value, it has been passed promoted 
00948       // to 32 bits.  Insert an assert[sz]ext to capture this, then 
00949       // truncate to the right size.
00950       if (VA.getLocInfo() != CCValAssign::Full) {
00951         unsigned Opcode = 0;
00952         if (VA.getLocInfo() == CCValAssign::SExt)
00953           Opcode = ISD::AssertSext;
00954         else if (VA.getLocInfo() == CCValAssign::ZExt)
00955           Opcode = ISD::AssertZext;
00956         if (Opcode)
00957           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue, 
00958                                  DAG.getValueType(VA.getValVT()));
00959         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
00960       }
00961 
00962       // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64 
00963       if (Subtarget->isABI_O32()) {
00964         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32) 
00965           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, ArgValue);
00966         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
00967           unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(), 
00968                                     VA.getLocReg()+1, RC);
00969           SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
00970           SDValue Hi = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, ArgValue);
00971           SDValue Lo = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, ArgValue2);
00972           ArgValue = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::f64, Lo, Hi);
00973         }
00974       }
00975 
00976       InVals.push_back(ArgValue);
00977 
00978       // To meet ABI, when VARARGS are passed on registers, the registers
00979       // must have their values written to the caller stack frame. 
00980       if ((isVarArg) && (Subtarget->isABI_O32())) {
00981         if (StackPtr.getNode() == 0)
00982           StackPtr = DAG.getRegister(StackReg, getPointerTy());
00983      
00984         // The stack pointer offset is relative to the caller stack frame. 
00985         // Since the real stack size is unknown here, a negative SPOffset 
00986         // is used so there's a way to adjust these offsets when the stack
00987         // size get known (on EliminateFrameIndex). A dummy SPOffset is 
00988         // used instead of a direct negative address (which is recorded to
00989         // be used on emitPrologue) to avoid mis-calc of the first stack 
00990         // offset on PEI::calculateFrameObjectOffsets.
00991         // Arguments are always 32-bit.
00992         int FI = MFI->CreateFixedObject(4, 0);
00993         MipsFI->recordStoreVarArgsFI(FI, -(4+(i*4)));
00994         SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
00995       
00996         // emit ISD::STORE whichs stores the 
00997         // parameter value to a stack Location
00998         InVals.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff, NULL, 0));
00999       }
01000 
01001     } else { // VA.isRegLoc()
01002 
01003       // sanity check
01004       assert(VA.isMemLoc());
01005       
01006       // The stack pointer offset is relative to the caller stack frame. 
01007       // Since the real stack size is unknown here, a negative SPOffset 
01008       // is used so there's a way to adjust these offsets when the stack
01009       // size get known (on EliminateFrameIndex). A dummy SPOffset is 
01010       // used instead of a direct negative address (which is recorded to
01011       // be used on emitPrologue) to avoid mis-calc of the first stack 
01012       // offset on PEI::calculateFrameObjectOffsets.
01013       // Arguments are always 32-bit.
01014       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
01015       int FI = MFI->CreateFixedObject(ArgSize, 0);
01016       MipsFI->recordLoadArgsFI(FI, -(ArgSize+
01017         (FirstStackArgLoc + VA.getLocMemOffset())));
01018 
01019       // Create load nodes to retrieve arguments from the stack
01020       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
01021       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, NULL, 0));
01022     }
01023   }
01024 
01025   // The mips ABIs for returning structs by value requires that we copy
01026   // the sret argument into $v0 for the return. Save the argument into
01027   // a virtual register so that we can access it from the return points.
01028   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
01029     unsigned Reg = MipsFI->getSRetReturnReg();
01030     if (!Reg) {
01031       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
01032       MipsFI->setSRetReturnReg(Reg);
01033     }
01034     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
01035     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
01036   }
01037 
01038   return Chain;
01039 }
01040 
01041 //===----------------------------------------------------------------------===//
01042 //               Return Value Calling Convention Implementation
01043 //===----------------------------------------------------------------------===//
01044 
01045 SDValue
01046 MipsTargetLowering::LowerReturn(SDValue Chain,
01047                                 unsigned CallConv, bool isVarArg,
01048                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
01049                                 DebugLoc dl, SelectionDAG &DAG) {
01050 
01051   // CCValAssign - represent the assignment of
01052   // the return value to a location
01053   SmallVector<CCValAssign, 16> RVLocs;
01054 
01055   // CCState - Info about the registers and stack slot.
01056   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
01057                  RVLocs, *DAG.getContext());
01058 
01059   // Analize return values.
01060   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
01061 
01062   // If this is the first return lowered for this function, add 
01063   // the regs to the liveout set for the function.
01064   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
01065     for (unsigned i = 0; i != RVLocs.size(); ++i)
01066       if (RVLocs[i].isRegLoc())
01067         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
01068   }
01069 
01070   SDValue Flag;
01071 
01072   // Copy the result values into the output registers.
01073   for (unsigned i = 0; i != RVLocs.size(); ++i) {
01074     CCValAssign &VA = RVLocs[i];
01075     assert(VA.isRegLoc() && "Can only return in registers!");
01076 
01077     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 
01078                              Outs[i].Val, Flag);
01079 
01080     // guarantee that all emitted copies are
01081     // stuck together, avoiding something bad
01082     Flag = Chain.getValue(1);
01083   }
01084 
01085   // The mips ABIs for returning structs by value requires that we copy
01086   // the sret argument into $v0 for the return. We saved the argument into
01087   // a virtual register in the entry block, so now we copy the value out
01088   // and into $v0.
01089   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
01090     MachineFunction &MF      = DAG.getMachineFunction();
01091     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
01092     unsigned Reg = MipsFI->getSRetReturnReg();
01093 
01094     if (!Reg) 
01095       llvm_unreachable("sret virtual register not created in the entry block");
01096     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
01097 
01098     Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
01099     Flag = Chain.getValue(1);
01100   }
01101 
01102   // Return on Mips is always a "jr $ra"
01103   if (Flag.getNode())
01104     return DAG.getNode(MipsISD::Ret, dl, MVT::Other, 
01105                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
01106   else // Return Void
01107     return DAG.getNode(MipsISD::Ret, dl, MVT::Other, 
01108                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
01109 }
01110 
01111 //===----------------------------------------------------------------------===//
01112 //                           Mips Inline Assembly Support
01113 //===----------------------------------------------------------------------===//
01114 
01115 /// getConstraintType - Given a constraint letter, return the type of
01116 /// constraint it is for this target.
01117 MipsTargetLowering::ConstraintType MipsTargetLowering::
01118 getConstraintType(const std::string &Constraint) const 
01119 {
01120   // Mips specific constrainy 
01121   // GCC config/mips/constraints.md
01122   //
01123   // 'd' : An address register. Equivalent to r 
01124   //       unless generating MIPS16 code. 
01125   // 'y' : Equivalent to r; retained for 
01126   //       backwards compatibility. 
01127   // 'f' : Floating Point registers.      
01128   if (Constraint.size() == 1) {
01129     switch (Constraint[0]) {
01130       default : break;
01131       case 'd':     
01132       case 'y': 
01133       case 'f':
01134         return C_RegisterClass;
01135         break;
01136     }
01137   }
01138   return TargetLowering::getConstraintType(Constraint);
01139 }
01140 
01141 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
01142 /// return a list of registers that can be used to satisfy the constraint.
01143 /// This should only be used for C_RegisterClass constraints.
01144 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
01145 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
01146 {
01147   if (Constraint.size() == 1) {
01148     switch (Constraint[0]) {
01149     case 'r':
01150       return std::make_pair(0U, Mips::CPURegsRegisterClass);
01151     case 'f':
01152       if (VT == MVT::f32)
01153         return std::make_pair(0U, Mips::FGR32RegisterClass);
01154       if (VT == MVT::f64)    
01155         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
01156           return std::make_pair(0U, Mips::AFGR64RegisterClass);
01157     }
01158   }
01159   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
01160 }
01161 
01162 /// Given a register class constraint, like 'r', if this corresponds directly
01163 /// to an LLVM register class, return a register of 0 and the register class
01164 /// pointer.
01165 std::vector<unsigned> MipsTargetLowering::
01166 getRegClassForInlineAsmConstraint(const std::string &Constraint,
01167                                   EVT VT) const
01168 {
01169   if (Constraint.size() != 1)
01170     return std::vector<unsigned>();
01171 
01172   switch (Constraint[0]) {         
01173     default : break;
01174     case 'r':
01175     // GCC Mips Constraint Letters
01176     case 'd':     
01177     case 'y': 
01178       return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3, 
01179              Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1, 
01180              Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7, 
01181              Mips::T8, 0);
01182 
01183     case 'f':
01184       if (VT == MVT::f32) {
01185         if (Subtarget->isSingleFloat())
01186           return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
01187                  Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
01188                  Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
01189                  Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
01190                  Mips::F30, Mips::F31, 0);
01191         else
01192           return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8, 
01193                  Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26, 
01194                  Mips::F28, Mips::F30, 0);
01195       }
01196 
01197       if (VT == MVT::f64)    
01198         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
01199           return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4, 
01200                  Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13, 
01201                  Mips::D14, Mips::D15, 0);
01202   }
01203   return std::vector<unsigned>();
01204 }
01205 
01206 bool
01207 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
01208   // The Mips target isn't yet aware of offsets.
01209   return false;
01210 }