MipsISelLowering.cpp revision ca8a2aa921ec8966b1f0708d77e4dc0a6f1a32f8
1//===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that Mips uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "mips-lower"
16#include "MipsISelLowering.h"
17#include "MipsMachineFunction.h"
18#include "MipsTargetMachine.h"
19#include "MipsTargetObjectFile.h"
20#include "MipsSubtarget.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/Intrinsics.h"
25#include "llvm/CallingConv.h"
26#include "llvm/CodeGen/CallingConvLower.h"
27#include "llvm/CodeGen/MachineFrameInfo.h"
28#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/CodeGen/SelectionDAGISel.h"
32#include "llvm/CodeGen/ValueTypes.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/ErrorHandling.h"
35using namespace llvm;
36
37const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
38  switch (Opcode) {
39    case MipsISD::JmpLink    : return "MipsISD::JmpLink";
40    case MipsISD::Hi         : return "MipsISD::Hi";
41    case MipsISD::Lo         : return "MipsISD::Lo";
42    case MipsISD::GPRel      : return "MipsISD::GPRel";
43    case MipsISD::Ret        : return "MipsISD::Ret";
44    case MipsISD::SelectCC   : return "MipsISD::SelectCC";
45    case MipsISD::FPSelectCC : return "MipsISD::FPSelectCC";
46    case MipsISD::FPBrcond   : return "MipsISD::FPBrcond";
47    case MipsISD::FPCmp      : return "MipsISD::FPCmp";
48    case MipsISD::FPRound    : return "MipsISD::FPRound";
49    case MipsISD::MAdd       : return "MipsISD::MAdd";
50    case MipsISD::MAddu      : return "MipsISD::MAddu";
51    case MipsISD::MSub       : return "MipsISD::MSub";
52    case MipsISD::MSubu      : return "MipsISD::MSubu";
53    default                  : return NULL;
54  }
55}
56
57MipsTargetLowering::
58MipsTargetLowering(MipsTargetMachine &TM)
59  : TargetLowering(TM, new MipsTargetObjectFile()) {
60  Subtarget = &TM.getSubtarget<MipsSubtarget>();
61
62  // Mips does not have i1 type, so use i32 for
63  // setcc operations results (slt, sgt, ...).
64  setBooleanContents(ZeroOrOneBooleanContent);
65
66  // Set up the register classes
67  addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
68  addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
69
70  // When dealing with single precision only, use libcalls
71  if (!Subtarget->isSingleFloat())
72    if (!Subtarget->isFP64bit())
73      addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
74
75  // Load extented operations for i1 types must be promoted
76  setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
77  setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
78  setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
79
80  // MIPS doesn't have extending float->double load/store
81  setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
82  setTruncStoreAction(MVT::f64, MVT::f32, Expand);
83
84  // Used by legalize types to correctly generate the setcc result.
85  // Without this, every float setcc comes with a AND/OR with the result,
86  // we don't want this, since the fpcmp result goes to a flag register,
87  // which is used implicitly by brcond and select operations.
88  AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
89
90  // Mips Custom Operations
91  setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
92  setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
93  setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
94  setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
95  setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
96  setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
97  setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
98  setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
99  setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
100  setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
101  setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
102  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
103  setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
104  setOperationAction(ISD::VASTART,            MVT::Other, Custom);
105
106
107  // We custom lower AND/OR to handle the case where the DAG contain 'ands/ors'
108  // with operands comming from setcc fp comparions. This is necessary since
109  // the result from these setcc are in a flag registers (FCR31).
110  setOperationAction(ISD::AND,              MVT::i32,   Custom);
111  setOperationAction(ISD::OR,               MVT::i32,   Custom);
112
113  // Operations not directly supported by Mips.
114  setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
115  setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
116  setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
117  setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
118  setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
119  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
120  setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
121  setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
122  setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
123
124  if (!Subtarget->isMips32r2())
125    setOperationAction(ISD::ROTR, MVT::i32,   Expand);
126
127  setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
128  setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
129  setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
130  setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Expand);
131  setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Expand);
132  setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
133  setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
134  setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
135  setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
136  setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
137  setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
138  setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
139  setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
140  setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
141  setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
142
143  setOperationAction(ISD::EH_LABEL,          MVT::Other, Expand);
144
145  // Use the default for now
146  setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
147  setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
148  setOperationAction(ISD::MEMBARRIER,        MVT::Other, Expand);
149
150  if (Subtarget->isSingleFloat())
151    setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
152
153  if (!Subtarget->hasSEInReg()) {
154    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
155    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
156  }
157
158  if (!Subtarget->hasBitCount())
159    setOperationAction(ISD::CTLZ, MVT::i32, Expand);
160
161  if (!Subtarget->hasSwap())
162    setOperationAction(ISD::BSWAP, MVT::i32, Expand);
163
164  setTargetDAGCombine(ISD::ADDE);
165  setTargetDAGCombine(ISD::SUBE);
166
167  setStackPointerRegisterToSaveRestore(Mips::SP);
168  computeRegisterProperties();
169}
170
171MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(EVT VT) const {
172  return MVT::i32;
173}
174
175/// getFunctionAlignment - Return the Log2 alignment of this function.
176unsigned MipsTargetLowering::getFunctionAlignment(const Function *) const {
177  return 2;
178}
179
180// SelectMadd -
181// Transforms a subgraph in CurDAG if the following pattern is found:
182//  (addc multLo, Lo0), (adde multHi, Hi0),
183// where,
184//  multHi/Lo: product of multiplication
185//  Lo0: initial value of Lo register
186//  Hi0: initial value of Hi register
187// Return true if mattern matching was successful.
188static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
189  // ADDENode's second operand must be a flag output of an ADDC node in order
190  // for the matching to be successful.
191  SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
192
193  if (ADDCNode->getOpcode() != ISD::ADDC)
194    return false;
195
196  SDValue MultHi = ADDENode->getOperand(0);
197  SDValue MultLo = ADDCNode->getOperand(0);
198  SDNode* MultNode = MultHi.getNode();
199  unsigned MultOpc = MultHi.getOpcode();
200
201  // MultHi and MultLo must be generated by the same node,
202  if (MultLo.getNode() != MultNode)
203    return false;
204
205  // and it must be a multiplication.
206  if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
207    return false;
208
209  // MultLo amd MultHi must be the first and second output of MultNode
210  // respectively.
211  if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
212    return false;
213
214  // Transform this to a MADD only if ADDENode and ADDCNode are the only users
215  // of the values of MultNode, in which case MultNode will be removed in later
216  // phases.
217  // If there exist users other than ADDENode or ADDCNode, this function returns
218  // here, which will result in MultNode being mapped to a single MULT
219  // instruction node rather than a pair of MULT and MADD instructions being
220  // produced.
221  if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
222    return false;
223
224  SDValue Chain = CurDAG->getEntryNode();
225  DebugLoc dl = ADDENode->getDebugLoc();
226
227  // create MipsMAdd(u) node
228  MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
229
230  SDValue MAdd = CurDAG->getNode(MultOpc, dl,
231                                 MVT::Glue,
232                                 MultNode->getOperand(0),// Factor 0
233                                 MultNode->getOperand(1),// Factor 1
234                                 ADDCNode->getOperand(1),// Lo0
235                                 ADDENode->getOperand(1));// Hi0
236
237  // create CopyFromReg nodes
238  SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
239                                              MAdd);
240  SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
241                                              Mips::HI, MVT::i32,
242                                              CopyFromLo.getValue(2));
243
244  // replace uses of adde and addc here
245  if (!SDValue(ADDCNode, 0).use_empty())
246    CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
247
248  if (!SDValue(ADDENode, 0).use_empty())
249    CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
250
251  return true;
252}
253
254// SelectMsub -
255// Transforms a subgraph in CurDAG if the following pattern is found:
256//  (addc Lo0, multLo), (sube Hi0, multHi),
257// where,
258//  multHi/Lo: product of multiplication
259//  Lo0: initial value of Lo register
260//  Hi0: initial value of Hi register
261// Return true if mattern matching was successful.
262static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
263  // SUBENode's second operand must be a flag output of an SUBC node in order
264  // for the matching to be successful.
265  SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
266
267  if (SUBCNode->getOpcode() != ISD::SUBC)
268    return false;
269
270  SDValue MultHi = SUBENode->getOperand(1);
271  SDValue MultLo = SUBCNode->getOperand(1);
272  SDNode* MultNode = MultHi.getNode();
273  unsigned MultOpc = MultHi.getOpcode();
274
275  // MultHi and MultLo must be generated by the same node,
276  if (MultLo.getNode() != MultNode)
277    return false;
278
279  // and it must be a multiplication.
280  if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
281    return false;
282
283  // MultLo amd MultHi must be the first and second output of MultNode
284  // respectively.
285  if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
286    return false;
287
288  // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
289  // of the values of MultNode, in which case MultNode will be removed in later
290  // phases.
291  // If there exist users other than SUBENode or SUBCNode, this function returns
292  // here, which will result in MultNode being mapped to a single MULT
293  // instruction node rather than a pair of MULT and MSUB instructions being
294  // produced.
295  if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
296    return false;
297
298  SDValue Chain = CurDAG->getEntryNode();
299  DebugLoc dl = SUBENode->getDebugLoc();
300
301  // create MipsSub(u) node
302  MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
303
304  SDValue MSub = CurDAG->getNode(MultOpc, dl,
305                                 MVT::Glue,
306                                 MultNode->getOperand(0),// Factor 0
307                                 MultNode->getOperand(1),// Factor 1
308                                 SUBCNode->getOperand(0),// Lo0
309                                 SUBENode->getOperand(0));// Hi0
310
311  // create CopyFromReg nodes
312  SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
313                                              MSub);
314  SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
315                                              Mips::HI, MVT::i32,
316                                              CopyFromLo.getValue(2));
317
318  // replace uses of sube and subc here
319  if (!SDValue(SUBCNode, 0).use_empty())
320    CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
321
322  if (!SDValue(SUBENode, 0).use_empty())
323    CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
324
325  return true;
326}
327
328static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
329                                  TargetLowering::DAGCombinerInfo &DCI,
330                                  const MipsSubtarget* Subtarget) {
331  if (DCI.isBeforeLegalize())
332    return SDValue();
333
334  if (Subtarget->isMips32() && SelectMadd(N, &DAG))
335    return SDValue(N, 0);
336
337  return SDValue();
338}
339
340static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
341                                  TargetLowering::DAGCombinerInfo &DCI,
342                                  const MipsSubtarget* Subtarget) {
343  if (DCI.isBeforeLegalize())
344    return SDValue();
345
346  if (Subtarget->isMips32() && SelectMsub(N, &DAG))
347    return SDValue(N, 0);
348
349  return SDValue();
350}
351
352SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
353  const {
354  SelectionDAG &DAG = DCI.DAG;
355  unsigned opc = N->getOpcode();
356
357  switch (opc) {
358  default: break;
359  case ISD::ADDE:
360    return PerformADDECombine(N, DAG, DCI, Subtarget);
361  case ISD::SUBE:
362    return PerformSUBECombine(N, DAG, DCI, Subtarget);
363  }
364
365  return SDValue();
366}
367
368SDValue MipsTargetLowering::
369LowerOperation(SDValue Op, SelectionDAG &DAG) const
370{
371  switch (Op.getOpcode())
372  {
373    case ISD::AND:                return LowerANDOR(Op, DAG);
374    case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
375    case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
376    case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
377    case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
378    case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
379    case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
380    case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
381    case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
382    case ISD::OR:                 return LowerANDOR(Op, DAG);
383    case ISD::SELECT:             return LowerSELECT(Op, DAG);
384    case ISD::SETCC:              return LowerSETCC(Op, DAG);
385    case ISD::VASTART:            return LowerVASTART(Op, DAG);
386  }
387  return SDValue();
388}
389
390//===----------------------------------------------------------------------===//
391//  Lower helper functions
392//===----------------------------------------------------------------------===//
393
394// AddLiveIn - This helper function adds the specified physical register to the
395// MachineFunction as a live in value.  It also creates a corresponding
396// virtual register for it.
397static unsigned
398AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
399{
400  assert(RC->contains(PReg) && "Not the correct regclass!");
401  unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
402  MF.getRegInfo().addLiveIn(PReg, VReg);
403  return VReg;
404}
405
406// Get fp branch code (not opcode) from condition code.
407static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
408  if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
409    return Mips::BRANCH_T;
410
411  if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
412    return Mips::BRANCH_F;
413
414  return Mips::BRANCH_INVALID;
415}
416
417static unsigned FPBranchCodeToOpc(Mips::FPBranchCode BC) {
418  switch(BC) {
419    default:
420      llvm_unreachable("Unknown branch code");
421    case Mips::BRANCH_T  : return Mips::BC1T;
422    case Mips::BRANCH_F  : return Mips::BC1F;
423    case Mips::BRANCH_TL : return Mips::BC1TL;
424    case Mips::BRANCH_FL : return Mips::BC1FL;
425  }
426}
427
428static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
429  switch (CC) {
430  default: llvm_unreachable("Unknown fp condition code!");
431  case ISD::SETEQ:
432  case ISD::SETOEQ: return Mips::FCOND_EQ;
433  case ISD::SETUNE: return Mips::FCOND_OGL;
434  case ISD::SETLT:
435  case ISD::SETOLT: return Mips::FCOND_OLT;
436  case ISD::SETGT:
437  case ISD::SETOGT: return Mips::FCOND_OGT;
438  case ISD::SETLE:
439  case ISD::SETOLE: return Mips::FCOND_OLE;
440  case ISD::SETGE:
441  case ISD::SETOGE: return Mips::FCOND_OGE;
442  case ISD::SETULT: return Mips::FCOND_ULT;
443  case ISD::SETULE: return Mips::FCOND_ULE;
444  case ISD::SETUGT: return Mips::FCOND_UGT;
445  case ISD::SETUGE: return Mips::FCOND_UGE;
446  case ISD::SETUO:  return Mips::FCOND_UN;
447  case ISD::SETO:   return Mips::FCOND_OR;
448  case ISD::SETNE:
449  case ISD::SETONE: return Mips::FCOND_NEQ;
450  case ISD::SETUEQ: return Mips::FCOND_UEQ;
451  }
452}
453
454MachineBasicBlock *
455MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
456                                                MachineBasicBlock *BB) const {
457  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
458  bool isFPCmp = false;
459  DebugLoc dl = MI->getDebugLoc();
460
461  switch (MI->getOpcode()) {
462  default: assert(false && "Unexpected instr type to insert");
463  case Mips::Select_FCC:
464  case Mips::Select_FCC_S32:
465  case Mips::Select_FCC_D32:
466    isFPCmp = true; // FALL THROUGH
467  case Mips::Select_CC:
468  case Mips::Select_CC_S32:
469  case Mips::Select_CC_D32: {
470    // To "insert" a SELECT_CC instruction, we actually have to insert the
471    // diamond control-flow pattern.  The incoming instruction knows the
472    // destination vreg to set, the condition code register to branch on, the
473    // true/false values to select between, and a branch opcode to use.
474    const BasicBlock *LLVM_BB = BB->getBasicBlock();
475    MachineFunction::iterator It = BB;
476    ++It;
477
478    //  thisMBB:
479    //  ...
480    //   TrueVal = ...
481    //   setcc r1, r2, r3
482    //   bNE   r1, r0, copy1MBB
483    //   fallthrough --> copy0MBB
484    MachineBasicBlock *thisMBB  = BB;
485    MachineFunction *F = BB->getParent();
486    MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
487    MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
488    F->insert(It, copy0MBB);
489    F->insert(It, sinkMBB);
490
491    // Transfer the remainder of BB and its successor edges to sinkMBB.
492    sinkMBB->splice(sinkMBB->begin(), BB,
493                    llvm::next(MachineBasicBlock::iterator(MI)),
494                    BB->end());
495    sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
496
497    // Next, add the true and fallthrough blocks as its successors.
498    BB->addSuccessor(copy0MBB);
499    BB->addSuccessor(sinkMBB);
500
501    // Emit the right instruction according to the type of the operands compared
502    if (isFPCmp) {
503      // Find the condiction code present in the setcc operation.
504      Mips::CondCode CC = (Mips::CondCode)MI->getOperand(4).getImm();
505      // Get the branch opcode from the branch code.
506      unsigned Opc = FPBranchCodeToOpc(GetFPBranchCodeFromCond(CC));
507      BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
508    } else
509      BuildMI(BB, dl, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
510        .addReg(Mips::ZERO).addMBB(sinkMBB);
511
512    //  copy0MBB:
513    //   %FalseValue = ...
514    //   # fallthrough to sinkMBB
515    BB = copy0MBB;
516
517    // Update machine-CFG edges
518    BB->addSuccessor(sinkMBB);
519
520    //  sinkMBB:
521    //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
522    //  ...
523    BB = sinkMBB;
524    BuildMI(*BB, BB->begin(), dl,
525            TII->get(Mips::PHI), MI->getOperand(0).getReg())
526      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
527      .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
528
529    MI->eraseFromParent();   // The pseudo instruction is gone now.
530    return BB;
531  }
532  }
533}
534
535//===----------------------------------------------------------------------===//
536//  Misc Lower Operation implementation
537//===----------------------------------------------------------------------===//
538
539SDValue MipsTargetLowering::
540LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) const
541{
542  if (!Subtarget->isMips1())
543    return Op;
544
545  MachineFunction &MF = DAG.getMachineFunction();
546  unsigned CCReg = AddLiveIn(MF, Mips::FCR31, Mips::CCRRegisterClass);
547
548  SDValue Chain = DAG.getEntryNode();
549  DebugLoc dl = Op.getDebugLoc();
550  SDValue Src = Op.getOperand(0);
551
552  // Set the condition register
553  SDValue CondReg = DAG.getCopyFromReg(Chain, dl, CCReg, MVT::i32);
554  CondReg = DAG.getCopyToReg(Chain, dl, Mips::AT, CondReg);
555  CondReg = DAG.getCopyFromReg(CondReg, dl, Mips::AT, MVT::i32);
556
557  SDValue Cst = DAG.getConstant(3, MVT::i32);
558  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, CondReg, Cst);
559  Cst = DAG.getConstant(2, MVT::i32);
560  SDValue Xor = DAG.getNode(ISD::XOR, dl, MVT::i32, Or, Cst);
561
562  SDValue InFlag(0, 0);
563  CondReg = DAG.getCopyToReg(Chain, dl, Mips::FCR31, Xor, InFlag);
564
565  // Emit the round instruction and bit convert to integer
566  SDValue Trunc = DAG.getNode(MipsISD::FPRound, dl, MVT::f32,
567                              Src, CondReg.getValue(1));
568  SDValue BitCvt = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Trunc);
569  return BitCvt;
570}
571
572SDValue MipsTargetLowering::
573LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
574{
575  SDValue Chain = Op.getOperand(0);
576  SDValue Size = Op.getOperand(1);
577  DebugLoc dl = Op.getDebugLoc();
578
579  // Get a reference from Mips stack pointer
580  SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
581
582  // Subtract the dynamic size from the actual stack size to
583  // obtain the new stack size.
584  SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
585
586  // The Sub result contains the new stack start address, so it
587  // must be placed in the stack pointer register.
588  Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub);
589
590  // This node always has two return values: a new stack pointer
591  // value and a chain
592  SDValue Ops[2] = { Sub, Chain };
593  return DAG.getMergeValues(Ops, 2, dl);
594}
595
596SDValue MipsTargetLowering::
597LowerANDOR(SDValue Op, SelectionDAG &DAG) const
598{
599  SDValue LHS   = Op.getOperand(0);
600  SDValue RHS   = Op.getOperand(1);
601  DebugLoc dl   = Op.getDebugLoc();
602
603  if (LHS.getOpcode() != MipsISD::FPCmp || RHS.getOpcode() != MipsISD::FPCmp)
604    return Op;
605
606  SDValue True  = DAG.getConstant(1, MVT::i32);
607  SDValue False = DAG.getConstant(0, MVT::i32);
608
609  SDValue LSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
610                             LHS, True, False, LHS.getOperand(2));
611  SDValue RSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
612                             RHS, True, False, RHS.getOperand(2));
613
614  return DAG.getNode(Op.getOpcode(), dl, MVT::i32, LSEL, RSEL);
615}
616
617SDValue MipsTargetLowering::
618LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
619{
620  // The first operand is the chain, the second is the condition, the third is
621  // the block to branch to if the condition is true.
622  SDValue Chain = Op.getOperand(0);
623  SDValue Dest = Op.getOperand(2);
624  DebugLoc dl = Op.getDebugLoc();
625
626  if (Op.getOperand(1).getOpcode() != MipsISD::FPCmp)
627    return Op;
628
629  SDValue CondRes = Op.getOperand(1);
630  SDValue CCNode  = CondRes.getOperand(2);
631  Mips::CondCode CC =
632    (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
633  SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
634
635  return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
636             Dest, CondRes);
637}
638
639SDValue MipsTargetLowering::
640LowerSETCC(SDValue Op, SelectionDAG &DAG) const
641{
642  // The operands to this are the left and right operands to compare (ops #0,
643  // and #1) and the condition code to compare them with (op #2) as a
644  // CondCodeSDNode.
645  SDValue LHS = Op.getOperand(0);
646  SDValue RHS = Op.getOperand(1);
647  DebugLoc dl = Op.getDebugLoc();
648
649  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
650
651  return DAG.getNode(MipsISD::FPCmp, dl, Op.getValueType(), LHS, RHS,
652                 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
653}
654
655SDValue MipsTargetLowering::
656LowerSELECT(SDValue Op, SelectionDAG &DAG) const
657{
658  SDValue Cond  = Op.getOperand(0);
659  SDValue True  = Op.getOperand(1);
660  SDValue False = Op.getOperand(2);
661  DebugLoc dl = Op.getDebugLoc();
662
663  // if the incomming condition comes from a integer compare, the select
664  // operation must be SelectCC or a conditional move if the subtarget
665  // supports it.
666  if (Cond.getOpcode() != MipsISD::FPCmp) {
667    if (Subtarget->hasCondMov() && !True.getValueType().isFloatingPoint())
668      return Op;
669    return DAG.getNode(MipsISD::SelectCC, dl, True.getValueType(),
670                       Cond, True, False);
671  }
672
673  // if the incomming condition comes from fpcmp, the select
674  // operation must use FPSelectCC.
675  SDValue CCNode = Cond.getOperand(2);
676  return DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
677                     Cond, True, False, CCNode);
678}
679
680SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
681                                               SelectionDAG &DAG) const {
682  // FIXME there isn't actually debug info here
683  DebugLoc dl = Op.getDebugLoc();
684  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
685
686  if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
687    SDVTList VTs = DAG.getVTList(MVT::i32);
688
689    MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
690
691    // %gp_rel relocation
692    if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
693      SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
694                                              MipsII::MO_GPREL);
695      SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
696      SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
697      return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
698    }
699    // %hi/%lo relocation
700    SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
701                                            MipsII::MO_ABS_HILO);
702    SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GA, 1);
703    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
704    return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
705
706  } else {
707    SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
708                                            MipsII::MO_GOT);
709    SDValue ResNode = DAG.getLoad(MVT::i32, dl,
710                                  DAG.getEntryNode(), GA, MachinePointerInfo(),
711                                  false, false, 0);
712    // On functions and global targets not internal linked only
713    // a load from got/GP is necessary for PIC to work.
714    if (!GV->hasLocalLinkage() || isa<Function>(GV))
715      return ResNode;
716    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
717    return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
718  }
719
720  llvm_unreachable("Dont know how to handle GlobalAddress");
721  return SDValue(0,0);
722}
723
724SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
725                                              SelectionDAG &DAG) const {
726  if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
727    assert(false && "implement LowerBlockAddress for -static");
728    return SDValue(0, 0);
729  }
730  else {
731    // FIXME there isn't actually debug info here
732    DebugLoc dl = Op.getDebugLoc();
733    const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
734    SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
735                                              MipsII::MO_GOT);
736    SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
737                                             MipsII::MO_ABS_HILO);
738    SDValue Load = DAG.getLoad(MVT::i32, dl,
739                               DAG.getEntryNode(), BAGOTOffset,
740                               MachinePointerInfo(), false, false, 0);
741    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
742    return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
743  }
744}
745
746SDValue MipsTargetLowering::
747LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
748{
749  llvm_unreachable("TLS not implemented for MIPS.");
750  return SDValue(); // Not reached
751}
752
753SDValue MipsTargetLowering::
754LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
755{
756  SDValue ResNode;
757  SDValue HiPart;
758  // FIXME there isn't actually debug info here
759  DebugLoc dl = Op.getDebugLoc();
760  bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
761  unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HILO;
762
763  EVT PtrVT = Op.getValueType();
764  JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
765
766  SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
767
768  if (!IsPIC) {
769    SDValue Ops[] = { JTI };
770    HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
771  } else // Emit Load from Global Pointer
772    HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
773                         MachinePointerInfo(),
774                         false, false, 0);
775
776  SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTI);
777  ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
778
779  return ResNode;
780}
781
782SDValue MipsTargetLowering::
783LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
784{
785  SDValue ResNode;
786  ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
787  const Constant *C = N->getConstVal();
788  // FIXME there isn't actually debug info here
789  DebugLoc dl = Op.getDebugLoc();
790
791  // gp_rel relocation
792  // FIXME: we should reference the constant pool using small data sections,
793  // but the asm printer currently doens't support this feature without
794  // hacking it. This feature should come soon so we can uncomment the
795  // stuff below.
796  //if (IsInSmallSection(C->getType())) {
797  //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
798  //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
799  //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
800
801  if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
802    SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
803                                      N->getOffset(), MipsII::MO_ABS_HILO);
804    SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CP);
805    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
806    ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
807  } else {
808    SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
809                                      N->getOffset(), MipsII::MO_GOT);
810    SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
811                               CP, MachinePointerInfo::getConstantPool(),
812                               false, false, 0);
813    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
814    ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
815  }
816
817  return ResNode;
818}
819
820SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
821  MachineFunction &MF = DAG.getMachineFunction();
822  MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
823
824  DebugLoc dl = Op.getDebugLoc();
825  SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
826                                 getPointerTy());
827
828  // vastart just stores the address of the VarArgsFrameIndex slot into the
829  // memory location argument.
830  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
831  return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
832                      MachinePointerInfo(SV),
833                      false, false, 0);
834}
835
836//===----------------------------------------------------------------------===//
837//                      Calling Convention Implementation
838//===----------------------------------------------------------------------===//
839
840#include "MipsGenCallingConv.inc"
841
842//===----------------------------------------------------------------------===//
843// TODO: Implement a generic logic using tblgen that can support this.
844// Mips O32 ABI rules:
845// ---
846// i32 - Passed in A0, A1, A2, A3 and stack
847// f32 - Only passed in f32 registers if no int reg has been used yet to hold
848//       an argument. Otherwise, passed in A1, A2, A3 and stack.
849// f64 - Only passed in two aliased f32 registers if no int reg has been used
850//       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
851//       not used, it must be shadowed. If only A3 is avaiable, shadow it and
852//       go to stack.
853//===----------------------------------------------------------------------===//
854
855static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
856                       MVT LocVT, CCValAssign::LocInfo LocInfo,
857                       ISD::ArgFlagsTy ArgFlags, CCState &State) {
858
859  static const unsigned IntRegsSize=4, FloatRegsSize=2;
860
861  static const unsigned IntRegs[] = {
862      Mips::A0, Mips::A1, Mips::A2, Mips::A3
863  };
864  static const unsigned F32Regs[] = {
865      Mips::F12, Mips::F14
866  };
867  static const unsigned F64Regs[] = {
868      Mips::D6, Mips::D7
869  };
870
871  unsigned Reg = 0;
872  static bool IntRegUsed = false;
873
874  // This must be the first arg of the call if no regs have been allocated.
875  // Initialize IntRegUsed in that case.
876  if (IntRegs[State.getFirstUnallocated(IntRegs, IntRegsSize)] == Mips::A0 &&
877      F32Regs[State.getFirstUnallocated(F32Regs, FloatRegsSize)] == Mips::F12 &&
878      F64Regs[State.getFirstUnallocated(F64Regs, FloatRegsSize)] == Mips::D6)
879    IntRegUsed = false;
880
881  // Promote i8 and i16
882  if (LocVT == MVT::i8 || LocVT == MVT::i16) {
883    LocVT = MVT::i32;
884    if (ArgFlags.isSExt())
885      LocInfo = CCValAssign::SExt;
886    else if (ArgFlags.isZExt())
887      LocInfo = CCValAssign::ZExt;
888    else
889      LocInfo = CCValAssign::AExt;
890  }
891
892  if (ValVT == MVT::i32) {
893    Reg = State.AllocateReg(IntRegs, IntRegsSize);
894    IntRegUsed = true;
895  } else if (ValVT == MVT::f32) {
896    // An int reg has to be marked allocated regardless of whether or not
897    // IntRegUsed is true.
898    Reg = State.AllocateReg(IntRegs, IntRegsSize);
899
900    if (IntRegUsed) {
901      if (Reg) // Int reg is available
902        LocVT = MVT::i32;
903    } else {
904      unsigned FReg = State.AllocateReg(F32Regs, FloatRegsSize);
905      if (FReg) // F32 reg is available
906        Reg = FReg;
907      else if (Reg) // No F32 regs are available, but an int reg is available.
908        LocVT = MVT::i32;
909    }
910  } else if (ValVT == MVT::f64) {
911    // Int regs have to be marked allocated regardless of whether or not
912    // IntRegUsed is true.
913    Reg = State.AllocateReg(IntRegs, IntRegsSize);
914    if (Reg == Mips::A1)
915      Reg = State.AllocateReg(IntRegs, IntRegsSize);
916    else if (Reg == Mips::A3)
917      Reg = 0;
918    State.AllocateReg(IntRegs, IntRegsSize);
919
920    // At this point, Reg is A0, A2 or 0, and all the unavailable integer regs
921    // are marked as allocated.
922    if (IntRegUsed) {
923      if (Reg)// if int reg is available
924        LocVT = MVT::i32;
925    } else {
926      unsigned FReg = State.AllocateReg(F64Regs, FloatRegsSize);
927      if (FReg) // F64 reg is available.
928        Reg = FReg;
929      else if (Reg) // No F64 regs are available, but an int reg is available.
930        LocVT = MVT::i32;
931    }
932  } else
933    assert(false && "cannot handle this ValVT");
934
935  if (!Reg) {
936    unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
937    unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
938    State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
939  } else
940    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
941
942  return false; // CC must always match
943}
944
945static bool CC_MipsO32_VarArgs(unsigned ValNo, MVT ValVT,
946                       MVT LocVT, CCValAssign::LocInfo LocInfo,
947                       ISD::ArgFlagsTy ArgFlags, CCState &State) {
948
949  static const unsigned IntRegsSize=4;
950
951  static const unsigned IntRegs[] = {
952      Mips::A0, Mips::A1, Mips::A2, Mips::A3
953  };
954
955  // Promote i8 and i16
956  if (LocVT == MVT::i8 || LocVT == MVT::i16) {
957    LocVT = MVT::i32;
958    if (ArgFlags.isSExt())
959      LocInfo = CCValAssign::SExt;
960    else if (ArgFlags.isZExt())
961      LocInfo = CCValAssign::ZExt;
962    else
963      LocInfo = CCValAssign::AExt;
964  }
965
966  if (ValVT == MVT::i32 || ValVT == MVT::f32) {
967    if (unsigned Reg = State.AllocateReg(IntRegs, IntRegsSize)) {
968      State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::i32, LocInfo));
969      return false;
970    }
971    unsigned Off = State.AllocateStack(4, 4);
972    State.addLoc(CCValAssign::getMem(ValNo, ValVT, Off, LocVT, LocInfo));
973    return false;
974  }
975
976  unsigned UnallocIntReg = State.getFirstUnallocated(IntRegs, IntRegsSize);
977  if (ValVT == MVT::f64) {
978    if (IntRegs[UnallocIntReg] == (unsigned (Mips::A1))) {
979      // A1 can't be used anymore, because 64 bit arguments
980      // must be aligned when copied back to the caller stack
981      State.AllocateReg(IntRegs, IntRegsSize);
982      UnallocIntReg++;
983    }
984
985    if (IntRegs[UnallocIntReg] == (unsigned (Mips::A0)) ||
986        IntRegs[UnallocIntReg] == (unsigned (Mips::A2))) {
987      unsigned Reg = State.AllocateReg(IntRegs, IntRegsSize);
988      State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::i32, LocInfo));
989      // Shadow the next register so it can be used
990      // later to get the other 32bit part.
991      State.AllocateReg(IntRegs, IntRegsSize);
992      return false;
993    }
994
995    // Register is shadowed to preserve alignment, and the
996    // argument goes to a stack location.
997    if (UnallocIntReg != IntRegsSize)
998      State.AllocateReg(IntRegs, IntRegsSize);
999
1000    unsigned Off = State.AllocateStack(8, 8);
1001    State.addLoc(CCValAssign::getMem(ValNo, ValVT, Off, LocVT, LocInfo));
1002    return false;
1003  }
1004
1005  return true; // CC didn't match
1006}
1007
1008//===----------------------------------------------------------------------===//
1009//                  Call Calling Convention Implementation
1010//===----------------------------------------------------------------------===//
1011
1012/// LowerCall - functions arguments are copied from virtual regs to
1013/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1014/// TODO: isTailCall.
1015SDValue
1016MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1017                              CallingConv::ID CallConv, bool isVarArg,
1018                              bool &isTailCall,
1019                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1020                              const SmallVectorImpl<SDValue> &OutVals,
1021                              const SmallVectorImpl<ISD::InputArg> &Ins,
1022                              DebugLoc dl, SelectionDAG &DAG,
1023                              SmallVectorImpl<SDValue> &InVals) const {
1024  // MIPs target does not yet support tail call optimization.
1025  isTailCall = false;
1026
1027  MachineFunction &MF = DAG.getMachineFunction();
1028  MachineFrameInfo *MFI = MF.getFrameInfo();
1029  bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1030
1031  // Analyze operands of the call, assigning locations to each operand.
1032  SmallVector<CCValAssign, 16> ArgLocs;
1033  CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1034                 *DAG.getContext());
1035
1036  // To meet O32 ABI, Mips must always allocate 16 bytes on
1037  // the stack (even if less than 4 are used as arguments)
1038  if (Subtarget->isABI_O32()) {
1039    int VTsize = MVT(MVT::i32).getSizeInBits()/8;
1040    MFI->CreateFixedObject(VTsize, (VTsize*3), true);
1041    CCInfo.AnalyzeCallOperands(Outs,
1042                     isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
1043  } else
1044    CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1045
1046  // Get a count of how many bytes are to be pushed on the stack.
1047  unsigned NumBytes = CCInfo.getNextStackOffset();
1048  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1049
1050  // With EABI is it possible to have 16 args on registers.
1051  SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1052  SmallVector<SDValue, 8> MemOpChains;
1053
1054  // First/LastArgStackLoc contains the first/last
1055  // "at stack" argument location.
1056  int LastArgStackLoc = 0;
1057  unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1058
1059  // Walk the register/memloc assignments, inserting copies/loads.
1060  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1061    SDValue Arg = OutVals[i];
1062    CCValAssign &VA = ArgLocs[i];
1063
1064    // Promote the value if needed.
1065    switch (VA.getLocInfo()) {
1066    default: llvm_unreachable("Unknown loc info!");
1067    case CCValAssign::Full:
1068      if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1069        if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1070          Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1071        if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1072          Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1073          SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1074                                   DAG.getConstant(0, getPointerTy()));
1075          SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1076                                   DAG.getConstant(1, getPointerTy()));
1077          RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1078          RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1079          continue;
1080        }
1081      }
1082      break;
1083    case CCValAssign::SExt:
1084      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1085      break;
1086    case CCValAssign::ZExt:
1087      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1088      break;
1089    case CCValAssign::AExt:
1090      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1091      break;
1092    }
1093
1094    // Arguments that can be passed on register must be kept at
1095    // RegsToPass vector
1096    if (VA.isRegLoc()) {
1097      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1098      continue;
1099    }
1100
1101    // Register can't get to this point...
1102    assert(VA.isMemLoc());
1103
1104    // Create the frame index object for this incoming parameter
1105    // This guarantees that when allocating Local Area the firsts
1106    // 16 bytes which are alwayes reserved won't be overwritten
1107    // if O32 ABI is used. For EABI the first address is zero.
1108    LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
1109    int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1110                                    LastArgStackLoc, true);
1111
1112    SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
1113
1114    // emit ISD::STORE whichs stores the
1115    // parameter value to a stack Location
1116    MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
1117                                       MachinePointerInfo(),
1118                                       false, false, 0));
1119  }
1120
1121  // Transform all store nodes into one single node because all store
1122  // nodes are independent of each other.
1123  if (!MemOpChains.empty())
1124    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1125                        &MemOpChains[0], MemOpChains.size());
1126
1127  // Build a sequence of copy-to-reg nodes chained together with token
1128  // chain and flag operands which copy the outgoing args into registers.
1129  // The InFlag in necessary since all emited instructions must be
1130  // stuck together.
1131  SDValue InFlag;
1132  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1133    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1134                             RegsToPass[i].second, InFlag);
1135    InFlag = Chain.getValue(1);
1136  }
1137
1138  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1139  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1140  // node so that legalize doesn't hack it.
1141  unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
1142  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1143    Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1144                                getPointerTy(), 0, OpFlag);
1145  else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1146    Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
1147                                getPointerTy(), OpFlag);
1148
1149  // MipsJmpLink = #chain, #target_address, #opt_in_flags...
1150  //             = Chain, Callee, Reg#1, Reg#2, ...
1151  //
1152  // Returns a chain & a flag for retval copy to use.
1153  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1154  SmallVector<SDValue, 8> Ops;
1155  Ops.push_back(Chain);
1156  Ops.push_back(Callee);
1157
1158  // Add argument registers to the end of the list so that they are
1159  // known live into the call.
1160  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1161    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1162                                  RegsToPass[i].second.getValueType()));
1163
1164  if (InFlag.getNode())
1165    Ops.push_back(InFlag);
1166
1167  Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
1168  InFlag = Chain.getValue(1);
1169
1170  // Create a stack location to hold GP when PIC is used. This stack
1171  // location is used on function prologue to save GP and also after all
1172  // emited CALL's to restore GP.
1173  if (IsPIC) {
1174      // Function can have an arbitrary number of calls, so
1175      // hold the LastArgStackLoc with the biggest offset.
1176      int FI;
1177      MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1178      if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
1179        LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
1180        // Create the frame index only once. SPOffset here can be anything
1181        // (this will be fixed on processFunctionBeforeFrameFinalized)
1182        if (MipsFI->getGPStackOffset() == -1) {
1183          FI = MFI->CreateFixedObject(4, 0, true);
1184          MipsFI->setGPFI(FI);
1185        }
1186        MipsFI->setGPStackOffset(LastArgStackLoc);
1187      }
1188
1189      // Reload GP value.
1190      FI = MipsFI->getGPFI();
1191      SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1192      SDValue GPLoad = DAG.getLoad(MVT::i32, dl, Chain, FIN,
1193                                   MachinePointerInfo::getFixedStack(FI),
1194                                   false, false, 0);
1195      Chain = GPLoad.getValue(1);
1196      Chain = DAG.getCopyToReg(Chain, dl, DAG.getRegister(Mips::GP, MVT::i32),
1197                               GPLoad, SDValue(0,0));
1198      InFlag = Chain.getValue(1);
1199  }
1200
1201  // Create the CALLSEQ_END node.
1202  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1203                             DAG.getIntPtrConstant(0, true), InFlag);
1204  InFlag = Chain.getValue(1);
1205
1206  // Handle result values, copying them out of physregs into vregs that we
1207  // return.
1208  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1209                         Ins, dl, DAG, InVals);
1210}
1211
1212/// LowerCallResult - Lower the result values of a call into the
1213/// appropriate copies out of appropriate physical registers.
1214SDValue
1215MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1216                                    CallingConv::ID CallConv, bool isVarArg,
1217                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1218                                    DebugLoc dl, SelectionDAG &DAG,
1219                                    SmallVectorImpl<SDValue> &InVals) const {
1220
1221  // Assign locations to each value returned by this call.
1222  SmallVector<CCValAssign, 16> RVLocs;
1223  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1224                 RVLocs, *DAG.getContext());
1225
1226  CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
1227
1228  // Copy all of the result registers out of their specified physreg.
1229  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1230    Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1231                               RVLocs[i].getValVT(), InFlag).getValue(1);
1232    InFlag = Chain.getValue(2);
1233    InVals.push_back(Chain.getValue(0));
1234  }
1235
1236  return Chain;
1237}
1238
1239//===----------------------------------------------------------------------===//
1240//             Formal Arguments Calling Convention Implementation
1241//===----------------------------------------------------------------------===//
1242
1243/// LowerFormalArguments - transform physical registers into virtual registers
1244/// and generate load operations for arguments places on the stack.
1245SDValue
1246MipsTargetLowering::LowerFormalArguments(SDValue Chain,
1247                                        CallingConv::ID CallConv, bool isVarArg,
1248                                        const SmallVectorImpl<ISD::InputArg>
1249                                        &Ins,
1250                                        DebugLoc dl, SelectionDAG &DAG,
1251                                        SmallVectorImpl<SDValue> &InVals)
1252                                          const {
1253
1254  MachineFunction &MF = DAG.getMachineFunction();
1255  MachineFrameInfo *MFI = MF.getFrameInfo();
1256  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1257
1258  unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
1259  MipsFI->setVarArgsFrameIndex(0);
1260
1261  // Used with vargs to acumulate store chains.
1262  std::vector<SDValue> OutChains;
1263
1264  // Keep track of the last register used for arguments
1265  unsigned ArgRegEnd = 0;
1266
1267  // Assign locations to all of the incoming arguments.
1268  SmallVector<CCValAssign, 16> ArgLocs;
1269  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1270                 ArgLocs, *DAG.getContext());
1271
1272  if (Subtarget->isABI_O32())
1273    CCInfo.AnalyzeFormalArguments(Ins,
1274                        isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
1275  else
1276    CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
1277
1278  SDValue StackPtr;
1279
1280  unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1281
1282  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1283    CCValAssign &VA = ArgLocs[i];
1284
1285    // Arguments stored on registers
1286    if (VA.isRegLoc()) {
1287      EVT RegVT = VA.getLocVT();
1288      ArgRegEnd = VA.getLocReg();
1289      TargetRegisterClass *RC = 0;
1290
1291      if (RegVT == MVT::i32)
1292        RC = Mips::CPURegsRegisterClass;
1293      else if (RegVT == MVT::f32)
1294        RC = Mips::FGR32RegisterClass;
1295      else if (RegVT == MVT::f64) {
1296        if (!Subtarget->isSingleFloat())
1297          RC = Mips::AFGR64RegisterClass;
1298      } else
1299        llvm_unreachable("RegVT not supported by FormalArguments Lowering");
1300
1301      // Transform the arguments stored on
1302      // physical registers into virtual ones
1303      unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1304      SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1305
1306      // If this is an 8 or 16-bit value, it has been passed promoted
1307      // to 32 bits.  Insert an assert[sz]ext to capture this, then
1308      // truncate to the right size.
1309      if (VA.getLocInfo() != CCValAssign::Full) {
1310        unsigned Opcode = 0;
1311        if (VA.getLocInfo() == CCValAssign::SExt)
1312          Opcode = ISD::AssertSext;
1313        else if (VA.getLocInfo() == CCValAssign::ZExt)
1314          Opcode = ISD::AssertZext;
1315        if (Opcode)
1316          ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
1317                                 DAG.getValueType(VA.getValVT()));
1318        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1319      }
1320
1321      // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
1322      if (Subtarget->isABI_O32()) {
1323        if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
1324          ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
1325        if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
1326          unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
1327                                    VA.getLocReg()+1, RC);
1328          SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
1329          SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, ArgValue2, ArgValue);
1330          ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Pair);
1331        }
1332      }
1333
1334      InVals.push_back(ArgValue);
1335    } else { // VA.isRegLoc()
1336
1337      // sanity check
1338      assert(VA.isMemLoc());
1339
1340      // The last argument is not a register anymore
1341      ArgRegEnd = 0;
1342
1343      // The stack pointer offset is relative to the caller stack frame.
1344      // Since the real stack size is unknown here, a negative SPOffset
1345      // is used so there's a way to adjust these offsets when the stack
1346      // size get known (on EliminateFrameIndex). A dummy SPOffset is
1347      // used instead of a direct negative address (which is recorded to
1348      // be used on emitPrologue) to avoid mis-calc of the first stack
1349      // offset on PEI::calculateFrameObjectOffsets.
1350      // Arguments are always 32-bit.
1351      unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1352      int FI = MFI->CreateFixedObject(ArgSize, 0, true);
1353      MipsFI->recordLoadArgsFI(FI, -(ArgSize+
1354        (FirstStackArgLoc + VA.getLocMemOffset())));
1355
1356      // Create load nodes to retrieve arguments from the stack
1357      SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1358      InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1359                                   MachinePointerInfo::getFixedStack(FI),
1360                                   false, false, 0));
1361    }
1362  }
1363
1364  // The mips ABIs for returning structs by value requires that we copy
1365  // the sret argument into $v0 for the return. Save the argument into
1366  // a virtual register so that we can access it from the return points.
1367  if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1368    unsigned Reg = MipsFI->getSRetReturnReg();
1369    if (!Reg) {
1370      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
1371      MipsFI->setSRetReturnReg(Reg);
1372    }
1373    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1374    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1375  }
1376
1377  // To meet ABI, when VARARGS are passed on registers, the registers
1378  // must have their values written to the caller stack frame. If the last
1379  // argument was placed in the stack, there's no need to save any register.
1380  if ((isVarArg) && (Subtarget->isABI_O32() && ArgRegEnd)) {
1381    if (StackPtr.getNode() == 0)
1382      StackPtr = DAG.getRegister(StackReg, getPointerTy());
1383
1384    // The last register argument that must be saved is Mips::A3
1385    TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
1386    unsigned StackLoc = ArgLocs.size()-1;
1387
1388    for (++ArgRegEnd; ArgRegEnd <= Mips::A3; ++ArgRegEnd, ++StackLoc) {
1389      unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1390      SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
1391
1392      int FI = MFI->CreateFixedObject(4, 0, true);
1393      MipsFI->recordStoreVarArgsFI(FI, -(4+(StackLoc*4)));
1394      SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
1395      OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
1396                                       MachinePointerInfo(),
1397                                       false, false, 0));
1398
1399      // Record the frame index of the first variable argument
1400      // which is a value necessary to VASTART.
1401      if (!MipsFI->getVarArgsFrameIndex())
1402        MipsFI->setVarArgsFrameIndex(FI);
1403    }
1404  }
1405
1406  // All stores are grouped in one node to allow the matching between
1407  // the size of Ins and InVals. This only happens when on varg functions
1408  if (!OutChains.empty()) {
1409    OutChains.push_back(Chain);
1410    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1411                        &OutChains[0], OutChains.size());
1412  }
1413
1414  return Chain;
1415}
1416
1417//===----------------------------------------------------------------------===//
1418//               Return Value Calling Convention Implementation
1419//===----------------------------------------------------------------------===//
1420
1421SDValue
1422MipsTargetLowering::LowerReturn(SDValue Chain,
1423                                CallingConv::ID CallConv, bool isVarArg,
1424                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1425                                const SmallVectorImpl<SDValue> &OutVals,
1426                                DebugLoc dl, SelectionDAG &DAG) const {
1427
1428  // CCValAssign - represent the assignment of
1429  // the return value to a location
1430  SmallVector<CCValAssign, 16> RVLocs;
1431
1432  // CCState - Info about the registers and stack slot.
1433  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1434                 RVLocs, *DAG.getContext());
1435
1436  // Analize return values.
1437  CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
1438
1439  // If this is the first return lowered for this function, add
1440  // the regs to the liveout set for the function.
1441  if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1442    for (unsigned i = 0; i != RVLocs.size(); ++i)
1443      if (RVLocs[i].isRegLoc())
1444        DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1445  }
1446
1447  SDValue Flag;
1448
1449  // Copy the result values into the output registers.
1450  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1451    CCValAssign &VA = RVLocs[i];
1452    assert(VA.isRegLoc() && "Can only return in registers!");
1453
1454    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1455                             OutVals[i], Flag);
1456
1457    // guarantee that all emitted copies are
1458    // stuck together, avoiding something bad
1459    Flag = Chain.getValue(1);
1460  }
1461
1462  // The mips ABIs for returning structs by value requires that we copy
1463  // the sret argument into $v0 for the return. We saved the argument into
1464  // a virtual register in the entry block, so now we copy the value out
1465  // and into $v0.
1466  if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1467    MachineFunction &MF      = DAG.getMachineFunction();
1468    MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1469    unsigned Reg = MipsFI->getSRetReturnReg();
1470
1471    if (!Reg)
1472      llvm_unreachable("sret virtual register not created in the entry block");
1473    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1474
1475    Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
1476    Flag = Chain.getValue(1);
1477  }
1478
1479  // Return on Mips is always a "jr $ra"
1480  if (Flag.getNode())
1481    return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1482                       Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
1483  else // Return Void
1484    return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1485                       Chain, DAG.getRegister(Mips::RA, MVT::i32));
1486}
1487
1488//===----------------------------------------------------------------------===//
1489//                           Mips Inline Assembly Support
1490//===----------------------------------------------------------------------===//
1491
1492/// getConstraintType - Given a constraint letter, return the type of
1493/// constraint it is for this target.
1494MipsTargetLowering::ConstraintType MipsTargetLowering::
1495getConstraintType(const std::string &Constraint) const
1496{
1497  // Mips specific constrainy
1498  // GCC config/mips/constraints.md
1499  //
1500  // 'd' : An address register. Equivalent to r
1501  //       unless generating MIPS16 code.
1502  // 'y' : Equivalent to r; retained for
1503  //       backwards compatibility.
1504  // 'f' : Floating Point registers.
1505  if (Constraint.size() == 1) {
1506    switch (Constraint[0]) {
1507      default : break;
1508      case 'd':
1509      case 'y':
1510      case 'f':
1511        return C_RegisterClass;
1512        break;
1513    }
1514  }
1515  return TargetLowering::getConstraintType(Constraint);
1516}
1517
1518/// Examine constraint type and operand type and determine a weight value.
1519/// This object must already have been set up with the operand type
1520/// and the current alternative constraint selected.
1521TargetLowering::ConstraintWeight
1522MipsTargetLowering::getSingleConstraintMatchWeight(
1523    AsmOperandInfo &info, const char *constraint) const {
1524  ConstraintWeight weight = CW_Invalid;
1525  Value *CallOperandVal = info.CallOperandVal;
1526    // If we don't have a value, we can't do a match,
1527    // but allow it at the lowest weight.
1528  if (CallOperandVal == NULL)
1529    return CW_Default;
1530  const Type *type = CallOperandVal->getType();
1531  // Look at the constraint type.
1532  switch (*constraint) {
1533  default:
1534    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1535    break;
1536  case 'd':
1537  case 'y':
1538    if (type->isIntegerTy())
1539      weight = CW_Register;
1540    break;
1541  case 'f':
1542    if (type->isFloatTy())
1543      weight = CW_Register;
1544    break;
1545  }
1546  return weight;
1547}
1548
1549/// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1550/// return a list of registers that can be used to satisfy the constraint.
1551/// This should only be used for C_RegisterClass constraints.
1552std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
1553getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
1554{
1555  if (Constraint.size() == 1) {
1556    switch (Constraint[0]) {
1557    case 'r':
1558      return std::make_pair(0U, Mips::CPURegsRegisterClass);
1559    case 'f':
1560      if (VT == MVT::f32)
1561        return std::make_pair(0U, Mips::FGR32RegisterClass);
1562      if (VT == MVT::f64)
1563        if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1564          return std::make_pair(0U, Mips::AFGR64RegisterClass);
1565    }
1566  }
1567  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1568}
1569
1570/// Given a register class constraint, like 'r', if this corresponds directly
1571/// to an LLVM register class, return a register of 0 and the register class
1572/// pointer.
1573std::vector<unsigned> MipsTargetLowering::
1574getRegClassForInlineAsmConstraint(const std::string &Constraint,
1575                                  EVT VT) const
1576{
1577  if (Constraint.size() != 1)
1578    return std::vector<unsigned>();
1579
1580  switch (Constraint[0]) {
1581    default : break;
1582    case 'r':
1583    // GCC Mips Constraint Letters
1584    case 'd':
1585    case 'y':
1586      return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
1587             Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
1588             Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
1589             Mips::T8, 0);
1590
1591    case 'f':
1592      if (VT == MVT::f32) {
1593        if (Subtarget->isSingleFloat())
1594          return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1595                 Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1596                 Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1597                 Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1598                 Mips::F30, Mips::F31, 0);
1599        else
1600          return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
1601                 Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
1602                 Mips::F28, Mips::F30, 0);
1603      }
1604
1605      if (VT == MVT::f64)
1606        if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1607          return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
1608                 Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
1609                 Mips::D14, Mips::D15, 0);
1610  }
1611  return std::vector<unsigned>();
1612}
1613
1614bool
1615MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1616  // The Mips target isn't yet aware of offsets.
1617  return false;
1618}
1619
1620bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1621  if (VT != MVT::f32 && VT != MVT::f64)
1622    return false;
1623  if (Imm.isNegZero())
1624    return false;
1625  return Imm.isZero();
1626}
1627