Add support for floating point base register + offset register addressing mode
[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, false, true,
1590                   TlsGetAddr, Args, DAG, dl);
1591
1592     SDValue Ret = CallResult.first;
1593
1594     if (!LocalDynamic)
1595       return Ret;
1596
1597     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1598                                                MipsII::MO_DTPREL_HI);
1599     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1600     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1601                                                MipsII::MO_DTPREL_LO);
1602     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1603     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1604     return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1605   }
1606
1607   SDValue Offset;
1608   if (GV->isDeclaration()) {
1609     // Initial Exec TLS Model
1610     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1611                                              MipsII::MO_GOTTPREL);
1612     TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1613                       TGA);
1614     Offset = DAG.getLoad(PtrVT, dl,
1615                          DAG.getEntryNode(), TGA, MachinePointerInfo(),
1616                          false, false, false, 0);
1617   } else {
1618     // Local Exec TLS Model
1619     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1620                                                MipsII::MO_TPREL_HI);
1621     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1622                                                MipsII::MO_TPREL_LO);
1623     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1624     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1625     Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1626   }
1627
1628   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1629   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1630 }
1631
1632 SDValue MipsTargetLowering::
1633 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1634 {
1635   SDValue HiPart, JTI, JTILo;
1636   // FIXME there isn't actually debug info here
1637   DebugLoc dl = Op.getDebugLoc();
1638   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1639   EVT PtrVT = Op.getValueType();
1640   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1641
1642   if (!IsPIC && !IsN64) {
1643     JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1644     HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1645     JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1646   } else {// Emit Load from Global Pointer
1647     unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1648     unsigned OfstFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1649     JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1650     JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1651                       JTI);
1652     HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1653                          MachinePointerInfo(), false, false, false, 0);
1654     JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1655   }
1656
1657   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1658   return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1659 }
1660
1661 SDValue MipsTargetLowering::
1662 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1663 {
1664   SDValue ResNode;
1665   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1666   const Constant *C = N->getConstVal();
1667   // FIXME there isn't actually debug info here
1668   DebugLoc dl = Op.getDebugLoc();
1669
1670   // gp_rel relocation
1671   // FIXME: we should reference the constant pool using small data sections,
1672   // but the asm printer currently doesn't support this feature without
1673   // hacking it. This feature should come soon so we can uncomment the
1674   // stuff below.
1675   //if (IsInSmallSection(C->getType())) {
1676   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1677   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1678   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1679
1680   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1681     SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1682                                              N->getOffset(), MipsII::MO_ABS_HI);
1683     SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1684                                              N->getOffset(), MipsII::MO_ABS_LO);
1685     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1686     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1687     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1688   } else {
1689     EVT ValTy = Op.getValueType();
1690     unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1691     unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1692     SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1693                                            N->getOffset(), GOTFlag);
1694     CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1695     SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1696                                MachinePointerInfo::getConstantPool(), false,
1697                                false, false, 0);
1698     SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1699                                              N->getOffset(), OFSTFlag);
1700     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1701     ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1702   }
1703
1704   return ResNode;
1705 }
1706
1707 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1708   MachineFunction &MF = DAG.getMachineFunction();
1709   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1710
1711   DebugLoc dl = Op.getDebugLoc();
1712   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1713                                  getPointerTy());
1714
1715   // vastart just stores the address of the VarArgsFrameIndex slot into the
1716   // memory location argument.
1717   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1718   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1719                       MachinePointerInfo(SV), false, false, 0);
1720 }
1721  
1722 // Called if the size of integer registers is large enough to hold the whole
1723 // floating point number.
1724 static SDValue LowerFCOPYSIGNLargeIntReg(SDValue Op, SelectionDAG &DAG) {
1725   // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1726   EVT ValTy = Op.getValueType();
1727   EVT IntValTy = MVT::getIntegerVT(ValTy.getSizeInBits());
1728   uint64_t Mask = (uint64_t)1 << (ValTy.getSizeInBits() - 1);
1729   DebugLoc dl = Op.getDebugLoc();
1730   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(0));
1731   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(1));
1732   SDValue And0 = DAG.getNode(ISD::AND, dl, IntValTy, Op0,
1733                              DAG.getConstant(Mask - 1, IntValTy));
1734   SDValue And1 = DAG.getNode(ISD::AND, dl, IntValTy, Op1,
1735                              DAG.getConstant(Mask, IntValTy));
1736   SDValue Result = DAG.getNode(ISD::OR, dl, IntValTy, And0, And1);
1737   return DAG.getNode(ISD::BITCAST, dl, ValTy, Result);
1738 }
1739
1740 // Called if the size of integer registers is not large enough to hold the whole
1741 // floating point number (e.g. f64 & 32-bit integer register).
1742 static SDValue
1743 LowerFCOPYSIGNSmallIntReg(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1744   // FIXME:
1745   //  Use ext/ins instructions if target architecture is Mips32r2.
1746   //  Eliminate redundant mfc1 and mtc1 instructions.
1747   unsigned LoIdx = 0, HiIdx = 1;
1748
1749   if (!isLittle)
1750     std::swap(LoIdx, HiIdx);
1751
1752   DebugLoc dl = Op.getDebugLoc();
1753   SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1754                               Op.getOperand(0),
1755                               DAG.getConstant(LoIdx, MVT::i32));
1756   SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1757                             Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1758   SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1759                             Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1760   SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1761                              DAG.getConstant(0x7fffffff, MVT::i32));
1762   SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1763                              DAG.getConstant(0x80000000, MVT::i32));
1764   SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1765
1766   if (!isLittle)
1767     std::swap(Word0, Word1);
1768
1769   return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1770 }
1771
1772 SDValue
1773 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1774   EVT Ty = Op.getValueType();
1775
1776   assert(Ty == MVT::f32 || Ty == MVT::f64);
1777
1778   if (Ty == MVT::f32 || HasMips64)
1779     return LowerFCOPYSIGNLargeIntReg(Op, DAG);
1780   
1781   return LowerFCOPYSIGNSmallIntReg(Op, DAG, Subtarget->isLittle());
1782 }
1783
1784 SDValue MipsTargetLowering::
1785 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1786   // check the depth
1787   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1788          "Frame address can only be determined for current frame.");
1789
1790   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1791   MFI->setFrameAddressIsTaken(true);
1792   EVT VT = Op.getValueType();
1793   DebugLoc dl = Op.getDebugLoc();
1794   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1795                                          IsN64 ? Mips::FP_64 : Mips::FP, VT);
1796   return FrameAddr;
1797 }
1798
1799 // TODO: set SType according to the desired memory barrier behavior.
1800 SDValue
1801 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
1802   unsigned SType = 0;
1803   DebugLoc dl = Op.getDebugLoc();
1804   return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1805                      DAG.getConstant(SType, MVT::i32));
1806 }
1807
1808 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1809                                               SelectionDAG& DAG) const {
1810   // FIXME: Need pseudo-fence for 'singlethread' fences
1811   // FIXME: Set SType for weaker fences where supported/appropriate.
1812   unsigned SType = 0;
1813   DebugLoc dl = Op.getDebugLoc();
1814   return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1815                      DAG.getConstant(SType, MVT::i32));
1816 }
1817
1818 //===----------------------------------------------------------------------===//
1819 //                      Calling Convention Implementation
1820 //===----------------------------------------------------------------------===//
1821
1822 //===----------------------------------------------------------------------===//
1823 // TODO: Implement a generic logic using tblgen that can support this.
1824 // Mips O32 ABI rules:
1825 // ---
1826 // i32 - Passed in A0, A1, A2, A3 and stack
1827 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1828 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
1829 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1830 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1831 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
1832 //       go to stack.
1833 //
1834 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1835 //===----------------------------------------------------------------------===//
1836
1837 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1838                        MVT LocVT, CCValAssign::LocInfo LocInfo,
1839                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
1840
1841   static const unsigned IntRegsSize=4, FloatRegsSize=2;
1842
1843   static const unsigned IntRegs[] = {
1844       Mips::A0, Mips::A1, Mips::A2, Mips::A3
1845   };
1846   static const unsigned F32Regs[] = {
1847       Mips::F12, Mips::F14
1848   };
1849   static const unsigned F64Regs[] = {
1850       Mips::D6, Mips::D7
1851   };
1852
1853   // ByVal Args
1854   if (ArgFlags.isByVal()) {
1855     State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1856                       1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1857     unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1858     for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1859          r < std::min(IntRegsSize, NextReg); ++r)
1860       State.AllocateReg(IntRegs[r]);
1861     return false;
1862   }
1863
1864   // Promote i8 and i16
1865   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1866     LocVT = MVT::i32;
1867     if (ArgFlags.isSExt())
1868       LocInfo = CCValAssign::SExt;
1869     else if (ArgFlags.isZExt())
1870       LocInfo = CCValAssign::ZExt;
1871     else
1872       LocInfo = CCValAssign::AExt;
1873   }
1874
1875   unsigned Reg;
1876
1877   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1878   // is true: function is vararg, argument is 3rd or higher, there is previous
1879   // argument which is not f32 or f64.
1880   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1881       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1882   unsigned OrigAlign = ArgFlags.getOrigAlign();
1883   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1884
1885   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1886     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1887     // If this is the first part of an i64 arg,
1888     // the allocated register must be either A0 or A2.
1889     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1890       Reg = State.AllocateReg(IntRegs, IntRegsSize);
1891     LocVT = MVT::i32;
1892   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1893     // Allocate int register and shadow next int register. If first
1894     // available register is Mips::A1 or Mips::A3, shadow it too.
1895     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1896     if (Reg == Mips::A1 || Reg == Mips::A3)
1897       Reg = State.AllocateReg(IntRegs, IntRegsSize);
1898     State.AllocateReg(IntRegs, IntRegsSize);
1899     LocVT = MVT::i32;
1900   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1901     // we are guaranteed to find an available float register
1902     if (ValVT == MVT::f32) {
1903       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1904       // Shadow int register
1905       State.AllocateReg(IntRegs, IntRegsSize);
1906     } else {
1907       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1908       // Shadow int registers
1909       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1910       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1911         State.AllocateReg(IntRegs, IntRegsSize);
1912       State.AllocateReg(IntRegs, IntRegsSize);
1913     }
1914   } else
1915     llvm_unreachable("Cannot handle this ValVT.");
1916
1917   unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1918   unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1919
1920   if (!Reg)
1921     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1922   else
1923     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1924
1925   return false; // CC must always match
1926 }
1927
1928 static const unsigned Mips64IntRegs[8] =
1929   {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1930    Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1931 static const unsigned Mips64DPRegs[8] =
1932   {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1933    Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1934
1935 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1936                            CCValAssign::LocInfo LocInfo,
1937                            ISD::ArgFlagsTy ArgFlags, CCState &State) {
1938   unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1939   unsigned Size  = (ArgFlags.getByValSize() + 7) / 8 * 8;
1940   unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1941
1942   assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1943
1944   // If byval is 16-byte aligned, the first arg register must be even.  
1945   if ((Align == 16) && (FirstIdx % 2)) {
1946     State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1947     ++FirstIdx;
1948   }
1949
1950   // Mark the registers allocated.
1951   for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1952     State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1953
1954   // Allocate space on caller's stack.
1955   unsigned Offset = State.AllocateStack(Size, Align);
1956   
1957   if (FirstIdx < 8)
1958     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1959                                      LocVT, LocInfo));    
1960   else
1961     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1962
1963   return true;
1964 }
1965
1966 #include "MipsGenCallingConv.inc"
1967
1968 static void
1969 AnalyzeMips64CallOperands(CCState &CCInfo,
1970                           const SmallVectorImpl<ISD::OutputArg> &Outs) {
1971   unsigned NumOps = Outs.size();
1972   for (unsigned i = 0; i != NumOps; ++i) {
1973     MVT ArgVT = Outs[i].VT;
1974     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1975     bool R;
1976
1977     if (Outs[i].IsFixed)
1978       R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1979     else
1980       R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1981       
1982     if (R) {
1983 #ifndef NDEBUG
1984       dbgs() << "Call operand #" << i << " has unhandled type "
1985              << EVT(ArgVT).getEVTString();
1986 #endif
1987       llvm_unreachable(0);
1988     }
1989   }
1990 }
1991
1992 //===----------------------------------------------------------------------===//
1993 //                  Call Calling Convention Implementation
1994 //===----------------------------------------------------------------------===//
1995
1996 static const unsigned O32IntRegsSize = 4;
1997
1998 static const unsigned O32IntRegs[] = {
1999   Mips::A0, Mips::A1, Mips::A2, Mips::A3
2000 };
2001
2002 // Return next O32 integer argument register.
2003 static unsigned getNextIntArgReg(unsigned Reg) {
2004   assert((Reg == Mips::A0) || (Reg == Mips::A2));
2005   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2006 }
2007
2008 // Write ByVal Arg to arg registers and stack.
2009 static void
2010 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2011               SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2012               SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2013               MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2014               const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2015               MVT PtrType, bool isLittle) {
2016   unsigned LocMemOffset = VA.getLocMemOffset();
2017   unsigned Offset = 0;
2018   uint32_t RemainingSize = Flags.getByValSize();
2019   unsigned ByValAlign = Flags.getByValAlign();
2020
2021   // Copy the first 4 words of byval arg to registers A0 - A3.
2022   // FIXME: Use a stricter alignment if it enables better optimization in passes
2023   //        run later.
2024   for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2025        Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2026     SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2027                                   DAG.getConstant(Offset, MVT::i32));
2028     SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2029                                   MachinePointerInfo(), false, false, false,
2030                                   std::min(ByValAlign, (unsigned )4));
2031     MemOpChains.push_back(LoadVal.getValue(1));
2032     unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2033     RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2034   }
2035
2036   if (RemainingSize == 0)
2037     return;
2038
2039   // If there still is a register available for argument passing, write the
2040   // remaining part of the structure to it using subword loads and shifts.
2041   if (LocMemOffset < 4 * 4) {
2042     assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2043            "There must be one to three bytes remaining.");
2044     unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2045     SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2046                                   DAG.getConstant(Offset, MVT::i32));
2047     unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2048     SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2049                                      LoadPtr, MachinePointerInfo(),
2050                                      MVT::getIntegerVT(LoadSize * 8), false,
2051                                      false, Alignment);
2052     MemOpChains.push_back(LoadVal.getValue(1));
2053
2054     // If target is big endian, shift it to the most significant half-word or
2055     // byte.
2056     if (!isLittle)
2057       LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2058                             DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2059
2060     Offset += LoadSize;
2061     RemainingSize -= LoadSize;
2062
2063     // Read second subword if necessary.
2064     if (RemainingSize != 0)  {
2065       assert(RemainingSize == 1 && "There must be one byte remaining.");
2066       LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg, 
2067                             DAG.getConstant(Offset, MVT::i32));
2068       unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2069       SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2070                                        LoadPtr, MachinePointerInfo(),
2071                                        MVT::i8, false, false, Alignment);
2072       MemOpChains.push_back(Subword.getValue(1));
2073       // Insert the loaded byte to LoadVal.
2074       // FIXME: Use INS if supported by target.
2075       unsigned ShiftAmt = isLittle ? 16 : 8;
2076       SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2077                                   DAG.getConstant(ShiftAmt, MVT::i32));
2078       LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2079     }
2080
2081     unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2082     RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2083     return;
2084   }
2085
2086   // Create a fixed object on stack at offset LocMemOffset and copy
2087   // remaining part of byval arg to it using memcpy.
2088   SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2089                             DAG.getConstant(Offset, MVT::i32));
2090   LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2091   SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2092   ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2093                              DAG.getConstant(RemainingSize, MVT::i32),
2094                              std::min(ByValAlign, (unsigned)4),
2095                              /*isVolatile=*/false, /*AlwaysInline=*/false,
2096                              MachinePointerInfo(0), MachinePointerInfo(0));
2097 }
2098
2099 // Copy Mips64 byVal arg to registers and stack.
2100 void static
2101 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2102                SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2103                SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2104                MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2105                const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2106                EVT PtrTy, bool isLittle) {
2107   unsigned ByValSize = Flags.getByValSize();
2108   unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2109   bool IsRegLoc = VA.isRegLoc();
2110   unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2111   unsigned LocMemOffset = 0;
2112   unsigned MemCpySize = ByValSize;
2113
2114   if (!IsRegLoc)
2115     LocMemOffset = VA.getLocMemOffset();
2116   else {
2117     const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2118                                     VA.getLocReg());
2119     const unsigned *RegEnd = Mips64IntRegs + 8;
2120
2121     // Copy double words to registers.
2122     for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2123       SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2124                                     DAG.getConstant(Offset, PtrTy));
2125       SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2126                                     MachinePointerInfo(), false, false, false,
2127                                     Alignment);
2128       MemOpChains.push_back(LoadVal.getValue(1));
2129       RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2130     }
2131
2132     // Return if the struct has been fully copied. 
2133     if (!(MemCpySize = ByValSize - Offset))
2134       return;
2135
2136     // If there is an argument register available, copy the remainder of the
2137     // byval argument with sub-doubleword loads and shifts.
2138     if (Reg != RegEnd) {
2139       assert((ByValSize < Offset + 8) &&
2140              "Size of the remainder should be smaller than 8-byte.");
2141       SDValue Val;
2142       for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2143         unsigned RemSize = ByValSize - Offset;
2144
2145         if (RemSize < LoadSize)
2146           continue;
2147         
2148         SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2149                                       DAG.getConstant(Offset, PtrTy));
2150         SDValue LoadVal = 
2151           DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2152                          MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2153                          false, false, Alignment);
2154         MemOpChains.push_back(LoadVal.getValue(1));
2155
2156         // Offset in number of bits from double word boundary.
2157         unsigned OffsetDW = (Offset % 8) * 8;
2158         unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2159         SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2160                                     DAG.getConstant(Shamt, MVT::i32));
2161         
2162         Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2163                               Shift;
2164         Offset += LoadSize;
2165         Alignment = std::min(Alignment, LoadSize);
2166       }
2167       
2168       RegsToPass.push_back(std::make_pair(*Reg, Val));
2169       return;
2170     }
2171   }
2172
2173   assert(MemCpySize && "MemCpySize must not be zero.");
2174
2175   // Create a fixed object on stack at offset LocMemOffset and copy
2176   // remainder of byval arg to it with memcpy.
2177   SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2178                             DAG.getConstant(Offset, PtrTy));
2179   LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2180   SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2181   ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2182                              DAG.getConstant(MemCpySize, PtrTy), Alignment,
2183                              /*isVolatile=*/false, /*AlwaysInline=*/false,
2184                              MachinePointerInfo(0), MachinePointerInfo(0));
2185 }
2186
2187 /// LowerCall - functions arguments are copied from virtual regs to
2188 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2189 /// TODO: isTailCall.
2190 SDValue
2191 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2192                               CallingConv::ID CallConv, bool isVarArg,
2193                               bool &isTailCall,
2194                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2195                               const SmallVectorImpl<SDValue> &OutVals,
2196                               const SmallVectorImpl<ISD::InputArg> &Ins,
2197                               DebugLoc dl, SelectionDAG &DAG,
2198                               SmallVectorImpl<SDValue> &InVals) const {
2199   // MIPs target does not yet support tail call optimization.
2200   isTailCall = false;
2201
2202   MachineFunction &MF = DAG.getMachineFunction();
2203   MachineFrameInfo *MFI = MF.getFrameInfo();
2204   const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2205   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2206   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2207
2208   // Analyze operands of the call, assigning locations to each operand.
2209   SmallVector<CCValAssign, 16> ArgLocs;
2210   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2211                  getTargetMachine(), ArgLocs, *DAG.getContext());
2212
2213   if (IsO32)
2214     CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2215   else if (HasMips64)
2216     AnalyzeMips64CallOperands(CCInfo, Outs);
2217   else
2218     CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2219
2220   // Get a count of how many bytes are to be pushed on the stack.
2221   unsigned NextStackOffset = CCInfo.getNextStackOffset();
2222
2223   // Chain is the output chain of the last Load/Store or CopyToReg node.
2224   // ByValChain is the output chain of the last Memcpy node created for copying
2225   // byval arguments to the stack.
2226   SDValue Chain, CallSeqStart, ByValChain;
2227   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2228   Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2229   ByValChain = InChain;
2230
2231   // If this is the first call, create a stack frame object that points to
2232   // a location to which .cprestore saves $gp.
2233   if (IsO32 && IsPIC && MipsFI->globalBaseRegFixed() && !MipsFI->getGPFI())
2234     MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2235
2236   // Get the frame index of the stack frame object that points to the location
2237   // of dynamically allocated area on the stack.
2238   int DynAllocFI = MipsFI->getDynAllocFI();
2239
2240   // Update size of the maximum argument space.
2241   // For O32, a minimum of four words (16 bytes) of argument space is
2242   // allocated.
2243   if (IsO32)
2244     NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2245
2246   unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2247
2248   if (MaxCallFrameSize < NextStackOffset) {
2249     MipsFI->setMaxCallFrameSize(NextStackOffset);
2250
2251     // Set the offsets relative to $sp of the $gp restore slot and dynamically
2252     // allocated stack space. These offsets must be aligned to a boundary
2253     // determined by the stack alignment of the ABI.
2254     unsigned StackAlignment = TFL->getStackAlignment();
2255     NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2256                       StackAlignment * StackAlignment;
2257
2258     if (MipsFI->needGPSaveRestore())
2259       MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2260
2261     MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2262   }
2263
2264   // With EABI is it possible to have 16 args on registers.
2265   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2266   SmallVector<SDValue, 8> MemOpChains;
2267
2268   int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2269
2270   // Walk the register/memloc assignments, inserting copies/loads.
2271   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2272     SDValue Arg = OutVals[i];
2273     CCValAssign &VA = ArgLocs[i];
2274     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2275     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2276
2277     // ByVal Arg.
2278     if (Flags.isByVal()) {
2279       assert(Flags.getByValSize() &&
2280              "ByVal args of size 0 should have been ignored by front-end.");
2281       if (IsO32)
2282         WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2283                       MFI, DAG, Arg, VA, Flags, getPointerTy(),
2284                       Subtarget->isLittle());
2285       else
2286         PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2287                        MFI, DAG, Arg, VA, Flags, getPointerTy(), 
2288                        Subtarget->isLittle());
2289       continue;
2290     }
2291     
2292     // Promote the value if needed.
2293     switch (VA.getLocInfo()) {
2294     default: llvm_unreachable("Unknown loc info!");
2295     case CCValAssign::Full:
2296       if (VA.isRegLoc()) {
2297         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2298             (ValVT == MVT::f64 && LocVT == MVT::i64))
2299           Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2300         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2301           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2302                                    Arg, DAG.getConstant(0, MVT::i32));
2303           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2304                                    Arg, DAG.getConstant(1, MVT::i32));
2305           if (!Subtarget->isLittle())
2306             std::swap(Lo, Hi);
2307           unsigned LocRegLo = VA.getLocReg(); 
2308           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2309           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2310           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2311           continue;
2312         }
2313       }
2314       break;
2315     case CCValAssign::SExt:
2316       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2317       break;
2318     case CCValAssign::ZExt:
2319       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2320       break;
2321     case CCValAssign::AExt:
2322       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2323       break;
2324     }
2325
2326     // Arguments that can be passed on register must be kept at
2327     // RegsToPass vector
2328     if (VA.isRegLoc()) {
2329       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2330       continue;
2331     }
2332
2333     // Register can't get to this point...
2334     assert(VA.isMemLoc());
2335
2336     // Create the frame index object for this incoming parameter
2337     LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2338                                     VA.getLocMemOffset(), true);
2339     SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2340
2341     // emit ISD::STORE whichs stores the
2342     // parameter value to a stack Location
2343     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2344                                        MachinePointerInfo(), false, false, 0));
2345   }
2346
2347   // Extend range of indices of frame objects for outgoing arguments that were
2348   // created during this function call. Skip this step if no such objects were
2349   // created.
2350   if (LastFI)
2351     MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2352
2353   // If a memcpy has been created to copy a byval arg to a stack, replace the
2354   // chain input of CallSeqStart with ByValChain.
2355   if (InChain != ByValChain)
2356     DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2357                            NextStackOffsetVal);
2358
2359   // Transform all store nodes into one single node because all store
2360   // nodes are independent of each other.
2361   if (!MemOpChains.empty())
2362     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2363                         &MemOpChains[0], MemOpChains.size());
2364
2365   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2366   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2367   // node so that legalize doesn't hack it.
2368   unsigned char OpFlag;
2369   bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2370   bool GlobalOrExternal = false;
2371   SDValue CalleeLo;
2372
2373   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2374     if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2375       OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2376       unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2377       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2378                                           OpFlag);
2379       CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2380                                             0, LoFlag);
2381     } else {
2382       OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2383       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2384                                           getPointerTy(), 0, OpFlag);
2385     }
2386
2387     GlobalOrExternal = true;
2388   }
2389   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2390     if (IsN64 || (!IsO32 && IsPIC))
2391       OpFlag = MipsII::MO_GOT_DISP;
2392     else if (!IsPIC) // !N64 && static
2393       OpFlag = MipsII::MO_NO_FLAG;
2394     else // O32 & PIC
2395       OpFlag = MipsII::MO_GOT_CALL;
2396     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2397                                          OpFlag);
2398     GlobalOrExternal = true;
2399   }
2400
2401   SDValue InFlag;
2402
2403   // Create nodes that load address of callee and copy it to T9
2404   if (IsPICCall) {
2405     if (GlobalOrExternal) {
2406       // Load callee address
2407       Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2408                            GetGlobalReg(DAG, getPointerTy()), Callee);
2409       SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2410                                       Callee, MachinePointerInfo::getGOT(),
2411                                       false, false, false, 0);
2412
2413       // Use GOT+LO if callee has internal linkage.
2414       if (CalleeLo.getNode()) {
2415         SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2416         Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2417       } else
2418         Callee = LoadValue;
2419     }
2420   }
2421
2422   // T9 should contain the address of the callee function if 
2423   // -reloction-model=pic or it is an indirect call.
2424   if (IsPICCall || !GlobalOrExternal) {
2425     // copy to T9
2426     unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2427     Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2428     InFlag = Chain.getValue(1);
2429     Callee = DAG.getRegister(T9Reg, getPointerTy());
2430   }
2431
2432   // Build a sequence of copy-to-reg nodes chained together with token
2433   // chain and flag operands which copy the outgoing args into registers.
2434   // The InFlag in necessary since all emitted instructions must be
2435   // stuck together.
2436   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2437     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2438                              RegsToPass[i].second, InFlag);
2439     InFlag = Chain.getValue(1);
2440   }
2441
2442   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2443   //             = Chain, Callee, Reg#1, Reg#2, ...
2444   //
2445   // Returns a chain & a flag for retval copy to use.
2446   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2447   SmallVector<SDValue, 8> Ops;
2448   Ops.push_back(Chain);
2449   Ops.push_back(Callee);
2450
2451   // Add argument registers to the end of the list so that they are
2452   // known live into the call.
2453   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2454     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2455                                   RegsToPass[i].second.getValueType()));
2456
2457   if (InFlag.getNode())
2458     Ops.push_back(InFlag);
2459
2460   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2461   InFlag = Chain.getValue(1);
2462
2463   // Create the CALLSEQ_END node.
2464   Chain = DAG.getCALLSEQ_END(Chain,
2465                              DAG.getIntPtrConstant(NextStackOffset, true),
2466                              DAG.getIntPtrConstant(0, true), InFlag);
2467   InFlag = Chain.getValue(1);
2468
2469   // Handle result values, copying them out of physregs into vregs that we
2470   // return.
2471   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2472                          Ins, dl, DAG, InVals);
2473 }
2474
2475 /// LowerCallResult - Lower the result values of a call into the
2476 /// appropriate copies out of appropriate physical registers.
2477 SDValue
2478 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2479                                     CallingConv::ID CallConv, bool isVarArg,
2480                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2481                                     DebugLoc dl, SelectionDAG &DAG,
2482                                     SmallVectorImpl<SDValue> &InVals) const {
2483   // Assign locations to each value returned by this call.
2484   SmallVector<CCValAssign, 16> RVLocs;
2485   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2486                  getTargetMachine(), RVLocs, *DAG.getContext());
2487
2488   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2489
2490   // Copy all of the result registers out of their specified physreg.
2491   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2492     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2493                                RVLocs[i].getValVT(), InFlag).getValue(1);
2494     InFlag = Chain.getValue(2);
2495     InVals.push_back(Chain.getValue(0));
2496   }
2497
2498   return Chain;
2499 }
2500
2501 //===----------------------------------------------------------------------===//
2502 //             Formal Arguments Calling Convention Implementation
2503 //===----------------------------------------------------------------------===//
2504 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2505                          std::vector<SDValue>& OutChains,
2506                          SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2507                          const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2508   unsigned LocMem = VA.getLocMemOffset();
2509   unsigned FirstWord = LocMem / 4;
2510
2511   // copy register A0 - A3 to frame object
2512   for (unsigned i = 0; i < NumWords; ++i) {
2513     unsigned CurWord = FirstWord + i;
2514     if (CurWord >= O32IntRegsSize)
2515       break;
2516
2517     unsigned SrcReg = O32IntRegs[CurWord];
2518     unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2519     SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2520                                    DAG.getConstant(i * 4, MVT::i32));
2521     SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2522                                  StorePtr, MachinePointerInfo(), false,
2523                                  false, 0);
2524     OutChains.push_back(Store);
2525   }
2526 }
2527
2528 // Create frame object on stack and copy registers used for byval passing to it.
2529 static unsigned
2530 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2531                     std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2532                     const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2533                     MachineFrameInfo *MFI, bool IsRegLoc,
2534                     SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2535                     EVT PtrTy) {
2536   const unsigned *Reg = Mips64IntRegs + 8;
2537   int FOOffset; // Frame object offset from virtual frame pointer.
2538
2539   if (IsRegLoc) {
2540     Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2541     FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2542   }
2543   else
2544     FOOffset = VA.getLocMemOffset();
2545
2546   // Create frame object.
2547   unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2548   unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2549   SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2550   InVals.push_back(FIN);
2551
2552   // Copy arg registers.
2553   for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2554        ++Reg, ++I) {
2555     unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2556     SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2557                                    DAG.getConstant(I * 8, PtrTy));
2558     SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2559                                  StorePtr, MachinePointerInfo(), false,
2560                                  false, 0);
2561     OutChains.push_back(Store);
2562   }
2563   
2564   return LastFI;
2565 }
2566
2567 /// LowerFormalArguments - transform physical registers into virtual registers
2568 /// and generate load operations for arguments places on the stack.
2569 SDValue
2570 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2571                                          CallingConv::ID CallConv,
2572                                          bool isVarArg,
2573                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2574                                          DebugLoc dl, SelectionDAG &DAG,
2575                                          SmallVectorImpl<SDValue> &InVals)
2576                                           const {
2577   MachineFunction &MF = DAG.getMachineFunction();
2578   MachineFrameInfo *MFI = MF.getFrameInfo();
2579   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2580
2581   MipsFI->setVarArgsFrameIndex(0);
2582
2583   // Used with vargs to acumulate store chains.
2584   std::vector<SDValue> OutChains;
2585
2586   // Assign locations to all of the incoming arguments.
2587   SmallVector<CCValAssign, 16> ArgLocs;
2588   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2589                  getTargetMachine(), ArgLocs, *DAG.getContext());
2590
2591   if (IsO32)
2592     CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2593   else
2594     CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2595
2596   int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2597
2598   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2599     CCValAssign &VA = ArgLocs[i];
2600     EVT ValVT = VA.getValVT();
2601     ISD::ArgFlagsTy Flags = Ins[i].Flags;
2602     bool IsRegLoc = VA.isRegLoc();
2603
2604     if (Flags.isByVal()) {
2605       assert(Flags.getByValSize() &&
2606              "ByVal args of size 0 should have been ignored by front-end.");
2607       if (IsO32) {
2608         unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2609         LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2610                                         true);
2611         SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2612         InVals.push_back(FIN);
2613         ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2614       } else // N32/64
2615         LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2616                                      MFI, IsRegLoc, InVals, MipsFI,
2617                                      getPointerTy());
2618       continue;
2619     }
2620
2621     // Arguments stored on registers
2622     if (IsRegLoc) {
2623       EVT RegVT = VA.getLocVT();
2624       unsigned ArgReg = VA.getLocReg();
2625       const TargetRegisterClass *RC;
2626
2627       if (RegVT == MVT::i32)
2628         RC = Mips::CPURegsRegisterClass;
2629       else if (RegVT == MVT::i64)
2630         RC = Mips::CPU64RegsRegisterClass;
2631       else if (RegVT == MVT::f32)
2632         RC = Mips::FGR32RegisterClass;
2633       else if (RegVT == MVT::f64)
2634         RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2635       else
2636         llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2637
2638       // Transform the arguments stored on
2639       // physical registers into virtual ones
2640       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2641       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2642
2643       // If this is an 8 or 16-bit value, it has been passed promoted
2644       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2645       // truncate to the right size.
2646       if (VA.getLocInfo() != CCValAssign::Full) {
2647         unsigned Opcode = 0;
2648         if (VA.getLocInfo() == CCValAssign::SExt)
2649           Opcode = ISD::AssertSext;
2650         else if (VA.getLocInfo() == CCValAssign::ZExt)
2651           Opcode = ISD::AssertZext;
2652         if (Opcode)
2653           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2654                                  DAG.getValueType(ValVT));
2655         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2656       }
2657
2658       // Handle floating point arguments passed in integer registers.
2659       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2660           (RegVT == MVT::i64 && ValVT == MVT::f64))
2661         ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2662       else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2663         unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2664                                   getNextIntArgReg(ArgReg), RC);
2665         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2666         if (!Subtarget->isLittle())
2667           std::swap(ArgValue, ArgValue2);
2668         ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2669                                ArgValue, ArgValue2);
2670       }
2671
2672       InVals.push_back(ArgValue);
2673     } else { // VA.isRegLoc()
2674
2675       // sanity check
2676       assert(VA.isMemLoc());
2677
2678       // The stack pointer offset is relative to the caller stack frame.
2679       LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2680                                       VA.getLocMemOffset(), true);
2681
2682       // Create load nodes to retrieve arguments from the stack
2683       SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2684       InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2685                                    MachinePointerInfo::getFixedStack(LastFI),
2686                                    false, false, false, 0));
2687     }
2688   }
2689
2690   // The mips ABIs for returning structs by value requires that we copy
2691   // the sret argument into $v0 for the return. Save the argument into
2692   // a virtual register so that we can access it from the return points.
2693   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2694     unsigned Reg = MipsFI->getSRetReturnReg();
2695     if (!Reg) {
2696       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2697       MipsFI->setSRetReturnReg(Reg);
2698     }
2699     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2700     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2701   }
2702
2703   if (isVarArg) {
2704     unsigned NumOfRegs = IsO32 ? 4 : 8;
2705     const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2706     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2707     int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2708     const TargetRegisterClass *RC
2709       = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2710     unsigned RegSize = RC->getSize();
2711     int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2712
2713     // Offset of the first variable argument from stack pointer.
2714     int FirstVaArgOffset;
2715
2716     if (IsO32 || (Idx == NumOfRegs)) {
2717       FirstVaArgOffset =
2718         (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2719     } else
2720       FirstVaArgOffset = RegSlotOffset;
2721
2722     // Record the frame index of the first variable argument
2723     // which is a value necessary to VASTART.
2724     LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2725     MipsFI->setVarArgsFrameIndex(LastFI);
2726
2727     // Copy the integer registers that have not been used for argument passing
2728     // to the argument register save area. For O32, the save area is allocated
2729     // in the caller's stack frame, while for N32/64, it is allocated in the
2730     // callee's stack frame.
2731     for (int StackOffset = RegSlotOffset;
2732          Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2733       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2734       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2735                                             MVT::getIntegerVT(RegSize * 8));
2736       LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2737       SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2738       OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2739                                        MachinePointerInfo(), false, false, 0));
2740     }
2741   }
2742
2743   MipsFI->setLastInArgFI(LastFI);
2744
2745   // All stores are grouped in one node to allow the matching between
2746   // the size of Ins and InVals. This only happens when on varg functions
2747   if (!OutChains.empty()) {
2748     OutChains.push_back(Chain);
2749     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2750                         &OutChains[0], OutChains.size());
2751   }
2752
2753   return Chain;
2754 }
2755
2756 //===----------------------------------------------------------------------===//
2757 //               Return Value Calling Convention Implementation
2758 //===----------------------------------------------------------------------===//
2759
2760 SDValue
2761 MipsTargetLowering::LowerReturn(SDValue Chain,
2762                                 CallingConv::ID CallConv, bool isVarArg,
2763                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
2764                                 const SmallVectorImpl<SDValue> &OutVals,
2765                                 DebugLoc dl, SelectionDAG &DAG) const {
2766
2767   // CCValAssign - represent the assignment of
2768   // the return value to a location
2769   SmallVector<CCValAssign, 16> RVLocs;
2770
2771   // CCState - Info about the registers and stack slot.
2772   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2773                  getTargetMachine(), RVLocs, *DAG.getContext());
2774
2775   // Analize return values.
2776   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2777
2778   // If this is the first return lowered for this function, add
2779   // the regs to the liveout set for the function.
2780   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2781     for (unsigned i = 0; i != RVLocs.size(); ++i)
2782       if (RVLocs[i].isRegLoc())
2783         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2784   }
2785
2786   SDValue Flag;
2787
2788   // Copy the result values into the output registers.
2789   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2790     CCValAssign &VA = RVLocs[i];
2791     assert(VA.isRegLoc() && "Can only return in registers!");
2792
2793     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
2794
2795     // guarantee that all emitted copies are
2796     // stuck together, avoiding something bad
2797     Flag = Chain.getValue(1);
2798   }
2799
2800   // The mips ABIs for returning structs by value requires that we copy
2801   // the sret argument into $v0 for the return. We saved the argument into
2802   // a virtual register in the entry block, so now we copy the value out
2803   // and into $v0.
2804   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2805     MachineFunction &MF      = DAG.getMachineFunction();
2806     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2807     unsigned Reg = MipsFI->getSRetReturnReg();
2808
2809     if (!Reg)
2810       llvm_unreachable("sret virtual register not created in the entry block");
2811     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2812
2813     Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2814     Flag = Chain.getValue(1);
2815   }
2816
2817   // Return on Mips is always a "jr $ra"
2818   if (Flag.getNode())
2819     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2820                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2821   else // Return Void
2822     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2823                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
2824 }
2825
2826 //===----------------------------------------------------------------------===//
2827 //                           Mips Inline Assembly Support
2828 //===----------------------------------------------------------------------===//
2829
2830 /// getConstraintType - Given a constraint letter, return the type of
2831 /// constraint it is for this target.
2832 MipsTargetLowering::ConstraintType MipsTargetLowering::
2833 getConstraintType(const std::string &Constraint) const
2834 {
2835   // Mips specific constrainy
2836   // GCC config/mips/constraints.md
2837   //
2838   // 'd' : An address register. Equivalent to r
2839   //       unless generating MIPS16 code.
2840   // 'y' : Equivalent to r; retained for
2841   //       backwards compatibility.
2842   // 'f' : Floating Point registers.
2843   if (Constraint.size() == 1) {
2844     switch (Constraint[0]) {
2845       default : break;
2846       case 'd':
2847       case 'y':
2848       case 'f':
2849         return C_RegisterClass;
2850     }
2851   }
2852   return TargetLowering::getConstraintType(Constraint);
2853 }
2854
2855 /// Examine constraint type and operand type and determine a weight value.
2856 /// This object must already have been set up with the operand type
2857 /// and the current alternative constraint selected.
2858 TargetLowering::ConstraintWeight
2859 MipsTargetLowering::getSingleConstraintMatchWeight(
2860     AsmOperandInfo &info, const char *constraint) const {
2861   ConstraintWeight weight = CW_Invalid;
2862   Value *CallOperandVal = info.CallOperandVal;
2863     // If we don't have a value, we can't do a match,
2864     // but allow it at the lowest weight.
2865   if (CallOperandVal == NULL)
2866     return CW_Default;
2867   Type *type = CallOperandVal->getType();
2868   // Look at the constraint type.
2869   switch (*constraint) {
2870   default:
2871     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2872     break;
2873   case 'd':
2874   case 'y':
2875     if (type->isIntegerTy())
2876       weight = CW_Register;
2877     break;
2878   case 'f':
2879     if (type->isFloatTy())
2880       weight = CW_Register;
2881     break;
2882   }
2883   return weight;
2884 }
2885
2886 /// Given a register class constraint, like 'r', if this corresponds directly
2887 /// to an LLVM register class, return a register of 0 and the register class
2888 /// pointer.
2889 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2890 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2891 {
2892   if (Constraint.size() == 1) {
2893     switch (Constraint[0]) {
2894     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2895     case 'y': // Same as 'r'. Exists for compatibility.
2896     case 'r':
2897       if (VT == MVT::i32)
2898         return std::make_pair(0U, Mips::CPURegsRegisterClass);
2899       assert(VT == MVT::i64 && "Unexpected type.");
2900       return std::make_pair(0U, Mips::CPU64RegsRegisterClass);
2901     case 'f':
2902       if (VT == MVT::f32)
2903         return std::make_pair(0U, Mips::FGR32RegisterClass);
2904       if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2905         if (Subtarget->isFP64bit())
2906           return std::make_pair(0U, Mips::FGR64RegisterClass);
2907         else
2908           return std::make_pair(0U, Mips::AFGR64RegisterClass);
2909       }
2910     }
2911   }
2912   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2913 }
2914
2915 bool
2916 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2917   // The Mips target isn't yet aware of offsets.
2918   return false;
2919 }
2920
2921 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2922   if (VT != MVT::f32 && VT != MVT::f64)
2923     return false;
2924   if (Imm.isNegZero())
2925     return false;
2926   return Imm.isZero();
2927 }
2928
2929 unsigned MipsTargetLowering::getJumpTableEncoding() const {
2930   if (IsN64)
2931     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
2932   
2933   return TargetLowering::getJumpTableEncoding();
2934 }