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