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