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