Set nomacro before emitting the sequence of instructions that set global pointer
[oota-llvm.git] / lib / Target / Mips / MipsISelLowering.cpp
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 "InstPrinter/MipsInstPrinter.h"
27 #include "MCTargetDesc/MipsBaseInfo.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 using namespace llvm;
38
39 // If I is a shifted mask, set the size (Size) and the first bit of the 
40 // mask (Pos), and return true.
41 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).  
42 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
43   if (!isUInt<32>(I) || !isShiftedMask_32(I))
44      return false;
45
46   Size = CountPopulation_32(I);
47   Pos = CountTrailingZeros_32(I);
48   return true;
49 }
50
51 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
52   switch (Opcode) {
53   case MipsISD::JmpLink:           return "MipsISD::JmpLink";
54   case MipsISD::Hi:                return "MipsISD::Hi";
55   case MipsISD::Lo:                return "MipsISD::Lo";
56   case MipsISD::GPRel:             return "MipsISD::GPRel";
57   case MipsISD::TlsGd:             return "MipsISD::TlsGd";
58   case MipsISD::TprelHi:           return "MipsISD::TprelHi";
59   case MipsISD::TprelLo:           return "MipsISD::TprelLo";
60   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
61   case MipsISD::Ret:               return "MipsISD::Ret";
62   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
63   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
64   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
65   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
66   case MipsISD::FPRound:           return "MipsISD::FPRound";
67   case MipsISD::MAdd:              return "MipsISD::MAdd";
68   case MipsISD::MAddu:             return "MipsISD::MAddu";
69   case MipsISD::MSub:              return "MipsISD::MSub";
70   case MipsISD::MSubu:             return "MipsISD::MSubu";
71   case MipsISD::DivRem:            return "MipsISD::DivRem";
72   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
73   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
74   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
75   case MipsISD::WrapperPIC:        return "MipsISD::WrapperPIC";
76   case MipsISD::DynAlloc:          return "MipsISD::DynAlloc";
77   case MipsISD::Sync:              return "MipsISD::Sync";
78   case MipsISD::Ext:               return "MipsISD::Ext";
79   case MipsISD::Ins:               return "MipsISD::Ins";
80   default:                         return NULL;
81   }
82 }
83
84 MipsTargetLowering::
85 MipsTargetLowering(MipsTargetMachine &TM)
86   : TargetLowering(TM, new MipsTargetObjectFile()),
87     Subtarget(&TM.getSubtarget<MipsSubtarget>()),
88     HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
89     IsO32(Subtarget->isABI_O32()) {
90
91   // Mips does not have i1 type, so use i32 for
92   // setcc operations results (slt, sgt, ...).
93   setBooleanContents(ZeroOrOneBooleanContent);
94   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
95
96   // Set up the register classes
97   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
98   addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
99
100   if (HasMips64)
101     addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
102
103   // When dealing with single precision only, use libcalls
104   if (!Subtarget->isSingleFloat()) {
105     if (HasMips64)
106       addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
107     else
108       addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
109   }
110
111   // Load extented operations for i1 types must be promoted
112   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
113   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
114   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
115
116   // MIPS doesn't have extending float->double load/store
117   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
118   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
119
120   // Used by legalize types to correctly generate the setcc result.
121   // Without this, every float setcc comes with a AND/OR with the result,
122   // we don't want this, since the fpcmp result goes to a flag register,
123   // which is used implicitly by brcond and select operations.
124   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
125
126   // Mips Custom Operations
127   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
128   setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
129   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
130   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
131   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
132   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
133   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
134   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
135   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
136   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
137   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
138   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
139
140   setOperationAction(ISD::SDIV, MVT::i32, Expand);
141   setOperationAction(ISD::SREM, MVT::i32, Expand);
142   setOperationAction(ISD::UDIV, MVT::i32, Expand);
143   setOperationAction(ISD::UREM, MVT::i32, Expand);
144   setOperationAction(ISD::SDIV, MVT::i64, Expand);
145   setOperationAction(ISD::SREM, MVT::i64, Expand);
146   setOperationAction(ISD::UDIV, MVT::i64, Expand);
147   setOperationAction(ISD::UREM, MVT::i64, Expand);
148
149   // Operations not directly supported by Mips.
150   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
151   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
152   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
153   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
154   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
155   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
156   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
157   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
158   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
159   setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
160
161   if (!Subtarget->hasMips32r2())
162     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
163
164   if (!Subtarget->hasMips64r2())
165     setOperationAction(ISD::ROTR, MVT::i64,   Expand);
166
167   setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
168   setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
169   setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
170   setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Custom);
171   setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Custom);
172   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
173   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
174   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
175   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
176   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
177   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
178   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
179   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
180   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
181   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
182   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
183   setOperationAction(ISD::FMA,               MVT::f32,   Expand);
184   setOperationAction(ISD::FMA,               MVT::f64,   Expand);
185
186   setOperationAction(ISD::EXCEPTIONADDR,     MVT::i32, Expand);
187   setOperationAction(ISD::EHSELECTION,       MVT::i32, Expand);
188
189   setOperationAction(ISD::VAARG,             MVT::Other, Expand);
190   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
191   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
192
193   // Use the default for now
194   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
195   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
196
197   setOperationAction(ISD::MEMBARRIER,        MVT::Other, Custom);
198   setOperationAction(ISD::ATOMIC_FENCE,      MVT::Other, Custom);  
199
200   setOperationAction(ISD::ATOMIC_LOAD,       MVT::i32,    Expand);  
201   setOperationAction(ISD::ATOMIC_STORE,      MVT::i32,    Expand);  
202
203   setInsertFencesForAtomic(true);
204
205   if (Subtarget->isSingleFloat())
206     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
207
208   if (!Subtarget->hasSEInReg()) {
209     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
210     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
211   }
212
213   if (!Subtarget->hasBitCount())
214     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
215
216   if (!Subtarget->hasSwap())
217     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
218
219   setTargetDAGCombine(ISD::ADDE);
220   setTargetDAGCombine(ISD::SUBE);
221   setTargetDAGCombine(ISD::SDIVREM);
222   setTargetDAGCombine(ISD::UDIVREM);
223   setTargetDAGCombine(ISD::SETCC);
224   setTargetDAGCombine(ISD::AND);
225   setTargetDAGCombine(ISD::OR);
226
227   setMinFunctionAlignment(2);
228
229   setStackPointerRegisterToSaveRestore(Mips::SP);
230   computeRegisterProperties();
231
232   setExceptionPointerRegister(Mips::A0);
233   setExceptionSelectorRegister(Mips::A1);
234 }
235
236 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
237   MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
238   return SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16; 
239 }
240
241 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
242   return MVT::i32;
243 }
244
245 // SelectMadd -
246 // Transforms a subgraph in CurDAG if the following pattern is found:
247 //  (addc multLo, Lo0), (adde multHi, Hi0),
248 // where,
249 //  multHi/Lo: product of multiplication
250 //  Lo0: initial value of Lo register
251 //  Hi0: initial value of Hi register
252 // Return true if pattern matching was successful.
253 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
254   // ADDENode's second operand must be a flag output of an ADDC node in order
255   // for the matching to be successful.
256   SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
257
258   if (ADDCNode->getOpcode() != ISD::ADDC)
259     return false;
260
261   SDValue MultHi = ADDENode->getOperand(0);
262   SDValue MultLo = ADDCNode->getOperand(0);
263   SDNode* MultNode = MultHi.getNode();
264   unsigned MultOpc = MultHi.getOpcode();
265
266   // MultHi and MultLo must be generated by the same node,
267   if (MultLo.getNode() != MultNode)
268     return false;
269
270   // and it must be a multiplication.
271   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
272     return false;
273
274   // MultLo amd MultHi must be the first and second output of MultNode
275   // respectively.
276   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
277     return false;
278
279   // Transform this to a MADD only if ADDENode and ADDCNode are the only users
280   // of the values of MultNode, in which case MultNode will be removed in later
281   // phases.
282   // If there exist users other than ADDENode or ADDCNode, this function returns
283   // here, which will result in MultNode being mapped to a single MULT
284   // instruction node rather than a pair of MULT and MADD instructions being
285   // produced.
286   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
287     return false;
288
289   SDValue Chain = CurDAG->getEntryNode();
290   DebugLoc dl = ADDENode->getDebugLoc();
291
292   // create MipsMAdd(u) node
293   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
294
295   SDValue MAdd = CurDAG->getNode(MultOpc, dl,
296                                  MVT::Glue,
297                                  MultNode->getOperand(0),// Factor 0
298                                  MultNode->getOperand(1),// Factor 1
299                                  ADDCNode->getOperand(1),// Lo0
300                                  ADDENode->getOperand(1));// Hi0
301
302   // create CopyFromReg nodes
303   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
304                                               MAdd);
305   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
306                                               Mips::HI, MVT::i32,
307                                               CopyFromLo.getValue(2));
308
309   // replace uses of adde and addc here
310   if (!SDValue(ADDCNode, 0).use_empty())
311     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
312
313   if (!SDValue(ADDENode, 0).use_empty())
314     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
315
316   return true;
317 }
318
319 // SelectMsub -
320 // Transforms a subgraph in CurDAG if the following pattern is found:
321 //  (addc Lo0, multLo), (sube Hi0, multHi),
322 // where,
323 //  multHi/Lo: product of multiplication
324 //  Lo0: initial value of Lo register
325 //  Hi0: initial value of Hi register
326 // Return true if pattern matching was successful.
327 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
328   // SUBENode's second operand must be a flag output of an SUBC node in order
329   // for the matching to be successful.
330   SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
331
332   if (SUBCNode->getOpcode() != ISD::SUBC)
333     return false;
334
335   SDValue MultHi = SUBENode->getOperand(1);
336   SDValue MultLo = SUBCNode->getOperand(1);
337   SDNode* MultNode = MultHi.getNode();
338   unsigned MultOpc = MultHi.getOpcode();
339
340   // MultHi and MultLo must be generated by the same node,
341   if (MultLo.getNode() != MultNode)
342     return false;
343
344   // and it must be a multiplication.
345   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
346     return false;
347
348   // MultLo amd MultHi must be the first and second output of MultNode
349   // respectively.
350   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
351     return false;
352
353   // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
354   // of the values of MultNode, in which case MultNode will be removed in later
355   // phases.
356   // If there exist users other than SUBENode or SUBCNode, this function returns
357   // here, which will result in MultNode being mapped to a single MULT
358   // instruction node rather than a pair of MULT and MSUB instructions being
359   // produced.
360   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
361     return false;
362
363   SDValue Chain = CurDAG->getEntryNode();
364   DebugLoc dl = SUBENode->getDebugLoc();
365
366   // create MipsSub(u) node
367   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
368
369   SDValue MSub = CurDAG->getNode(MultOpc, dl,
370                                  MVT::Glue,
371                                  MultNode->getOperand(0),// Factor 0
372                                  MultNode->getOperand(1),// Factor 1
373                                  SUBCNode->getOperand(0),// Lo0
374                                  SUBENode->getOperand(0));// Hi0
375
376   // create CopyFromReg nodes
377   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
378                                               MSub);
379   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
380                                               Mips::HI, MVT::i32,
381                                               CopyFromLo.getValue(2));
382
383   // replace uses of sube and subc here
384   if (!SDValue(SUBCNode, 0).use_empty())
385     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
386
387   if (!SDValue(SUBENode, 0).use_empty())
388     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
389
390   return true;
391 }
392
393 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
394                                   TargetLowering::DAGCombinerInfo &DCI,
395                                   const MipsSubtarget* Subtarget) {
396   if (DCI.isBeforeLegalize())
397     return SDValue();
398
399   if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
400       SelectMadd(N, &DAG))
401     return SDValue(N, 0);
402
403   return SDValue();
404 }
405
406 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
407                                   TargetLowering::DAGCombinerInfo &DCI,
408                                   const MipsSubtarget* Subtarget) {
409   if (DCI.isBeforeLegalize())
410     return SDValue();
411
412   if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
413       SelectMsub(N, &DAG))
414     return SDValue(N, 0);
415
416   return SDValue();
417 }
418
419 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
420                                     TargetLowering::DAGCombinerInfo &DCI,
421                                     const MipsSubtarget* Subtarget) {
422   if (DCI.isBeforeLegalizeOps())
423     return SDValue();
424
425   EVT Ty = N->getValueType(0);
426   unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64; 
427   unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64; 
428   unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
429                                                   MipsISD::DivRemU;
430   DebugLoc dl = N->getDebugLoc();
431
432   SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
433                                N->getOperand(0), N->getOperand(1));
434   SDValue InChain = DAG.getEntryNode();
435   SDValue InGlue = DivRem;
436
437   // insert MFLO
438   if (N->hasAnyUseOfValue(0)) {
439     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
440                                             InGlue);
441     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
442     InChain = CopyFromLo.getValue(1);
443     InGlue = CopyFromLo.getValue(2);
444   }
445
446   // insert MFHI
447   if (N->hasAnyUseOfValue(1)) {
448     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
449                                             HI, Ty, InGlue);
450     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
451   }
452
453   return SDValue();
454 }
455
456 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
457   switch (CC) {
458   default: llvm_unreachable("Unknown fp condition code!");
459   case ISD::SETEQ:
460   case ISD::SETOEQ: return Mips::FCOND_OEQ;
461   case ISD::SETUNE: return Mips::FCOND_UNE;
462   case ISD::SETLT:
463   case ISD::SETOLT: return Mips::FCOND_OLT;
464   case ISD::SETGT:
465   case ISD::SETOGT: return Mips::FCOND_OGT;
466   case ISD::SETLE:
467   case ISD::SETOLE: return Mips::FCOND_OLE;
468   case ISD::SETGE:
469   case ISD::SETOGE: return Mips::FCOND_OGE;
470   case ISD::SETULT: return Mips::FCOND_ULT;
471   case ISD::SETULE: return Mips::FCOND_ULE;
472   case ISD::SETUGT: return Mips::FCOND_UGT;
473   case ISD::SETUGE: return Mips::FCOND_UGE;
474   case ISD::SETUO:  return Mips::FCOND_UN;
475   case ISD::SETO:   return Mips::FCOND_OR;
476   case ISD::SETNE:
477   case ISD::SETONE: return Mips::FCOND_ONE;
478   case ISD::SETUEQ: return Mips::FCOND_UEQ;
479   }
480 }
481
482
483 // Returns true if condition code has to be inverted.
484 static bool InvertFPCondCode(Mips::CondCode CC) {
485   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
486     return false;
487
488   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
489     return true;
490
491   assert(false && "Illegal Condition Code");
492   return false;
493 }
494
495 // Creates and returns an FPCmp node from a setcc node.
496 // Returns Op if setcc is not a floating point comparison.
497 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
498   // must be a SETCC node
499   if (Op.getOpcode() != ISD::SETCC)
500     return Op;
501
502   SDValue LHS = Op.getOperand(0);
503
504   if (!LHS.getValueType().isFloatingPoint())
505     return Op;
506
507   SDValue RHS = Op.getOperand(1);
508   DebugLoc dl = Op.getDebugLoc();
509
510   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
511   // node if necessary.
512   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
513
514   return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
515                      DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
516 }
517
518 // Creates and returns a CMovFPT/F node.
519 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
520                             SDValue False, DebugLoc DL) {
521   bool invert = InvertFPCondCode((Mips::CondCode)
522                                  cast<ConstantSDNode>(Cond.getOperand(2))
523                                  ->getSExtValue());
524
525   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
526                      True.getValueType(), True, False, Cond);
527 }
528
529 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
530                                    TargetLowering::DAGCombinerInfo &DCI,
531                                    const MipsSubtarget* Subtarget) {
532   if (DCI.isBeforeLegalizeOps())
533     return SDValue();
534
535   SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
536
537   if (Cond.getOpcode() != MipsISD::FPCmp)
538     return SDValue();
539
540   SDValue True  = DAG.getConstant(1, MVT::i32);
541   SDValue False = DAG.getConstant(0, MVT::i32);
542
543   return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
544 }
545
546 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
547                                  TargetLowering::DAGCombinerInfo &DCI,
548                                  const MipsSubtarget* Subtarget) {
549   // Pattern match EXT.
550   //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
551   //  => ext $dst, $src, size, pos
552   if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
553     return SDValue();
554
555   SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
556   
557   // Op's first operand must be a shift right.
558   if (ShiftRight.getOpcode() != ISD::SRA && ShiftRight.getOpcode() != ISD::SRL)
559     return SDValue();
560
561   // The second operand of the shift must be an immediate.
562   uint64_t Pos;
563   ConstantSDNode *CN;
564   if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
565     return SDValue();
566   
567   Pos = CN->getZExtValue();
568
569   uint64_t SMPos, SMSize;
570   // Op's second operand must be a shifted mask.
571   if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
572       !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
573     return SDValue();
574
575   // Return if the shifted mask does not start at bit 0 or the sum of its size
576   // and Pos exceeds the word's size.
577   if (SMPos != 0 || Pos + SMSize > 32)
578     return SDValue();
579
580   return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), MVT::i32,
581                      ShiftRight.getOperand(0),
582                      DAG.getConstant(Pos, MVT::i32),
583                      DAG.getConstant(SMSize, MVT::i32));
584 }
585   
586 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
587                                 TargetLowering::DAGCombinerInfo &DCI,
588                                 const MipsSubtarget* Subtarget) {
589   // Pattern match INS.
590   //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
591   //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1 
592   //  => ins $dst, $src, size, pos, $src1
593   if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
594     return SDValue();
595
596   SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
597   uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
598   ConstantSDNode *CN;
599
600   // See if Op's first operand matches (and $src1 , mask0).
601   if (And0.getOpcode() != ISD::AND)
602     return SDValue();
603
604   if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
605       !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
606     return SDValue();
607
608   // See if Op's second operand matches (and (shl $src, pos), mask1).
609   if (And1.getOpcode() != ISD::AND)
610     return SDValue();
611   
612   if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
613       !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
614     return SDValue();
615
616   // The shift masks must have the same position and size.
617   if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
618     return SDValue();
619
620   SDValue Shl = And1.getOperand(0);
621   if (Shl.getOpcode() != ISD::SHL)
622     return SDValue();
623
624   if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
625     return SDValue();
626
627   unsigned Shamt = CN->getZExtValue();
628
629   // Return if the shift amount and the first bit position of mask are not the
630   // same.  
631   if (Shamt != SMPos0)
632     return SDValue();
633   
634   return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), MVT::i32,
635                      Shl.getOperand(0),
636                      DAG.getConstant(SMPos0, MVT::i32),
637                      DAG.getConstant(SMSize0, MVT::i32),
638                      And0.getOperand(0));  
639 }
640   
641 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
642   const {
643   SelectionDAG &DAG = DCI.DAG;
644   unsigned opc = N->getOpcode();
645
646   switch (opc) {
647   default: break;
648   case ISD::ADDE:
649     return PerformADDECombine(N, DAG, DCI, Subtarget);
650   case ISD::SUBE:
651     return PerformSUBECombine(N, DAG, DCI, Subtarget);
652   case ISD::SDIVREM:
653   case ISD::UDIVREM:
654     return PerformDivRemCombine(N, DAG, DCI, Subtarget);
655   case ISD::SETCC:
656     return PerformSETCCCombine(N, DAG, DCI, Subtarget);
657   case ISD::AND:
658     return PerformANDCombine(N, DAG, DCI, Subtarget);
659   case ISD::OR:
660     return PerformORCombine(N, DAG, DCI, Subtarget);
661   }
662
663   return SDValue();
664 }
665
666 SDValue MipsTargetLowering::
667 LowerOperation(SDValue Op, SelectionDAG &DAG) const
668 {
669   switch (Op.getOpcode())
670   {
671     case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
672     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
673     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
674     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
675     case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
676     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
677     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
678     case ISD::SELECT:             return LowerSELECT(Op, DAG);
679     case ISD::VASTART:            return LowerVASTART(Op, DAG);
680     case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
681     case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
682     case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, DAG);
683     case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
684   }
685   return SDValue();
686 }
687
688 //===----------------------------------------------------------------------===//
689 //  Lower helper functions
690 //===----------------------------------------------------------------------===//
691
692 // AddLiveIn - This helper function adds the specified physical register to the
693 // MachineFunction as a live in value.  It also creates a corresponding
694 // virtual register for it.
695 static unsigned
696 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
697 {
698   assert(RC->contains(PReg) && "Not the correct regclass!");
699   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
700   MF.getRegInfo().addLiveIn(PReg, VReg);
701   return VReg;
702 }
703
704 // Get fp branch code (not opcode) from condition code.
705 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
706   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
707     return Mips::BRANCH_T;
708
709   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
710     return Mips::BRANCH_F;
711
712   return Mips::BRANCH_INVALID;
713 }
714
715 /*
716 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
717                                         DebugLoc dl,
718                                         const MipsSubtarget* Subtarget,
719                                         const TargetInstrInfo *TII,
720                                         bool isFPCmp, unsigned Opc) {
721   // There is no need to expand CMov instructions if target has
722   // conditional moves.
723   if (Subtarget->hasCondMov())
724     return BB;
725
726   // To "insert" a SELECT_CC instruction, we actually have to insert the
727   // diamond control-flow pattern.  The incoming instruction knows the
728   // destination vreg to set, the condition code register to branch on, the
729   // true/false values to select between, and a branch opcode to use.
730   const BasicBlock *LLVM_BB = BB->getBasicBlock();
731   MachineFunction::iterator It = BB;
732   ++It;
733
734   //  thisMBB:
735   //  ...
736   //   TrueVal = ...
737   //   setcc r1, r2, r3
738   //   bNE   r1, r0, copy1MBB
739   //   fallthrough --> copy0MBB
740   MachineBasicBlock *thisMBB  = BB;
741   MachineFunction *F = BB->getParent();
742   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
743   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
744   F->insert(It, copy0MBB);
745   F->insert(It, sinkMBB);
746
747   // Transfer the remainder of BB and its successor edges to sinkMBB.
748   sinkMBB->splice(sinkMBB->begin(), BB,
749                   llvm::next(MachineBasicBlock::iterator(MI)),
750                   BB->end());
751   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
752
753   // Next, add the true and fallthrough blocks as its successors.
754   BB->addSuccessor(copy0MBB);
755   BB->addSuccessor(sinkMBB);
756
757   // Emit the right instruction according to the type of the operands compared
758   if (isFPCmp)
759     BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
760   else
761     BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
762       .addReg(Mips::ZERO).addMBB(sinkMBB);
763
764   //  copy0MBB:
765   //   %FalseValue = ...
766   //   # fallthrough to sinkMBB
767   BB = copy0MBB;
768
769   // Update machine-CFG edges
770   BB->addSuccessor(sinkMBB);
771
772   //  sinkMBB:
773   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
774   //  ...
775   BB = sinkMBB;
776
777   if (isFPCmp)
778     BuildMI(*BB, BB->begin(), dl,
779             TII->get(Mips::PHI), MI->getOperand(0).getReg())
780       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
781       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
782   else
783     BuildMI(*BB, BB->begin(), dl,
784             TII->get(Mips::PHI), MI->getOperand(0).getReg())
785       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
786       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
787
788   MI->eraseFromParent();   // The pseudo instruction is gone now.
789   return BB;
790 }
791 */
792 MachineBasicBlock *
793 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
794                                                 MachineBasicBlock *BB) const {
795   switch (MI->getOpcode()) {
796   default:
797     assert(false && "Unexpected instr type to insert");
798     return NULL;
799   case Mips::ATOMIC_LOAD_ADD_I8:
800   case Mips::ATOMIC_LOAD_ADD_I8_P8:
801     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
802   case Mips::ATOMIC_LOAD_ADD_I16:
803   case Mips::ATOMIC_LOAD_ADD_I16_P8:
804     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
805   case Mips::ATOMIC_LOAD_ADD_I32:
806   case Mips::ATOMIC_LOAD_ADD_I32_P8:
807     return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
808   case Mips::ATOMIC_LOAD_ADD_I64:
809   case Mips::ATOMIC_LOAD_ADD_I64_P8:
810     return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
811
812   case Mips::ATOMIC_LOAD_AND_I8:
813   case Mips::ATOMIC_LOAD_AND_I8_P8:
814     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
815   case Mips::ATOMIC_LOAD_AND_I16:
816   case Mips::ATOMIC_LOAD_AND_I16_P8:
817     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
818   case Mips::ATOMIC_LOAD_AND_I32:
819   case Mips::ATOMIC_LOAD_AND_I32_P8:
820     return EmitAtomicBinary(MI, BB, 4, Mips::AND);
821   case Mips::ATOMIC_LOAD_AND_I64:
822   case Mips::ATOMIC_LOAD_AND_I64_P8:
823     return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
824
825   case Mips::ATOMIC_LOAD_OR_I8:
826   case Mips::ATOMIC_LOAD_OR_I8_P8:
827     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
828   case Mips::ATOMIC_LOAD_OR_I16:
829   case Mips::ATOMIC_LOAD_OR_I16_P8:
830     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
831   case Mips::ATOMIC_LOAD_OR_I32:
832   case Mips::ATOMIC_LOAD_OR_I32_P8:
833     return EmitAtomicBinary(MI, BB, 4, Mips::OR);
834   case Mips::ATOMIC_LOAD_OR_I64:
835   case Mips::ATOMIC_LOAD_OR_I64_P8:
836     return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
837
838   case Mips::ATOMIC_LOAD_XOR_I8:
839   case Mips::ATOMIC_LOAD_XOR_I8_P8:
840     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
841   case Mips::ATOMIC_LOAD_XOR_I16:
842   case Mips::ATOMIC_LOAD_XOR_I16_P8:
843     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
844   case Mips::ATOMIC_LOAD_XOR_I32:
845   case Mips::ATOMIC_LOAD_XOR_I32_P8:
846     return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
847   case Mips::ATOMIC_LOAD_XOR_I64:
848   case Mips::ATOMIC_LOAD_XOR_I64_P8:
849     return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
850
851   case Mips::ATOMIC_LOAD_NAND_I8:
852   case Mips::ATOMIC_LOAD_NAND_I8_P8:
853     return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
854   case Mips::ATOMIC_LOAD_NAND_I16:
855   case Mips::ATOMIC_LOAD_NAND_I16_P8:
856     return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
857   case Mips::ATOMIC_LOAD_NAND_I32:
858   case Mips::ATOMIC_LOAD_NAND_I32_P8:
859     return EmitAtomicBinary(MI, BB, 4, 0, true);
860   case Mips::ATOMIC_LOAD_NAND_I64:
861   case Mips::ATOMIC_LOAD_NAND_I64_P8:
862     return EmitAtomicBinary(MI, BB, 8, 0, true);
863
864   case Mips::ATOMIC_LOAD_SUB_I8:
865   case Mips::ATOMIC_LOAD_SUB_I8_P8:
866     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
867   case Mips::ATOMIC_LOAD_SUB_I16:
868   case Mips::ATOMIC_LOAD_SUB_I16_P8:
869     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
870   case Mips::ATOMIC_LOAD_SUB_I32:
871   case Mips::ATOMIC_LOAD_SUB_I32_P8:
872     return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
873   case Mips::ATOMIC_LOAD_SUB_I64:
874   case Mips::ATOMIC_LOAD_SUB_I64_P8:
875     return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
876
877   case Mips::ATOMIC_SWAP_I8:
878   case Mips::ATOMIC_SWAP_I8_P8:
879     return EmitAtomicBinaryPartword(MI, BB, 1, 0);
880   case Mips::ATOMIC_SWAP_I16:
881   case Mips::ATOMIC_SWAP_I16_P8:
882     return EmitAtomicBinaryPartword(MI, BB, 2, 0);
883   case Mips::ATOMIC_SWAP_I32:
884   case Mips::ATOMIC_SWAP_I32_P8:
885     return EmitAtomicBinary(MI, BB, 4, 0);
886   case Mips::ATOMIC_SWAP_I64:
887   case Mips::ATOMIC_SWAP_I64_P8:
888     return EmitAtomicBinary(MI, BB, 8, 0);
889
890   case Mips::ATOMIC_CMP_SWAP_I8:
891   case Mips::ATOMIC_CMP_SWAP_I8_P8:
892     return EmitAtomicCmpSwapPartword(MI, BB, 1);
893   case Mips::ATOMIC_CMP_SWAP_I16:
894   case Mips::ATOMIC_CMP_SWAP_I16_P8:
895     return EmitAtomicCmpSwapPartword(MI, BB, 2);
896   case Mips::ATOMIC_CMP_SWAP_I32:
897   case Mips::ATOMIC_CMP_SWAP_I32_P8:
898     return EmitAtomicCmpSwap(MI, BB, 4);
899   case Mips::ATOMIC_CMP_SWAP_I64:
900   case Mips::ATOMIC_CMP_SWAP_I64_P8:
901     return EmitAtomicCmpSwap(MI, BB, 8);
902   }
903 }
904
905 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
906 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
907 MachineBasicBlock *
908 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
909                                      unsigned Size, unsigned BinOpcode,
910                                      bool Nand) const {
911   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
912
913   MachineFunction *MF = BB->getParent();
914   MachineRegisterInfo &RegInfo = MF->getRegInfo();
915   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
916   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
917   DebugLoc dl = MI->getDebugLoc();
918   unsigned LL, SC, AND, NOR, ZERO, BEQ;
919
920   if (Size == 4) {
921     LL = IsN64 ? Mips::LL_P8 : Mips::LL;
922     SC = IsN64 ? Mips::SC_P8 : Mips::SC;
923     AND = Mips::AND;
924     NOR = Mips::NOR;
925     ZERO = Mips::ZERO;
926     BEQ = Mips::BEQ;
927   }
928   else {
929     LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
930     SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
931     AND = Mips::AND64;
932     NOR = Mips::NOR64;
933     ZERO = Mips::ZERO_64;
934     BEQ = Mips::BEQ64;
935   }
936
937   unsigned OldVal = MI->getOperand(0).getReg();
938   unsigned Ptr = MI->getOperand(1).getReg();
939   unsigned Incr = MI->getOperand(2).getReg();
940
941   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
942   unsigned AndRes = RegInfo.createVirtualRegister(RC);
943   unsigned Success = RegInfo.createVirtualRegister(RC);
944
945   // insert new blocks after the current block
946   const BasicBlock *LLVM_BB = BB->getBasicBlock();
947   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
948   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
949   MachineFunction::iterator It = BB;
950   ++It;
951   MF->insert(It, loopMBB);
952   MF->insert(It, exitMBB);
953
954   // Transfer the remainder of BB and its successor edges to exitMBB.
955   exitMBB->splice(exitMBB->begin(), BB,
956                   llvm::next(MachineBasicBlock::iterator(MI)),
957                   BB->end());
958   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
959
960   //  thisMBB:
961   //    ...
962   //    fallthrough --> loopMBB
963   BB->addSuccessor(loopMBB);
964   loopMBB->addSuccessor(loopMBB);
965   loopMBB->addSuccessor(exitMBB);
966
967   //  loopMBB:
968   //    ll oldval, 0(ptr)
969   //    <binop> storeval, oldval, incr
970   //    sc success, storeval, 0(ptr)
971   //    beq success, $0, loopMBB
972   BB = loopMBB;
973   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
974   if (Nand) {
975     //  and andres, oldval, incr
976     //  nor storeval, $0, andres
977     BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
978     BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
979   } else if (BinOpcode) {
980     //  <binop> storeval, oldval, incr
981     BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
982   } else {
983     StoreVal = Incr;
984   }
985   BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
986   BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
987
988   MI->eraseFromParent();   // The instruction is gone now.
989
990   return exitMBB;
991 }
992
993 MachineBasicBlock *
994 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
995                                              MachineBasicBlock *BB,
996                                              unsigned Size, unsigned BinOpcode,
997                                              bool Nand) const {
998   assert((Size == 1 || Size == 2) &&
999       "Unsupported size for EmitAtomicBinaryPartial.");
1000
1001   MachineFunction *MF = BB->getParent();
1002   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1003   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1004   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1005   DebugLoc dl = MI->getDebugLoc();
1006   unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1007   unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1008
1009   unsigned Dest = MI->getOperand(0).getReg();
1010   unsigned Ptr = MI->getOperand(1).getReg();
1011   unsigned Incr = MI->getOperand(2).getReg();
1012
1013   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1014   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1015   unsigned Mask = RegInfo.createVirtualRegister(RC);
1016   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1017   unsigned NewVal = RegInfo.createVirtualRegister(RC);
1018   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1019   unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1020   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1021   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1022   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1023   unsigned AndRes = RegInfo.createVirtualRegister(RC);
1024   unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1025   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1026   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1027   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1028   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1029   unsigned SllRes = RegInfo.createVirtualRegister(RC);
1030   unsigned Success = RegInfo.createVirtualRegister(RC);
1031
1032   // insert new blocks after the current block
1033   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1034   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1035   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1036   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1037   MachineFunction::iterator It = BB;
1038   ++It;
1039   MF->insert(It, loopMBB);
1040   MF->insert(It, sinkMBB);
1041   MF->insert(It, exitMBB);
1042
1043   // Transfer the remainder of BB and its successor edges to exitMBB.
1044   exitMBB->splice(exitMBB->begin(), BB,
1045                   llvm::next(MachineBasicBlock::iterator(MI)),
1046                   BB->end());
1047   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1048
1049   BB->addSuccessor(loopMBB);
1050   loopMBB->addSuccessor(loopMBB);
1051   loopMBB->addSuccessor(sinkMBB);
1052   sinkMBB->addSuccessor(exitMBB);
1053
1054   //  thisMBB:
1055   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1056   //    and     alignedaddr,ptr,masklsb2
1057   //    andi    ptrlsb2,ptr,3
1058   //    sll     shiftamt,ptrlsb2,3
1059   //    ori     maskupper,$0,255               # 0xff
1060   //    sll     mask,maskupper,shiftamt
1061   //    nor     mask2,$0,mask
1062   //    sll     incr2,incr,shiftamt
1063
1064   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1065   BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1066     .addReg(Mips::ZERO).addImm(-4);
1067   BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1068     .addReg(Ptr).addReg(MaskLSB2);
1069   BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1070   BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1071   BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1072     .addReg(Mips::ZERO).addImm(MaskImm);
1073   BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1074     .addReg(ShiftAmt).addReg(MaskUpper);
1075   BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1076   BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1077
1078
1079   // atomic.load.binop
1080   // loopMBB:
1081   //   ll      oldval,0(alignedaddr)
1082   //   binop   binopres,oldval,incr2
1083   //   and     newval,binopres,mask
1084   //   and     maskedoldval0,oldval,mask2
1085   //   or      storeval,maskedoldval0,newval
1086   //   sc      success,storeval,0(alignedaddr)
1087   //   beq     success,$0,loopMBB
1088
1089   // atomic.swap
1090   // loopMBB:
1091   //   ll      oldval,0(alignedaddr)
1092   //   and     newval,incr2,mask
1093   //   and     maskedoldval0,oldval,mask2
1094   //   or      storeval,maskedoldval0,newval
1095   //   sc      success,storeval,0(alignedaddr)
1096   //   beq     success,$0,loopMBB
1097
1098   BB = loopMBB;
1099   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1100   if (Nand) {
1101     //  and andres, oldval, incr2
1102     //  nor binopres, $0, andres
1103     //  and newval, binopres, mask
1104     BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1105     BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1106       .addReg(Mips::ZERO).addReg(AndRes);
1107     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1108   } else if (BinOpcode) {
1109     //  <binop> binopres, oldval, incr2
1110     //  and newval, binopres, mask
1111     BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1112     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1113   } else {// atomic.swap
1114     //  and newval, incr2, mask
1115     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1116   }
1117     
1118   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1119     .addReg(OldVal).addReg(Mask2);
1120   BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1121     .addReg(MaskedOldVal0).addReg(NewVal);
1122   BuildMI(BB, dl, TII->get(SC), Success)
1123     .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1124   BuildMI(BB, dl, TII->get(Mips::BEQ))
1125     .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1126
1127   //  sinkMBB:
1128   //    and     maskedoldval1,oldval,mask
1129   //    srl     srlres,maskedoldval1,shiftamt
1130   //    sll     sllres,srlres,24
1131   //    sra     dest,sllres,24
1132   BB = sinkMBB;
1133   int64_t ShiftImm = (Size == 1) ? 24 : 16;
1134
1135   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1136     .addReg(OldVal).addReg(Mask);
1137   BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1138       .addReg(ShiftAmt).addReg(MaskedOldVal1);
1139   BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1140       .addReg(SrlRes).addImm(ShiftImm);
1141   BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1142       .addReg(SllRes).addImm(ShiftImm);
1143
1144   MI->eraseFromParent();   // The instruction is gone now.
1145
1146   return exitMBB;
1147 }
1148
1149 MachineBasicBlock *
1150 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1151                                       MachineBasicBlock *BB,
1152                                       unsigned Size) const {
1153   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1154
1155   MachineFunction *MF = BB->getParent();
1156   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1157   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1158   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1159   DebugLoc dl = MI->getDebugLoc();
1160   unsigned LL, SC, ZERO, BNE, BEQ;
1161
1162   if (Size == 4) {
1163     LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1164     SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1165     ZERO = Mips::ZERO;
1166     BNE = Mips::BNE;
1167     BEQ = Mips::BEQ;
1168   }
1169   else {
1170     LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1171     SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1172     ZERO = Mips::ZERO_64;
1173     BNE = Mips::BNE64;
1174     BEQ = Mips::BEQ64;
1175   }
1176
1177   unsigned Dest    = MI->getOperand(0).getReg();
1178   unsigned Ptr     = MI->getOperand(1).getReg();
1179   unsigned OldVal  = MI->getOperand(2).getReg();
1180   unsigned NewVal  = MI->getOperand(3).getReg();
1181
1182   unsigned Success = RegInfo.createVirtualRegister(RC);
1183
1184   // insert new blocks after the current block
1185   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1186   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1187   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1188   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1189   MachineFunction::iterator It = BB;
1190   ++It;
1191   MF->insert(It, loop1MBB);
1192   MF->insert(It, loop2MBB);
1193   MF->insert(It, exitMBB);
1194
1195   // Transfer the remainder of BB and its successor edges to exitMBB.
1196   exitMBB->splice(exitMBB->begin(), BB,
1197                   llvm::next(MachineBasicBlock::iterator(MI)),
1198                   BB->end());
1199   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1200
1201   //  thisMBB:
1202   //    ...
1203   //    fallthrough --> loop1MBB
1204   BB->addSuccessor(loop1MBB);
1205   loop1MBB->addSuccessor(exitMBB);
1206   loop1MBB->addSuccessor(loop2MBB);
1207   loop2MBB->addSuccessor(loop1MBB);
1208   loop2MBB->addSuccessor(exitMBB);
1209
1210   // loop1MBB:
1211   //   ll dest, 0(ptr)
1212   //   bne dest, oldval, exitMBB
1213   BB = loop1MBB;
1214   BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1215   BuildMI(BB, dl, TII->get(BNE))
1216     .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1217
1218   // loop2MBB:
1219   //   sc success, newval, 0(ptr)
1220   //   beq success, $0, loop1MBB
1221   BB = loop2MBB;
1222   BuildMI(BB, dl, TII->get(SC), Success)
1223     .addReg(NewVal).addReg(Ptr).addImm(0);
1224   BuildMI(BB, dl, TII->get(BEQ))
1225     .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1226
1227   MI->eraseFromParent();   // The instruction is gone now.
1228
1229   return exitMBB;
1230 }
1231
1232 MachineBasicBlock *
1233 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1234                                               MachineBasicBlock *BB,
1235                                               unsigned Size) const {
1236   assert((Size == 1 || Size == 2) &&
1237       "Unsupported size for EmitAtomicCmpSwapPartial.");
1238
1239   MachineFunction *MF = BB->getParent();
1240   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1241   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1242   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1243   DebugLoc dl = MI->getDebugLoc();
1244   unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1245   unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1246
1247   unsigned Dest    = MI->getOperand(0).getReg();
1248   unsigned Ptr     = MI->getOperand(1).getReg();
1249   unsigned CmpVal  = MI->getOperand(2).getReg();
1250   unsigned NewVal  = MI->getOperand(3).getReg();
1251
1252   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1253   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1254   unsigned Mask = RegInfo.createVirtualRegister(RC);
1255   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1256   unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1257   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1258   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1259   unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1260   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1261   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1262   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1263   unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1264   unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1265   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1266   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1267   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1268   unsigned SllRes = RegInfo.createVirtualRegister(RC);
1269   unsigned Success = RegInfo.createVirtualRegister(RC);
1270
1271   // insert new blocks after the current block
1272   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1273   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1274   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1275   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1276   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1277   MachineFunction::iterator It = BB;
1278   ++It;
1279   MF->insert(It, loop1MBB);
1280   MF->insert(It, loop2MBB);
1281   MF->insert(It, sinkMBB);
1282   MF->insert(It, exitMBB);
1283
1284   // Transfer the remainder of BB and its successor edges to exitMBB.
1285   exitMBB->splice(exitMBB->begin(), BB,
1286                   llvm::next(MachineBasicBlock::iterator(MI)),
1287                   BB->end());
1288   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1289
1290   BB->addSuccessor(loop1MBB);
1291   loop1MBB->addSuccessor(sinkMBB);
1292   loop1MBB->addSuccessor(loop2MBB);
1293   loop2MBB->addSuccessor(loop1MBB);
1294   loop2MBB->addSuccessor(sinkMBB);
1295   sinkMBB->addSuccessor(exitMBB);
1296
1297   // FIXME: computation of newval2 can be moved to loop2MBB.
1298   //  thisMBB:
1299   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1300   //    and     alignedaddr,ptr,masklsb2
1301   //    andi    ptrlsb2,ptr,3
1302   //    sll     shiftamt,ptrlsb2,3
1303   //    ori     maskupper,$0,255               # 0xff
1304   //    sll     mask,maskupper,shiftamt
1305   //    nor     mask2,$0,mask
1306   //    andi    maskedcmpval,cmpval,255
1307   //    sll     shiftedcmpval,maskedcmpval,shiftamt
1308   //    andi    maskednewval,newval,255
1309   //    sll     shiftednewval,maskednewval,shiftamt
1310   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1311   BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1312     .addReg(Mips::ZERO).addImm(-4);
1313   BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1314     .addReg(Ptr).addReg(MaskLSB2);
1315   BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1316   BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1317   BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1318     .addReg(Mips::ZERO).addImm(MaskImm);
1319   BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1320     .addReg(ShiftAmt).addReg(MaskUpper);
1321   BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1322   BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1323     .addReg(CmpVal).addImm(MaskImm);
1324   BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1325     .addReg(ShiftAmt).addReg(MaskedCmpVal);
1326   BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1327     .addReg(NewVal).addImm(MaskImm);
1328   BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1329     .addReg(ShiftAmt).addReg(MaskedNewVal);
1330
1331   //  loop1MBB:
1332   //    ll      oldval,0(alginedaddr)
1333   //    and     maskedoldval0,oldval,mask
1334   //    bne     maskedoldval0,shiftedcmpval,sinkMBB
1335   BB = loop1MBB;
1336   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1337   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1338     .addReg(OldVal).addReg(Mask);
1339   BuildMI(BB, dl, TII->get(Mips::BNE))
1340     .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1341
1342   //  loop2MBB:
1343   //    and     maskedoldval1,oldval,mask2
1344   //    or      storeval,maskedoldval1,shiftednewval
1345   //    sc      success,storeval,0(alignedaddr)
1346   //    beq     success,$0,loop1MBB
1347   BB = loop2MBB;
1348   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1349     .addReg(OldVal).addReg(Mask2);
1350   BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1351     .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1352   BuildMI(BB, dl, TII->get(SC), Success)
1353       .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1354   BuildMI(BB, dl, TII->get(Mips::BEQ))
1355       .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1356
1357   //  sinkMBB:
1358   //    srl     srlres,maskedoldval0,shiftamt
1359   //    sll     sllres,srlres,24
1360   //    sra     dest,sllres,24
1361   BB = sinkMBB;
1362   int64_t ShiftImm = (Size == 1) ? 24 : 16;
1363
1364   BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1365       .addReg(ShiftAmt).addReg(MaskedOldVal0);
1366   BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1367       .addReg(SrlRes).addImm(ShiftImm);
1368   BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1369       .addReg(SllRes).addImm(ShiftImm);
1370
1371   MI->eraseFromParent();   // The instruction is gone now.
1372
1373   return exitMBB;
1374 }
1375
1376 //===----------------------------------------------------------------------===//
1377 //  Misc Lower Operation implementation
1378 //===----------------------------------------------------------------------===//
1379 SDValue MipsTargetLowering::
1380 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1381 {
1382   MachineFunction &MF = DAG.getMachineFunction();
1383   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1384   unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1385
1386   assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1387          cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1388          "Cannot lower if the alignment of the allocated space is larger than \
1389           that of the stack.");
1390
1391   SDValue Chain = Op.getOperand(0);
1392   SDValue Size = Op.getOperand(1);
1393   DebugLoc dl = Op.getDebugLoc();
1394
1395   // Get a reference from Mips stack pointer
1396   SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1397
1398   // Subtract the dynamic size from the actual stack size to
1399   // obtain the new stack size.
1400   SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1401
1402   // The Sub result contains the new stack start address, so it
1403   // must be placed in the stack pointer register.
1404   Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1405
1406   // This node always has two return values: a new stack pointer
1407   // value and a chain
1408   SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1409   SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1410   SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1411
1412   return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1413 }
1414
1415 SDValue MipsTargetLowering::
1416 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1417 {
1418   // The first operand is the chain, the second is the condition, the third is
1419   // the block to branch to if the condition is true.
1420   SDValue Chain = Op.getOperand(0);
1421   SDValue Dest = Op.getOperand(2);
1422   DebugLoc dl = Op.getDebugLoc();
1423
1424   SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1425
1426   // Return if flag is not set by a floating point comparison.
1427   if (CondRes.getOpcode() != MipsISD::FPCmp)
1428     return Op;
1429
1430   SDValue CCNode  = CondRes.getOperand(2);
1431   Mips::CondCode CC =
1432     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1433   SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1434
1435   return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1436                      Dest, CondRes);
1437 }
1438
1439 SDValue MipsTargetLowering::
1440 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1441 {
1442   SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1443
1444   // Return if flag is not set by a floating point comparison.
1445   if (Cond.getOpcode() != MipsISD::FPCmp)
1446     return Op;
1447
1448   return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1449                       Op.getDebugLoc());
1450 }
1451
1452 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1453                                                SelectionDAG &DAG) const {
1454   // FIXME there isn't actually debug info here
1455   DebugLoc dl = Op.getDebugLoc();
1456   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();   
1457
1458   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1459     SDVTList VTs = DAG.getVTList(MVT::i32);
1460
1461     MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1462
1463     // %gp_rel relocation
1464     if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1465       SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1466                                               MipsII::MO_GPREL);
1467       SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1468       SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1469       return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1470     }
1471     // %hi/%lo relocation
1472     SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1473                                               MipsII::MO_ABS_HI);
1474     SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1475                                               MipsII::MO_ABS_LO);
1476     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1477     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1478     return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1479   }
1480
1481   EVT ValTy = Op.getValueType();
1482   bool HasGotOfst = (GV->hasInternalLinkage() ||
1483                      (GV->hasLocalLinkage() && !isa<Function>(GV)));
1484   unsigned GotFlag = IsN64 ?
1485                      (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1486                      MipsII::MO_GOT;
1487   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1488   GA = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, GA);
1489   SDValue ResNode = DAG.getLoad(ValTy, dl,
1490                                 DAG.getEntryNode(), GA, MachinePointerInfo(),
1491                                 false, false, false, 0);
1492   // On functions and global targets not internal linked only
1493   // a load from got/GP is necessary for PIC to work.
1494   if (!HasGotOfst)
1495     return ResNode;
1496   SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1497                                             IsN64 ? MipsII::MO_GOT_OFST :
1498                                                     MipsII::MO_ABS_LO);
1499   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1500   return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1501 }
1502
1503 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1504                                               SelectionDAG &DAG) const {
1505   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1506   // FIXME there isn't actually debug info here
1507   DebugLoc dl = Op.getDebugLoc();
1508
1509   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1510     // %hi/%lo relocation
1511     SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1512                                        MipsII::MO_ABS_HI);
1513     SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1514                                        MipsII::MO_ABS_LO);
1515     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1516     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1517     return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1518   }
1519
1520   SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1521                                             MipsII::MO_GOT);
1522   BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, BAGOTOffset);
1523   SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1524                                            MipsII::MO_ABS_LO);
1525   SDValue Load = DAG.getLoad(MVT::i32, dl,
1526                              DAG.getEntryNode(), BAGOTOffset,
1527                              MachinePointerInfo(), false, false, false, 0);
1528   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
1529   return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1530 }
1531
1532 SDValue MipsTargetLowering::
1533 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1534 {
1535   // If the relocation model is PIC, use the General Dynamic TLS Model,
1536   // otherwise use the Initial Exec or Local Exec TLS Model.
1537   // TODO: implement Local Dynamic TLS model
1538
1539   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1540   DebugLoc dl = GA->getDebugLoc();
1541   const GlobalValue *GV = GA->getGlobal();
1542   EVT PtrVT = getPointerTy();
1543
1544   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1545     // General Dynamic TLS Model
1546     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
1547                                              0, MipsII::MO_TLSGD);
1548     SDValue Tlsgd = DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
1549     SDValue GP = DAG.getRegister(Mips::GP, MVT::i32);
1550     SDValue Argument = DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
1551
1552     ArgListTy Args;
1553     ArgListEntry Entry;
1554     Entry.Node = Argument;
1555     Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
1556     Args.push_back(Entry);
1557     std::pair<SDValue, SDValue> CallResult =
1558         LowerCallTo(DAG.getEntryNode(),
1559                     (Type *) Type::getInt32Ty(*DAG.getContext()),
1560                     false, false, false, false, 0, CallingConv::C, false, true,
1561                     DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG,
1562                     dl);
1563
1564     return CallResult.first;
1565   }
1566
1567   SDValue Offset;
1568   if (GV->isDeclaration()) {
1569     // Initial Exec TLS Model
1570     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1571                                              MipsII::MO_GOTTPREL);
1572     Offset = DAG.getLoad(MVT::i32, dl,
1573                          DAG.getEntryNode(), TGA, MachinePointerInfo(),
1574                          false, false, false, 0);
1575   } else {
1576     // Local Exec TLS Model
1577     SDVTList VTs = DAG.getVTList(MVT::i32);
1578     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1579                                                MipsII::MO_TPREL_HI);
1580     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1581                                                MipsII::MO_TPREL_LO);
1582     SDValue Hi = DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
1583     SDValue Lo = DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
1584     Offset = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1585   }
1586
1587   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1588   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1589 }
1590
1591 SDValue MipsTargetLowering::
1592 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1593 {
1594   SDValue ResNode;
1595   SDValue HiPart;
1596   // FIXME there isn't actually debug info here
1597   DebugLoc dl = Op.getDebugLoc();
1598   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1599   unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
1600
1601   EVT PtrVT = Op.getValueType();
1602   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
1603
1604   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
1605
1606   if (!IsPIC) {
1607     SDValue Ops[] = { JTI };
1608     HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
1609   } else {// Emit Load from Global Pointer
1610     JTI = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, JTI);
1611     HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
1612                          MachinePointerInfo(),
1613                          false, false, false, 0);
1614   }
1615
1616   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1617                                          MipsII::MO_ABS_LO);
1618   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
1619   ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1620
1621   return ResNode;
1622 }
1623
1624 SDValue MipsTargetLowering::
1625 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1626 {
1627   SDValue ResNode;
1628   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1629   const Constant *C = N->getConstVal();
1630   // FIXME there isn't actually debug info here
1631   DebugLoc dl = Op.getDebugLoc();
1632
1633   // gp_rel relocation
1634   // FIXME: we should reference the constant pool using small data sections,
1635   // but the asm printer currently doesn't support this feature without
1636   // hacking it. This feature should come soon so we can uncomment the
1637   // stuff below.
1638   //if (IsInSmallSection(C->getType())) {
1639   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1640   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1641   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1642
1643   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1644     SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1645                                              N->getOffset(), MipsII::MO_ABS_HI);
1646     SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1647                                              N->getOffset(), MipsII::MO_ABS_LO);
1648     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1649     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1650     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1651   } else {
1652     SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1653                                            N->getOffset(), MipsII::MO_GOT);
1654     CP = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, CP);
1655     SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
1656                                CP, MachinePointerInfo::getConstantPool(),
1657                                false, false, false, 0);
1658     SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1659                                              N->getOffset(), MipsII::MO_ABS_LO);
1660     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1661     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1662   }
1663
1664   return ResNode;
1665 }
1666
1667 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1668   MachineFunction &MF = DAG.getMachineFunction();
1669   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1670
1671   DebugLoc dl = Op.getDebugLoc();
1672   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1673                                  getPointerTy());
1674
1675   // vastart just stores the address of the VarArgsFrameIndex slot into the
1676   // memory location argument.
1677   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1678   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1679                       MachinePointerInfo(SV),
1680                       false, false, 0);
1681 }
1682
1683 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG) {
1684   // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1685   DebugLoc dl = Op.getDebugLoc();
1686   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(0));
1687   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(1));
1688   SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op0,
1689                              DAG.getConstant(0x7fffffff, MVT::i32));
1690   SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op1,
1691                              DAG.getConstant(0x80000000, MVT::i32));
1692   SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1693   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Result);
1694 }
1695
1696 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1697   // FIXME:
1698   //  Use ext/ins instructions if target architecture is Mips32r2.
1699   //  Eliminate redundant mfc1 and mtc1 instructions.
1700   unsigned LoIdx = 0, HiIdx = 1;
1701
1702   if (!isLittle)
1703     std::swap(LoIdx, HiIdx);
1704
1705   DebugLoc dl = Op.getDebugLoc();
1706   SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1707                               Op.getOperand(0),
1708                               DAG.getConstant(LoIdx, MVT::i32));
1709   SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1710                             Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1711   SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1712                             Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1713   SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1714                              DAG.getConstant(0x7fffffff, MVT::i32));
1715   SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1716                              DAG.getConstant(0x80000000, MVT::i32));
1717   SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1718
1719   if (!isLittle)
1720     std::swap(Word0, Word1);
1721
1722   return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1723 }
1724
1725 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1726   const {
1727   EVT Ty = Op.getValueType();
1728
1729   assert(Ty == MVT::f32 || Ty == MVT::f64);
1730
1731   if (Ty == MVT::f32)
1732     return LowerFCOPYSIGN32(Op, DAG);
1733   else
1734     return LowerFCOPYSIGN64(Op, DAG, Subtarget->isLittle());
1735 }
1736
1737 SDValue MipsTargetLowering::
1738 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1739   // check the depth
1740   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1741          "Frame address can only be determined for current frame.");
1742
1743   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1744   MFI->setFrameAddressIsTaken(true);
1745   EVT VT = Op.getValueType();
1746   DebugLoc dl = Op.getDebugLoc();
1747   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1748                                          IsN64 ? Mips::FP_64 : Mips::FP, VT);
1749   return FrameAddr;
1750 }
1751
1752 // TODO: set SType according to the desired memory barrier behavior.
1753 SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
1754                                             SelectionDAG& DAG) const {
1755   unsigned SType = 0;
1756   DebugLoc dl = Op.getDebugLoc();
1757   return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1758                      DAG.getConstant(SType, MVT::i32));
1759 }
1760
1761 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1762                                               SelectionDAG& DAG) const {
1763   // FIXME: Need pseudo-fence for 'singlethread' fences
1764   // FIXME: Set SType for weaker fences where supported/appropriate.
1765   unsigned SType = 0;
1766   DebugLoc dl = Op.getDebugLoc();
1767   return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1768                      DAG.getConstant(SType, MVT::i32));
1769 }
1770
1771 //===----------------------------------------------------------------------===//
1772 //                      Calling Convention Implementation
1773 //===----------------------------------------------------------------------===//
1774
1775 //===----------------------------------------------------------------------===//
1776 // TODO: Implement a generic logic using tblgen that can support this.
1777 // Mips O32 ABI rules:
1778 // ---
1779 // i32 - Passed in A0, A1, A2, A3 and stack
1780 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1781 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
1782 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1783 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1784 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
1785 //       go to stack.
1786 //
1787 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1788 //===----------------------------------------------------------------------===//
1789
1790 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1791                        MVT LocVT, CCValAssign::LocInfo LocInfo,
1792                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
1793
1794   static const unsigned IntRegsSize=4, FloatRegsSize=2;
1795
1796   static const unsigned IntRegs[] = {
1797       Mips::A0, Mips::A1, Mips::A2, Mips::A3
1798   };
1799   static const unsigned F32Regs[] = {
1800       Mips::F12, Mips::F14
1801   };
1802   static const unsigned F64Regs[] = {
1803       Mips::D6, Mips::D7
1804   };
1805
1806   // ByVal Args
1807   if (ArgFlags.isByVal()) {
1808     State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1809                       1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1810     unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1811     for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1812          r < std::min(IntRegsSize, NextReg); ++r)
1813       State.AllocateReg(IntRegs[r]);
1814     return false;
1815   }
1816
1817   // Promote i8 and i16
1818   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1819     LocVT = MVT::i32;
1820     if (ArgFlags.isSExt())
1821       LocInfo = CCValAssign::SExt;
1822     else if (ArgFlags.isZExt())
1823       LocInfo = CCValAssign::ZExt;
1824     else
1825       LocInfo = CCValAssign::AExt;
1826   }
1827
1828   unsigned Reg;
1829
1830   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1831   // is true: function is vararg, argument is 3rd or higher, there is previous
1832   // argument which is not f32 or f64.
1833   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1834       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1835   unsigned OrigAlign = ArgFlags.getOrigAlign();
1836   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1837
1838   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1839     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1840     // If this is the first part of an i64 arg,
1841     // the allocated register must be either A0 or A2.
1842     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1843       Reg = State.AllocateReg(IntRegs, IntRegsSize);
1844     LocVT = MVT::i32;
1845   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1846     // Allocate int register and shadow next int register. If first
1847     // available register is Mips::A1 or Mips::A3, shadow it too.
1848     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1849     if (Reg == Mips::A1 || Reg == Mips::A3)
1850       Reg = State.AllocateReg(IntRegs, IntRegsSize);
1851     State.AllocateReg(IntRegs, IntRegsSize);
1852     LocVT = MVT::i32;
1853   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1854     // we are guaranteed to find an available float register
1855     if (ValVT == MVT::f32) {
1856       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1857       // Shadow int register
1858       State.AllocateReg(IntRegs, IntRegsSize);
1859     } else {
1860       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1861       // Shadow int registers
1862       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1863       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1864         State.AllocateReg(IntRegs, IntRegsSize);
1865       State.AllocateReg(IntRegs, IntRegsSize);
1866     }
1867   } else
1868     llvm_unreachable("Cannot handle this ValVT.");
1869
1870   unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1871   unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1872
1873   if (!Reg)
1874     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1875   else
1876     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1877
1878   return false; // CC must always match
1879 }
1880
1881 static const unsigned Mips64IntRegs[8] =
1882   {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1883    Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1884 static const unsigned Mips64DPRegs[8] =
1885   {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1886    Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1887
1888 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1889                            CCValAssign::LocInfo LocInfo,
1890                            ISD::ArgFlagsTy ArgFlags, CCState &State) {
1891   unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1892   unsigned Size  = (ArgFlags.getByValSize() + 7) / 8 * 8;
1893   unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1894
1895   assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1896
1897   // If byval is 16-byte aligned, the first arg register must be even.  
1898   if ((Align == 16) && (FirstIdx % 2)) {
1899     State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1900     ++FirstIdx;
1901   }
1902
1903   // Mark the registers allocated.
1904   for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1905     State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1906
1907   // Allocate space on caller's stack.
1908   unsigned Offset = State.AllocateStack(Size, Align);
1909   
1910   if (FirstIdx < 8)
1911     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1912                                      LocVT, LocInfo));    
1913   else
1914     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1915
1916   return true;
1917 }
1918
1919 #include "MipsGenCallingConv.inc"
1920
1921 static void
1922 AnalyzeMips64CallOperands(CCState CCInfo,
1923                           const SmallVectorImpl<ISD::OutputArg> &Outs) {
1924   unsigned NumOps = Outs.size();
1925   for (unsigned i = 0; i != NumOps; ++i) {
1926     MVT ArgVT = Outs[i].VT;
1927     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1928     bool R;
1929
1930     if (Outs[i].IsFixed)
1931       R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1932     else
1933       R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1934       
1935     if (R) {
1936 #ifndef NDEBUG
1937       dbgs() << "Call operand #" << i << " has unhandled type "
1938              << EVT(ArgVT).getEVTString();
1939 #endif
1940       llvm_unreachable(0);
1941     }
1942   }
1943 }
1944
1945 //===----------------------------------------------------------------------===//
1946 //                  Call Calling Convention Implementation
1947 //===----------------------------------------------------------------------===//
1948
1949 static const unsigned O32IntRegsSize = 4;
1950
1951 static const unsigned O32IntRegs[] = {
1952   Mips::A0, Mips::A1, Mips::A2, Mips::A3
1953 };
1954
1955 // Return next O32 integer argument register.
1956 static unsigned getNextIntArgReg(unsigned Reg) {
1957   assert((Reg == Mips::A0) || (Reg == Mips::A2));
1958   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1959 }
1960
1961 // Write ByVal Arg to arg registers and stack.
1962 static void
1963 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1964               SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1965               SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1966               MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1967               const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1968               MVT PtrType, bool isLittle) {
1969   unsigned LocMemOffset = VA.getLocMemOffset();
1970   unsigned Offset = 0;
1971   uint32_t RemainingSize = Flags.getByValSize();
1972   unsigned ByValAlign = Flags.getByValAlign();
1973
1974   // Copy the first 4 words of byval arg to registers A0 - A3.
1975   // FIXME: Use a stricter alignment if it enables better optimization in passes
1976   //        run later.
1977   for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
1978        Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
1979     SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1980                                   DAG.getConstant(Offset, MVT::i32));
1981     SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1982                                   MachinePointerInfo(),
1983                                   false, false, false, std::min(ByValAlign,
1984                                                                 (unsigned )4));
1985     MemOpChains.push_back(LoadVal.getValue(1));
1986     unsigned DstReg = O32IntRegs[LocMemOffset / 4];
1987     RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1988   }
1989
1990   if (RemainingSize == 0)
1991     return;
1992
1993   // If there still is a register available for argument passing, write the
1994   // remaining part of the structure to it using subword loads and shifts.
1995   if (LocMemOffset < 4 * 4) {
1996     assert(RemainingSize <= 3 && RemainingSize >= 1 &&
1997            "There must be one to three bytes remaining.");
1998     unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
1999     SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2000                                   DAG.getConstant(Offset, MVT::i32));
2001     unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2002     SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2003                                      LoadPtr, MachinePointerInfo(),
2004                                      MVT::getIntegerVT(LoadSize * 8), false,
2005                                      false, Alignment);
2006     MemOpChains.push_back(LoadVal.getValue(1));
2007
2008     // If target is big endian, shift it to the most significant half-word or
2009     // byte.
2010     if (!isLittle)
2011       LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2012                             DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2013
2014     Offset += LoadSize;
2015     RemainingSize -= LoadSize;
2016
2017     // Read second subword if necessary.
2018     if (RemainingSize != 0)  {
2019       assert(RemainingSize == 1 && "There must be one byte remaining.");
2020       LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg, 
2021                             DAG.getConstant(Offset, MVT::i32));
2022       unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2023       SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2024                                        LoadPtr, MachinePointerInfo(),
2025                                        MVT::i8, false, false, Alignment);
2026       MemOpChains.push_back(Subword.getValue(1));
2027       // Insert the loaded byte to LoadVal.
2028       // FIXME: Use INS if supported by target.
2029       unsigned ShiftAmt = isLittle ? 16 : 8;
2030       SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2031                                   DAG.getConstant(ShiftAmt, MVT::i32));
2032       LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2033     }
2034
2035     unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2036     RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2037     return;
2038   }
2039
2040   // Create a fixed object on stack at offset LocMemOffset and copy
2041   // remaining part of byval arg to it using memcpy.
2042   SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2043                             DAG.getConstant(Offset, MVT::i32));
2044   LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2045   SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2046   ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2047                              DAG.getConstant(RemainingSize, MVT::i32),
2048                              std::min(ByValAlign, (unsigned)4),
2049                              /*isVolatile=*/false, /*AlwaysInline=*/false,
2050                              MachinePointerInfo(0), MachinePointerInfo(0));
2051 }
2052
2053 // Copy Mips64 byVal arg to registers and stack.
2054 void static
2055 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2056                SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2057                SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2058                MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2059                const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2060                EVT PtrTy, bool isLittle) {
2061   unsigned ByValSize = Flags.getByValSize();
2062   unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2063   bool IsRegLoc = VA.isRegLoc();
2064   unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2065   unsigned LocMemOffset = 0;
2066   unsigned MemCpySize = ByValSize;
2067
2068   if (!IsRegLoc)
2069     LocMemOffset = VA.getLocMemOffset();
2070   else {
2071     const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2072                                     VA.getLocReg());
2073     const unsigned *RegEnd = Mips64IntRegs + 8;
2074
2075     // Copy double words to registers.
2076     for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2077       SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2078                                     DAG.getConstant(Offset, PtrTy));
2079       SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2080                                     MachinePointerInfo(), false, false, false,
2081                                     Alignment);
2082       MemOpChains.push_back(LoadVal.getValue(1));
2083       RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2084     }
2085
2086     // Return if the struct has been fully copied. 
2087     if (!(MemCpySize = ByValSize - Offset))
2088       return;
2089
2090     // If there is an argument register available, copy the remainder of the
2091     // byval argument with sub-doubleword loads and shifts.
2092     if (Reg != RegEnd) {
2093       assert((ByValSize < Offset + 8) &&
2094              "Size of the remainder should be smaller than 8-byte.");
2095       SDValue Val;
2096       for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2097         unsigned RemSize = ByValSize - Offset;
2098
2099         if (RemSize < LoadSize)
2100           continue;
2101         
2102         SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2103                                       DAG.getConstant(Offset, PtrTy));
2104         SDValue LoadVal = 
2105           DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2106                          MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2107                          false, false, Alignment);
2108         MemOpChains.push_back(LoadVal.getValue(1));
2109
2110         // Offset in number of bits from double word boundary.
2111         unsigned OffsetDW = (Offset % 8) * 8;
2112         unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2113         SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2114                                     DAG.getConstant(Shamt, MVT::i32));
2115         
2116         Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2117                               Shift;
2118         Offset += LoadSize;
2119         Alignment = std::min(Alignment, LoadSize);
2120       }
2121       
2122       RegsToPass.push_back(std::make_pair(*Reg, Val));
2123       return;
2124     }
2125   }
2126
2127   assert(MemCpySize && "MemCpySize must not be zero.");
2128
2129   // Create a fixed object on stack at offset LocMemOffset and copy
2130   // remainder of byval arg to it with memcpy.
2131   SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2132                             DAG.getConstant(Offset, PtrTy));
2133   LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2134   SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2135   ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2136                              DAG.getConstant(MemCpySize, PtrTy), Alignment,
2137                              /*isVolatile=*/false, /*AlwaysInline=*/false,
2138                              MachinePointerInfo(0), MachinePointerInfo(0));
2139 }
2140
2141 /// LowerCall - functions arguments are copied from virtual regs to
2142 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2143 /// TODO: isTailCall.
2144 SDValue
2145 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2146                               CallingConv::ID CallConv, bool isVarArg,
2147                               bool &isTailCall,
2148                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2149                               const SmallVectorImpl<SDValue> &OutVals,
2150                               const SmallVectorImpl<ISD::InputArg> &Ins,
2151                               DebugLoc dl, SelectionDAG &DAG,
2152                               SmallVectorImpl<SDValue> &InVals) const {
2153   // MIPs target does not yet support tail call optimization.
2154   isTailCall = false;
2155
2156   MachineFunction &MF = DAG.getMachineFunction();
2157   MachineFrameInfo *MFI = MF.getFrameInfo();
2158   const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2159   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2160   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2161
2162   // Analyze operands of the call, assigning locations to each operand.
2163   SmallVector<CCValAssign, 16> ArgLocs;
2164   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2165                  getTargetMachine(), ArgLocs, *DAG.getContext());
2166
2167   if (IsO32)
2168     CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2169   else if (HasMips64)
2170     AnalyzeMips64CallOperands(CCInfo, Outs);
2171   else
2172     CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2173
2174   // Get a count of how many bytes are to be pushed on the stack.
2175   unsigned NextStackOffset = CCInfo.getNextStackOffset();
2176
2177   // Chain is the output chain of the last Load/Store or CopyToReg node.
2178   // ByValChain is the output chain of the last Memcpy node created for copying
2179   // byval arguments to the stack.
2180   SDValue Chain, CallSeqStart, ByValChain;
2181   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2182   Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2183   ByValChain = InChain;
2184
2185   // If this is the first call, create a stack frame object that points to
2186   // a location to which .cprestore saves $gp.
2187   if (IsO32 && IsPIC && !MipsFI->getGPFI())
2188     MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2189
2190   // Get the frame index of the stack frame object that points to the location
2191   // of dynamically allocated area on the stack.
2192   int DynAllocFI = MipsFI->getDynAllocFI();
2193
2194   // Update size of the maximum argument space.
2195   // For O32, a minimum of four words (16 bytes) of argument space is
2196   // allocated.
2197   if (IsO32)
2198     NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2199
2200   unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2201
2202   if (MaxCallFrameSize < NextStackOffset) {
2203     MipsFI->setMaxCallFrameSize(NextStackOffset);
2204
2205     // Set the offsets relative to $sp of the $gp restore slot and dynamically
2206     // allocated stack space. These offsets must be aligned to a boundary
2207     // determined by the stack alignment of the ABI.
2208     unsigned StackAlignment = TFL->getStackAlignment();
2209     NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2210                       StackAlignment * StackAlignment;
2211
2212     if (MipsFI->needGPSaveRestore())
2213       MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2214
2215     MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2216   }
2217
2218   // With EABI is it possible to have 16 args on registers.
2219   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2220   SmallVector<SDValue, 8> MemOpChains;
2221
2222   int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2223
2224   // Walk the register/memloc assignments, inserting copies/loads.
2225   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2226     SDValue Arg = OutVals[i];
2227     CCValAssign &VA = ArgLocs[i];
2228     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2229     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2230
2231     // ByVal Arg.
2232     if (Flags.isByVal()) {
2233       assert(Flags.getByValSize() &&
2234              "ByVal args of size 0 should have been ignored by front-end.");
2235       if (IsO32)
2236         WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2237                       MFI, DAG, Arg, VA, Flags, getPointerTy(),
2238                       Subtarget->isLittle());
2239       else
2240         PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2241                        MFI, DAG, Arg, VA, Flags, getPointerTy(), 
2242                        Subtarget->isLittle());
2243       continue;
2244     }
2245     
2246     // Promote the value if needed.
2247     switch (VA.getLocInfo()) {
2248     default: llvm_unreachable("Unknown loc info!");
2249     case CCValAssign::Full:
2250       if (VA.isRegLoc()) {
2251         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2252             (ValVT == MVT::f64 && LocVT == MVT::i64))
2253           Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2254         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2255           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2256                                    Arg, DAG.getConstant(0, MVT::i32));
2257           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2258                                    Arg, DAG.getConstant(1, MVT::i32));
2259           if (!Subtarget->isLittle())
2260             std::swap(Lo, Hi);
2261           unsigned LocRegLo = VA.getLocReg(); 
2262           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2263           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2264           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2265           continue;
2266         }
2267       }
2268       break;
2269     case CCValAssign::SExt:
2270       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2271       break;
2272     case CCValAssign::ZExt:
2273       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2274       break;
2275     case CCValAssign::AExt:
2276       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2277       break;
2278     }
2279
2280     // Arguments that can be passed on register must be kept at
2281     // RegsToPass vector
2282     if (VA.isRegLoc()) {
2283       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2284       continue;
2285     }
2286
2287     // Register can't get to this point...
2288     assert(VA.isMemLoc());
2289
2290     // Create the frame index object for this incoming parameter
2291     LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2292                                     VA.getLocMemOffset(), true);
2293     SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2294
2295     // emit ISD::STORE whichs stores the
2296     // parameter value to a stack Location
2297     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2298                                        MachinePointerInfo(),
2299                                        false, false, 0));
2300   }
2301
2302   // Extend range of indices of frame objects for outgoing arguments that were
2303   // created during this function call. Skip this step if no such objects were
2304   // created.
2305   if (LastFI)
2306     MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2307
2308   // If a memcpy has been created to copy a byval arg to a stack, replace the
2309   // chain input of CallSeqStart with ByValChain.
2310   if (InChain != ByValChain)
2311     DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2312                            NextStackOffsetVal);
2313
2314   // Transform all store nodes into one single node because all store
2315   // nodes are independent of each other.
2316   if (!MemOpChains.empty())
2317     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2318                         &MemOpChains[0], MemOpChains.size());
2319
2320   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2321   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2322   // node so that legalize doesn't hack it.
2323   unsigned char OpFlag;
2324   bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2325   bool LoadSymAddr = false;
2326   SDValue CalleeLo;
2327
2328   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2329     if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2330       OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2331       unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2332       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2333                                           OpFlag);
2334       CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2335                                             0, LoFlag);
2336     } else {
2337       OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2338       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2339                                           getPointerTy(), 0, OpFlag);
2340     }
2341
2342     LoadSymAddr = true;
2343   }
2344   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2345     if (IsN64 || (!IsO32 && IsPIC))
2346       OpFlag = MipsII::MO_GOT_DISP;
2347     else if (!IsPIC) // !N64 && static
2348       OpFlag = MipsII::MO_NO_FLAG;
2349     else // O32 & PIC
2350       OpFlag = MipsII::MO_GOT_CALL;
2351     Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
2352                                          getPointerTy(), OpFlag);
2353     LoadSymAddr = true;
2354   }
2355
2356   SDValue InFlag;
2357
2358   // Create nodes that load address of callee and copy it to T9
2359   if (IsPICCall) {
2360     if (LoadSymAddr) {
2361       // Load callee address
2362       Callee = DAG.getNode(MipsISD::WrapperPIC, dl, getPointerTy(), Callee);
2363       SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2364                                       Callee, MachinePointerInfo::getGOT(),
2365                                       false, false, false, 0);
2366
2367       // Use GOT+LO if callee has internal linkage.
2368       if (CalleeLo.getNode()) {
2369         SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2370         Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2371       } else
2372         Callee = LoadValue;
2373     }
2374
2375     // copy to T9
2376     unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2377     Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2378     InFlag = Chain.getValue(1);
2379     Callee = DAG.getRegister(T9Reg, getPointerTy());
2380   }
2381
2382   // Build a sequence of copy-to-reg nodes chained together with token
2383   // chain and flag operands which copy the outgoing args into registers.
2384   // The InFlag in necessary since all emitted instructions must be
2385   // stuck together.
2386   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2387     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2388                              RegsToPass[i].second, InFlag);
2389     InFlag = Chain.getValue(1);
2390   }
2391
2392   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2393   //             = Chain, Callee, Reg#1, Reg#2, ...
2394   //
2395   // Returns a chain & a flag for retval copy to use.
2396   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2397   SmallVector<SDValue, 8> Ops;
2398   Ops.push_back(Chain);
2399   Ops.push_back(Callee);
2400
2401   // Add argument registers to the end of the list so that they are
2402   // known live into the call.
2403   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2404     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2405                                   RegsToPass[i].second.getValueType()));
2406
2407   if (InFlag.getNode())
2408     Ops.push_back(InFlag);
2409
2410   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2411   InFlag = Chain.getValue(1);
2412
2413   // Create the CALLSEQ_END node.
2414   Chain = DAG.getCALLSEQ_END(Chain,
2415                              DAG.getIntPtrConstant(NextStackOffset, true),
2416                              DAG.getIntPtrConstant(0, true), InFlag);
2417   InFlag = Chain.getValue(1);
2418
2419   // Handle result values, copying them out of physregs into vregs that we
2420   // return.
2421   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2422                          Ins, dl, DAG, InVals);
2423 }
2424
2425 /// LowerCallResult - Lower the result values of a call into the
2426 /// appropriate copies out of appropriate physical registers.
2427 SDValue
2428 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2429                                     CallingConv::ID CallConv, bool isVarArg,
2430                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2431                                     DebugLoc dl, SelectionDAG &DAG,
2432                                     SmallVectorImpl<SDValue> &InVals) const {
2433   // Assign locations to each value returned by this call.
2434   SmallVector<CCValAssign, 16> RVLocs;
2435   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2436                  getTargetMachine(), RVLocs, *DAG.getContext());
2437
2438   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2439
2440   // Copy all of the result registers out of their specified physreg.
2441   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2442     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2443                                RVLocs[i].getValVT(), InFlag).getValue(1);
2444     InFlag = Chain.getValue(2);
2445     InVals.push_back(Chain.getValue(0));
2446   }
2447
2448   return Chain;
2449 }
2450
2451 //===----------------------------------------------------------------------===//
2452 //             Formal Arguments Calling Convention Implementation
2453 //===----------------------------------------------------------------------===//
2454 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2455                          std::vector<SDValue>& OutChains,
2456                          SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2457                          const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2458   unsigned LocMem = VA.getLocMemOffset();
2459   unsigned FirstWord = LocMem / 4;
2460
2461   // copy register A0 - A3 to frame object
2462   for (unsigned i = 0; i < NumWords; ++i) {
2463     unsigned CurWord = FirstWord + i;
2464     if (CurWord >= O32IntRegsSize)
2465       break;
2466
2467     unsigned SrcReg = O32IntRegs[CurWord];
2468     unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2469     SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2470                                    DAG.getConstant(i * 4, MVT::i32));
2471     SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2472                                  StorePtr, MachinePointerInfo(), false,
2473                                  false, 0);
2474     OutChains.push_back(Store);
2475   }
2476 }
2477
2478 // Create frame object on stack and copy registers used for byval passing to it.
2479 static unsigned
2480 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2481                     std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2482                     const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2483                     MachineFrameInfo *MFI, bool IsRegLoc,
2484                     SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2485                     EVT PtrTy) {
2486   const unsigned *Reg = Mips64IntRegs + 8;
2487   int FOOffset; // Frame object offset from virtual frame pointer.
2488
2489   if (IsRegLoc) {
2490     Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2491     FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2492   }
2493   else
2494     FOOffset = VA.getLocMemOffset();
2495
2496   // Create frame object.
2497   unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2498   unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2499   SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2500   InVals.push_back(FIN);
2501
2502   // Copy arg registers.
2503   for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2504        ++Reg, ++I) {
2505     unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2506     SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2507                                    DAG.getConstant(I * 8, PtrTy));
2508     SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2509                                  StorePtr, MachinePointerInfo(), false,
2510                                  false, 0);
2511     OutChains.push_back(Store);
2512   }
2513   
2514   return LastFI;
2515 }
2516
2517 /// LowerFormalArguments - transform physical registers into virtual registers
2518 /// and generate load operations for arguments places on the stack.
2519 SDValue
2520 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2521                                          CallingConv::ID CallConv,
2522                                          bool isVarArg,
2523                                          const SmallVectorImpl<ISD::InputArg>
2524                                          &Ins,
2525                                          DebugLoc dl, SelectionDAG &DAG,
2526                                          SmallVectorImpl<SDValue> &InVals)
2527                                           const {
2528   MachineFunction &MF = DAG.getMachineFunction();
2529   MachineFrameInfo *MFI = MF.getFrameInfo();
2530   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2531
2532   MipsFI->setVarArgsFrameIndex(0);
2533
2534   // Used with vargs to acumulate store chains.
2535   std::vector<SDValue> OutChains;
2536
2537   // Assign locations to all of the incoming arguments.
2538   SmallVector<CCValAssign, 16> ArgLocs;
2539   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2540                  getTargetMachine(), ArgLocs, *DAG.getContext());
2541
2542   if (IsO32)
2543     CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2544   else
2545     CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2546
2547   int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2548
2549   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2550     CCValAssign &VA = ArgLocs[i];
2551     EVT ValVT = VA.getValVT();
2552     ISD::ArgFlagsTy Flags = Ins[i].Flags;
2553     bool IsRegLoc = VA.isRegLoc();
2554
2555     if (Flags.isByVal()) {
2556       assert(Flags.getByValSize() &&
2557              "ByVal args of size 0 should have been ignored by front-end.");
2558       if (IsO32) {
2559         unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2560         LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2561                                         true);
2562         SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2563         InVals.push_back(FIN);
2564         ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2565       } else // N32/64
2566         LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2567                                      MFI, IsRegLoc, InVals, MipsFI,
2568                                      getPointerTy());
2569       continue;
2570     }
2571
2572     // Arguments stored on registers
2573     if (IsRegLoc) {
2574       EVT RegVT = VA.getLocVT();
2575       unsigned ArgReg = VA.getLocReg();
2576       TargetRegisterClass *RC = 0;
2577
2578       if (RegVT == MVT::i32)
2579         RC = Mips::CPURegsRegisterClass;
2580       else if (RegVT == MVT::i64)
2581         RC = Mips::CPU64RegsRegisterClass;
2582       else if (RegVT == MVT::f32)
2583         RC = Mips::FGR32RegisterClass;
2584       else if (RegVT == MVT::f64)
2585         RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2586       else
2587         llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2588
2589       // Transform the arguments stored on
2590       // physical registers into virtual ones
2591       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2592       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2593
2594       // If this is an 8 or 16-bit value, it has been passed promoted
2595       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2596       // truncate to the right size.
2597       if (VA.getLocInfo() != CCValAssign::Full) {
2598         unsigned Opcode = 0;
2599         if (VA.getLocInfo() == CCValAssign::SExt)
2600           Opcode = ISD::AssertSext;
2601         else if (VA.getLocInfo() == CCValAssign::ZExt)
2602           Opcode = ISD::AssertZext;
2603         if (Opcode)
2604           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2605                                  DAG.getValueType(ValVT));
2606         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2607       }
2608
2609       // Handle floating point arguments passed in integer registers.
2610       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2611           (RegVT == MVT::i64 && ValVT == MVT::f64))
2612         ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2613       else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2614         unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2615                                   getNextIntArgReg(ArgReg), RC);
2616         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2617         if (!Subtarget->isLittle())
2618           std::swap(ArgValue, ArgValue2);
2619         ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2620                                ArgValue, ArgValue2);
2621       }
2622
2623       InVals.push_back(ArgValue);
2624     } else { // VA.isRegLoc()
2625
2626       // sanity check
2627       assert(VA.isMemLoc());
2628
2629       // The stack pointer offset is relative to the caller stack frame.
2630       LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2631                                       VA.getLocMemOffset(), true);
2632
2633       // Create load nodes to retrieve arguments from the stack
2634       SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2635       InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2636                                    MachinePointerInfo::getFixedStack(LastFI),
2637                                    false, false, false, 0));
2638     }
2639   }
2640
2641   // The mips ABIs for returning structs by value requires that we copy
2642   // the sret argument into $v0 for the return. Save the argument into
2643   // a virtual register so that we can access it from the return points.
2644   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2645     unsigned Reg = MipsFI->getSRetReturnReg();
2646     if (!Reg) {
2647       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2648       MipsFI->setSRetReturnReg(Reg);
2649     }
2650     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2651     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2652   }
2653
2654   if (isVarArg) {
2655     unsigned NumOfRegs = IsO32 ? 4 : 8;
2656     const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2657     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2658     int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2659     TargetRegisterClass *RC
2660       = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2661     unsigned RegSize = RC->getSize();
2662     int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2663
2664     // Offset of the first variable argument from stack pointer.
2665     int FirstVaArgOffset;
2666
2667     if (IsO32 || (Idx == NumOfRegs)) {
2668       FirstVaArgOffset =
2669         (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2670     } else
2671       FirstVaArgOffset = RegSlotOffset;
2672
2673     // Record the frame index of the first variable argument
2674     // which is a value necessary to VASTART.
2675     LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2676     MipsFI->setVarArgsFrameIndex(LastFI);
2677
2678     // Copy the integer registers that have not been used for argument passing
2679     // to the argument register save area. For O32, the save area is allocated
2680     // in the caller's stack frame, while for N32/64, it is allocated in the
2681     // callee's stack frame.
2682     for (int StackOffset = RegSlotOffset;
2683          Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2684       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2685       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2686                                             MVT::getIntegerVT(RegSize * 8));
2687       LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2688       SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2689       OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2690                                        MachinePointerInfo(),
2691                                        false, false, 0));
2692     }
2693   }
2694
2695   MipsFI->setLastInArgFI(LastFI);
2696
2697   // All stores are grouped in one node to allow the matching between
2698   // the size of Ins and InVals. This only happens when on varg functions
2699   if (!OutChains.empty()) {
2700     OutChains.push_back(Chain);
2701     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2702                         &OutChains[0], OutChains.size());
2703   }
2704
2705   return Chain;
2706 }
2707
2708 //===----------------------------------------------------------------------===//
2709 //               Return Value Calling Convention Implementation
2710 //===----------------------------------------------------------------------===//
2711
2712 SDValue
2713 MipsTargetLowering::LowerReturn(SDValue Chain,
2714                                 CallingConv::ID CallConv, bool isVarArg,
2715                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
2716                                 const SmallVectorImpl<SDValue> &OutVals,
2717                                 DebugLoc dl, SelectionDAG &DAG) const {
2718
2719   // CCValAssign - represent the assignment of
2720   // the return value to a location
2721   SmallVector<CCValAssign, 16> RVLocs;
2722
2723   // CCState - Info about the registers and stack slot.
2724   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2725                  getTargetMachine(), RVLocs, *DAG.getContext());
2726
2727   // Analize return values.
2728   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2729
2730   // If this is the first return lowered for this function, add
2731   // the regs to the liveout set for the function.
2732   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2733     for (unsigned i = 0; i != RVLocs.size(); ++i)
2734       if (RVLocs[i].isRegLoc())
2735         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2736   }
2737
2738   SDValue Flag;
2739
2740   // Copy the result values into the output registers.
2741   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2742     CCValAssign &VA = RVLocs[i];
2743     assert(VA.isRegLoc() && "Can only return in registers!");
2744
2745     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2746                              OutVals[i], Flag);
2747
2748     // guarantee that all emitted copies are
2749     // stuck together, avoiding something bad
2750     Flag = Chain.getValue(1);
2751   }
2752
2753   // The mips ABIs for returning structs by value requires that we copy
2754   // the sret argument into $v0 for the return. We saved the argument into
2755   // a virtual register in the entry block, so now we copy the value out
2756   // and into $v0.
2757   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2758     MachineFunction &MF      = DAG.getMachineFunction();
2759     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2760     unsigned Reg = MipsFI->getSRetReturnReg();
2761
2762     if (!Reg)
2763       llvm_unreachable("sret virtual register not created in the entry block");
2764     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2765
2766     Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2767     Flag = Chain.getValue(1);
2768   }
2769
2770   // Return on Mips is always a "jr $ra"
2771   if (Flag.getNode())
2772     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2773                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2774   else // Return Void
2775     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2776                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
2777 }
2778
2779 //===----------------------------------------------------------------------===//
2780 //                           Mips Inline Assembly Support
2781 //===----------------------------------------------------------------------===//
2782
2783 /// getConstraintType - Given a constraint letter, return the type of
2784 /// constraint it is for this target.
2785 MipsTargetLowering::ConstraintType MipsTargetLowering::
2786 getConstraintType(const std::string &Constraint) const
2787 {
2788   // Mips specific constrainy
2789   // GCC config/mips/constraints.md
2790   //
2791   // 'd' : An address register. Equivalent to r
2792   //       unless generating MIPS16 code.
2793   // 'y' : Equivalent to r; retained for
2794   //       backwards compatibility.
2795   // 'f' : Floating Point registers.
2796   if (Constraint.size() == 1) {
2797     switch (Constraint[0]) {
2798       default : break;
2799       case 'd':
2800       case 'y':
2801       case 'f':
2802         return C_RegisterClass;
2803         break;
2804     }
2805   }
2806   return TargetLowering::getConstraintType(Constraint);
2807 }
2808
2809 /// Examine constraint type and operand type and determine a weight value.
2810 /// This object must already have been set up with the operand type
2811 /// and the current alternative constraint selected.
2812 TargetLowering::ConstraintWeight
2813 MipsTargetLowering::getSingleConstraintMatchWeight(
2814     AsmOperandInfo &info, const char *constraint) const {
2815   ConstraintWeight weight = CW_Invalid;
2816   Value *CallOperandVal = info.CallOperandVal;
2817     // If we don't have a value, we can't do a match,
2818     // but allow it at the lowest weight.
2819   if (CallOperandVal == NULL)
2820     return CW_Default;
2821   Type *type = CallOperandVal->getType();
2822   // Look at the constraint type.
2823   switch (*constraint) {
2824   default:
2825     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2826     break;
2827   case 'd':
2828   case 'y':
2829     if (type->isIntegerTy())
2830       weight = CW_Register;
2831     break;
2832   case 'f':
2833     if (type->isFloatTy())
2834       weight = CW_Register;
2835     break;
2836   }
2837   return weight;
2838 }
2839
2840 /// Given a register class constraint, like 'r', if this corresponds directly
2841 /// to an LLVM register class, return a register of 0 and the register class
2842 /// pointer.
2843 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2844 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2845 {
2846   if (Constraint.size() == 1) {
2847     switch (Constraint[0]) {
2848     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2849     case 'y': // Same as 'r'. Exists for compatibility.
2850     case 'r':
2851       return std::make_pair(0U, Mips::CPURegsRegisterClass);
2852     case 'f':
2853       if (VT == MVT::f32)
2854         return std::make_pair(0U, Mips::FGR32RegisterClass);
2855       if (VT == MVT::f64)
2856         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2857           return std::make_pair(0U, Mips::AFGR64RegisterClass);
2858       break;
2859     }
2860   }
2861   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2862 }
2863
2864 bool
2865 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2866   // The Mips target isn't yet aware of offsets.
2867   return false;
2868 }
2869
2870 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2871   if (VT != MVT::f32 && VT != MVT::f64)
2872     return false;
2873   if (Imm.isNegZero())
2874     return false;
2875   return Imm.isZero();
2876 }