[mips] Define getTargetNode as a template function.
[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 #define DEBUG_TYPE "mips-lower"
15 #include "MipsISelLowering.h"
16 #include "InstPrinter/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsBaseInfo.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <cctype>
38
39 using namespace llvm;
40
41 STATISTIC(NumTailCalls, "Number of tail calls");
42
43 static cl::opt<bool>
44 LargeGOT("mxgot", cl::Hidden,
45          cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
46
47 static cl::opt<bool>
48 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
49                cl::desc("MIPS: Don't trap on integer division by zero."),
50                cl::init(false));
51
52 static const uint16_t O32IntRegs[4] = {
53   Mips::A0, Mips::A1, Mips::A2, Mips::A3
54 };
55
56 static const uint16_t Mips64IntRegs[8] = {
57   Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
58   Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
59 };
60
61 static const uint16_t Mips64DPRegs[8] = {
62   Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
63   Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
64 };
65
66 // If I is a shifted mask, set the size (Size) and the first bit of the
67 // mask (Pos), and return true.
68 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
69 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
70   if (!isShiftedMask_64(I))
71      return false;
72
73   Size = CountPopulation_64(I);
74   Pos = countTrailingZeros(I);
75   return true;
76 }
77
78 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
79   MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
80   return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
81 }
82
83 template<class NodeTy>
84 static SDValue getTargetNode(NodeTy *Node, EVT Ty, SelectionDAG &DAG,
85                              unsigned Flag) {
86   llvm_unreachable("Unexpected node type.");
87   return SDValue();
88 }
89
90 template<>
91 SDValue getTargetNode<GlobalAddressSDNode>(GlobalAddressSDNode *N, EVT Ty,
92                                            SelectionDAG &DAG, unsigned Flag) {
93   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
94 }
95
96 template<>
97 SDValue getTargetNode<ExternalSymbolSDNode>(ExternalSymbolSDNode *N, EVT Ty,
98                                             SelectionDAG &DAG, unsigned Flag) {
99   return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
100 }
101
102 template<>
103 SDValue getTargetNode<BlockAddressSDNode>(BlockAddressSDNode *N, EVT Ty,
104                                           SelectionDAG &DAG, unsigned Flag) {
105   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
106 }
107
108 template<>
109 SDValue getTargetNode<JumpTableSDNode>(JumpTableSDNode *N, EVT Ty,
110                                        SelectionDAG &DAG, unsigned Flag) {
111   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
112 }
113
114 template<>
115 SDValue getTargetNode<ConstantPoolSDNode>(ConstantPoolSDNode *N, EVT Ty,
116                                           SelectionDAG &DAG, unsigned Flag) {
117   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
118                                    N->getOffset(), Flag);
119 }
120
121 template<class NodeTy>
122 static SDValue getAddrNonPIC(NodeTy *N, EVT Ty, SelectionDAG &DAG) {
123   SDLoc DL(N);
124   SDValue Hi = getTargetNode(N, Ty, DAG, MipsII::MO_ABS_HI);
125   SDValue Lo = getTargetNode(N, Ty, DAG, MipsII::MO_ABS_LO);
126   return DAG.getNode(ISD::ADD, DL, Ty,
127                      DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
128                      DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
129 }
130
131 template<class NodeTy>
132 SDValue MipsTargetLowering::getAddrLocal(NodeTy *N, EVT Ty, SelectionDAG &DAG,
133                                          bool HasMips64) const {
134   SDLoc DL(N);
135   unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
136   SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
137                             getTargetNode(N, Ty, DAG, GOTFlag));
138   SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
139                              MachinePointerInfo::getGOT(), false, false, false,
140                              0);
141   unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
142   SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty,
143                            getTargetNode(N, Ty, DAG, LoFlag));
144   return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
145 }
146
147 template<class NodeTy>
148 SDValue MipsTargetLowering::getAddrGlobal(NodeTy *N, EVT Ty, SelectionDAG &DAG,
149                                           unsigned Flag) const {
150   SDLoc DL(N);
151   SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
152                             getTargetNode(N, Ty, DAG, Flag));
153   return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
154                      MachinePointerInfo::getGOT(), false, false, false, 0);
155 }
156
157 template<class NodeTy>
158 SDValue MipsTargetLowering::getAddrGlobalLargeGOT(NodeTy *N, EVT Ty,
159                                                   SelectionDAG &DAG,
160                                                   unsigned HiFlag,
161                                                   unsigned LoFlag) const {
162   SDLoc DL(N);
163   SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty,
164                            getTargetNode(N, Ty, DAG, HiFlag));
165   Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, getGlobalReg(DAG, Ty));
166   SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
167                                 getTargetNode(N, Ty, DAG, LoFlag));
168   return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
169                      MachinePointerInfo::getGOT(), false, false, false, 0);
170 }
171
172 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
173   switch (Opcode) {
174   case MipsISD::JmpLink:           return "MipsISD::JmpLink";
175   case MipsISD::TailCall:          return "MipsISD::TailCall";
176   case MipsISD::Hi:                return "MipsISD::Hi";
177   case MipsISD::Lo:                return "MipsISD::Lo";
178   case MipsISD::GPRel:             return "MipsISD::GPRel";
179   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
180   case MipsISD::Ret:               return "MipsISD::Ret";
181   case MipsISD::EH_RETURN:         return "MipsISD::EH_RETURN";
182   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
183   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
184   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
185   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
186   case MipsISD::TruncIntFP:        return "MipsISD::TruncIntFP";
187   case MipsISD::ExtractLOHI:       return "MipsISD::ExtractLOHI";
188   case MipsISD::InsertLOHI:        return "MipsISD::InsertLOHI";
189   case MipsISD::Mult:              return "MipsISD::Mult";
190   case MipsISD::Multu:             return "MipsISD::Multu";
191   case MipsISD::MAdd:              return "MipsISD::MAdd";
192   case MipsISD::MAddu:             return "MipsISD::MAddu";
193   case MipsISD::MSub:              return "MipsISD::MSub";
194   case MipsISD::MSubu:             return "MipsISD::MSubu";
195   case MipsISD::DivRem:            return "MipsISD::DivRem";
196   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
197   case MipsISD::DivRem16:          return "MipsISD::DivRem16";
198   case MipsISD::DivRemU16:         return "MipsISD::DivRemU16";
199   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
200   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
201   case MipsISD::Wrapper:           return "MipsISD::Wrapper";
202   case MipsISD::Sync:              return "MipsISD::Sync";
203   case MipsISD::Ext:               return "MipsISD::Ext";
204   case MipsISD::Ins:               return "MipsISD::Ins";
205   case MipsISD::LWL:               return "MipsISD::LWL";
206   case MipsISD::LWR:               return "MipsISD::LWR";
207   case MipsISD::SWL:               return "MipsISD::SWL";
208   case MipsISD::SWR:               return "MipsISD::SWR";
209   case MipsISD::LDL:               return "MipsISD::LDL";
210   case MipsISD::LDR:               return "MipsISD::LDR";
211   case MipsISD::SDL:               return "MipsISD::SDL";
212   case MipsISD::SDR:               return "MipsISD::SDR";
213   case MipsISD::EXTP:              return "MipsISD::EXTP";
214   case MipsISD::EXTPDP:            return "MipsISD::EXTPDP";
215   case MipsISD::EXTR_S_H:          return "MipsISD::EXTR_S_H";
216   case MipsISD::EXTR_W:            return "MipsISD::EXTR_W";
217   case MipsISD::EXTR_R_W:          return "MipsISD::EXTR_R_W";
218   case MipsISD::EXTR_RS_W:         return "MipsISD::EXTR_RS_W";
219   case MipsISD::SHILO:             return "MipsISD::SHILO";
220   case MipsISD::MTHLIP:            return "MipsISD::MTHLIP";
221   case MipsISD::MULT:              return "MipsISD::MULT";
222   case MipsISD::MULTU:             return "MipsISD::MULTU";
223   case MipsISD::MADD_DSP:          return "MipsISD::MADD_DSP";
224   case MipsISD::MADDU_DSP:         return "MipsISD::MADDU_DSP";
225   case MipsISD::MSUB_DSP:          return "MipsISD::MSUB_DSP";
226   case MipsISD::MSUBU_DSP:         return "MipsISD::MSUBU_DSP";
227   case MipsISD::SHLL_DSP:          return "MipsISD::SHLL_DSP";
228   case MipsISD::SHRA_DSP:          return "MipsISD::SHRA_DSP";
229   case MipsISD::SHRL_DSP:          return "MipsISD::SHRL_DSP";
230   case MipsISD::SETCC_DSP:         return "MipsISD::SETCC_DSP";
231   case MipsISD::SELECT_CC_DSP:     return "MipsISD::SELECT_CC_DSP";
232   case MipsISD::VALL_ZERO:         return "MipsISD::VALL_ZERO";
233   case MipsISD::VANY_ZERO:         return "MipsISD::VANY_ZERO";
234   case MipsISD::VALL_NONZERO:      return "MipsISD::VALL_NONZERO";
235   case MipsISD::VANY_NONZERO:      return "MipsISD::VANY_NONZERO";
236   case MipsISD::VCEQ:              return "MipsISD::VCEQ";
237   case MipsISD::VCLE_S:            return "MipsISD::VCLE_S";
238   case MipsISD::VCLE_U:            return "MipsISD::VCLE_U";
239   case MipsISD::VCLT_S:            return "MipsISD::VCLT_S";
240   case MipsISD::VCLT_U:            return "MipsISD::VCLT_U";
241   case MipsISD::VSMAX:             return "MipsISD::VSMAX";
242   case MipsISD::VSMIN:             return "MipsISD::VSMIN";
243   case MipsISD::VUMAX:             return "MipsISD::VUMAX";
244   case MipsISD::VUMIN:             return "MipsISD::VUMIN";
245   case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
246   case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
247   case MipsISD::VNOR:              return "MipsISD::VNOR";
248   case MipsISD::VSHF:              return "MipsISD::VSHF";
249   case MipsISD::SHF:               return "MipsISD::SHF";
250   case MipsISD::ILVEV:             return "MipsISD::ILVEV";
251   case MipsISD::ILVOD:             return "MipsISD::ILVOD";
252   case MipsISD::ILVL:              return "MipsISD::ILVL";
253   case MipsISD::ILVR:              return "MipsISD::ILVR";
254   case MipsISD::PCKEV:             return "MipsISD::PCKEV";
255   case MipsISD::PCKOD:             return "MipsISD::PCKOD";
256   default:                         return NULL;
257   }
258 }
259
260 MipsTargetLowering::
261 MipsTargetLowering(MipsTargetMachine &TM)
262   : TargetLowering(TM, new MipsTargetObjectFile()),
263     Subtarget(&TM.getSubtarget<MipsSubtarget>()),
264     HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
265     IsO32(Subtarget->isABI_O32()) {
266   // Mips does not have i1 type, so use i32 for
267   // setcc operations results (slt, sgt, ...).
268   setBooleanContents(ZeroOrOneBooleanContent);
269   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
270
271   // Load extented operations for i1 types must be promoted
272   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
273   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
274   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
275
276   // MIPS doesn't have extending float->double load/store
277   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
278   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
279
280   // Used by legalize types to correctly generate the setcc result.
281   // Without this, every float setcc comes with a AND/OR with the result,
282   // we don't want this, since the fpcmp result goes to a flag register,
283   // which is used implicitly by brcond and select operations.
284   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
285
286   // Mips Custom Operations
287   setOperationAction(ISD::BR_JT,              MVT::Other, Custom);
288   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
289   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
290   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
291   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
292   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
293   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
294   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
295   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
296   setOperationAction(ISD::SELECT_CC,          MVT::f32,   Custom);
297   setOperationAction(ISD::SELECT_CC,          MVT::f64,   Custom);
298   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
299   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
300   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
301   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
302   setOperationAction(ISD::FCOPYSIGN,          MVT::f32,   Custom);
303   setOperationAction(ISD::FCOPYSIGN,          MVT::f64,   Custom);
304   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
305
306   if (!TM.Options.NoNaNsFPMath) {
307     setOperationAction(ISD::FABS,             MVT::f32,   Custom);
308     setOperationAction(ISD::FABS,             MVT::f64,   Custom);
309   }
310
311   if (HasMips64) {
312     setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
313     setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
314     setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
315     setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
316     setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
317     setOperationAction(ISD::SELECT,             MVT::i64,   Custom);
318     setOperationAction(ISD::LOAD,               MVT::i64,   Custom);
319     setOperationAction(ISD::STORE,              MVT::i64,   Custom);
320     setOperationAction(ISD::FP_TO_SINT,         MVT::i64,   Custom);
321   }
322
323   if (!HasMips64) {
324     setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Custom);
325     setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Custom);
326     setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Custom);
327   }
328
329   setOperationAction(ISD::ADD,                MVT::i32,   Custom);
330   if (HasMips64)
331     setOperationAction(ISD::ADD,                MVT::i64,   Custom);
332
333   setOperationAction(ISD::SDIV, MVT::i32, Expand);
334   setOperationAction(ISD::SREM, MVT::i32, Expand);
335   setOperationAction(ISD::UDIV, MVT::i32, Expand);
336   setOperationAction(ISD::UREM, MVT::i32, Expand);
337   setOperationAction(ISD::SDIV, MVT::i64, Expand);
338   setOperationAction(ISD::SREM, MVT::i64, Expand);
339   setOperationAction(ISD::UDIV, MVT::i64, Expand);
340   setOperationAction(ISD::UREM, MVT::i64, Expand);
341
342   // Operations not directly supported by Mips.
343   setOperationAction(ISD::BR_CC,             MVT::f32,   Expand);
344   setOperationAction(ISD::BR_CC,             MVT::f64,   Expand);
345   setOperationAction(ISD::BR_CC,             MVT::i32,   Expand);
346   setOperationAction(ISD::BR_CC,             MVT::i64,   Expand);
347   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
348   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
349   setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
350   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
351   setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
352   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
353   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
354   setOperationAction(ISD::CTPOP,             MVT::i64,   Expand);
355   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
356   setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
357   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i32,   Expand);
358   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i64,   Expand);
359   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i32,   Expand);
360   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i64,   Expand);
361   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
362   setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
363   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,  Expand);
364   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,  Expand);
365
366   if (!Subtarget->hasMips32r2())
367     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
368
369   if (!Subtarget->hasMips64r2())
370     setOperationAction(ISD::ROTR, MVT::i64,   Expand);
371
372   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
373   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
374   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
375   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
376   setOperationAction(ISD::FSINCOS,           MVT::f32,   Expand);
377   setOperationAction(ISD::FSINCOS,           MVT::f64,   Expand);
378   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
379   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
380   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
381   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
382   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
383   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
384   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
385   setOperationAction(ISD::FMA,               MVT::f32,   Expand);
386   setOperationAction(ISD::FMA,               MVT::f64,   Expand);
387   setOperationAction(ISD::FREM,              MVT::f32,   Expand);
388   setOperationAction(ISD::FREM,              MVT::f64,   Expand);
389
390   if (!TM.Options.NoNaNsFPMath) {
391     setOperationAction(ISD::FNEG,             MVT::f32,   Expand);
392     setOperationAction(ISD::FNEG,             MVT::f64,   Expand);
393   }
394
395   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
396
397   setOperationAction(ISD::VAARG,             MVT::Other, Expand);
398   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
399   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
400
401   // Use the default for now
402   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
403   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
404
405   setOperationAction(ISD::ATOMIC_LOAD,       MVT::i32,    Expand);
406   setOperationAction(ISD::ATOMIC_LOAD,       MVT::i64,    Expand);
407   setOperationAction(ISD::ATOMIC_STORE,      MVT::i32,    Expand);
408   setOperationAction(ISD::ATOMIC_STORE,      MVT::i64,    Expand);
409
410   setInsertFencesForAtomic(true);
411
412   if (!Subtarget->hasSEInReg()) {
413     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
414     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
415   }
416
417   if (!Subtarget->hasBitCount()) {
418     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
419     setOperationAction(ISD::CTLZ, MVT::i64, Expand);
420   }
421
422   if (!Subtarget->hasSwap()) {
423     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
424     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
425   }
426
427   if (HasMips64) {
428     setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
429     setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
430     setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
431     setTruncStoreAction(MVT::i64, MVT::i32, Custom);
432   }
433
434   setOperationAction(ISD::TRAP, MVT::Other, Legal);
435
436   setTargetDAGCombine(ISD::SDIVREM);
437   setTargetDAGCombine(ISD::UDIVREM);
438   setTargetDAGCombine(ISD::SELECT);
439   setTargetDAGCombine(ISD::AND);
440   setTargetDAGCombine(ISD::OR);
441   setTargetDAGCombine(ISD::ADD);
442
443   setMinFunctionAlignment(HasMips64 ? 3 : 2);
444
445   setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
446
447   setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
448   setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
449
450   MaxStoresPerMemcpy = 16;
451 }
452
453 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
454   if (TM.getSubtargetImpl()->inMips16Mode())
455     return llvm::createMips16TargetLowering(TM);
456
457   return llvm::createMipsSETargetLowering(TM);
458 }
459
460 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
461   if (!VT.isVector())
462     return MVT::i32;
463   return VT.changeVectorElementTypeToInteger();
464 }
465
466 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
467                                     TargetLowering::DAGCombinerInfo &DCI,
468                                     const MipsSubtarget *Subtarget) {
469   if (DCI.isBeforeLegalizeOps())
470     return SDValue();
471
472   EVT Ty = N->getValueType(0);
473   unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
474   unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
475   unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
476                                                   MipsISD::DivRemU16;
477   SDLoc DL(N);
478
479   SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
480                                N->getOperand(0), N->getOperand(1));
481   SDValue InChain = DAG.getEntryNode();
482   SDValue InGlue = DivRem;
483
484   // insert MFLO
485   if (N->hasAnyUseOfValue(0)) {
486     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
487                                             InGlue);
488     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
489     InChain = CopyFromLo.getValue(1);
490     InGlue = CopyFromLo.getValue(2);
491   }
492
493   // insert MFHI
494   if (N->hasAnyUseOfValue(1)) {
495     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
496                                             HI, Ty, InGlue);
497     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
498   }
499
500   return SDValue();
501 }
502
503 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
504   switch (CC) {
505   default: llvm_unreachable("Unknown fp condition code!");
506   case ISD::SETEQ:
507   case ISD::SETOEQ: return Mips::FCOND_OEQ;
508   case ISD::SETUNE: return Mips::FCOND_UNE;
509   case ISD::SETLT:
510   case ISD::SETOLT: return Mips::FCOND_OLT;
511   case ISD::SETGT:
512   case ISD::SETOGT: return Mips::FCOND_OGT;
513   case ISD::SETLE:
514   case ISD::SETOLE: return Mips::FCOND_OLE;
515   case ISD::SETGE:
516   case ISD::SETOGE: return Mips::FCOND_OGE;
517   case ISD::SETULT: return Mips::FCOND_ULT;
518   case ISD::SETULE: return Mips::FCOND_ULE;
519   case ISD::SETUGT: return Mips::FCOND_UGT;
520   case ISD::SETUGE: return Mips::FCOND_UGE;
521   case ISD::SETUO:  return Mips::FCOND_UN;
522   case ISD::SETO:   return Mips::FCOND_OR;
523   case ISD::SETNE:
524   case ISD::SETONE: return Mips::FCOND_ONE;
525   case ISD::SETUEQ: return Mips::FCOND_UEQ;
526   }
527 }
528
529
530 /// This function returns true if the floating point conditional branches and
531 /// conditional moves which use condition code CC should be inverted.
532 static bool invertFPCondCodeUser(Mips::CondCode CC) {
533   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
534     return false;
535
536   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
537          "Illegal Condition Code");
538
539   return true;
540 }
541
542 // Creates and returns an FPCmp node from a setcc node.
543 // Returns Op if setcc is not a floating point comparison.
544 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
545   // must be a SETCC node
546   if (Op.getOpcode() != ISD::SETCC)
547     return Op;
548
549   SDValue LHS = Op.getOperand(0);
550
551   if (!LHS.getValueType().isFloatingPoint())
552     return Op;
553
554   SDValue RHS = Op.getOperand(1);
555   SDLoc DL(Op);
556
557   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
558   // node if necessary.
559   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
560
561   return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
562                      DAG.getConstant(condCodeToFCC(CC), MVT::i32));
563 }
564
565 // Creates and returns a CMovFPT/F node.
566 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
567                             SDValue False, SDLoc DL) {
568   ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
569   bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
570   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
571
572   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
573                      True.getValueType(), True, FCC0, False, Cond);
574 }
575
576 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
577                                     TargetLowering::DAGCombinerInfo &DCI,
578                                     const MipsSubtarget *Subtarget) {
579   if (DCI.isBeforeLegalizeOps())
580     return SDValue();
581
582   SDValue SetCC = N->getOperand(0);
583
584   if ((SetCC.getOpcode() != ISD::SETCC) ||
585       !SetCC.getOperand(0).getValueType().isInteger())
586     return SDValue();
587
588   SDValue False = N->getOperand(2);
589   EVT FalseTy = False.getValueType();
590
591   if (!FalseTy.isInteger())
592     return SDValue();
593
594   ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
595
596   if (!CN || CN->getZExtValue())
597     return SDValue();
598
599   const SDLoc DL(N);
600   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
601   SDValue True = N->getOperand(1);
602
603   SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
604                        SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
605
606   return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
607 }
608
609 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
610                                  TargetLowering::DAGCombinerInfo &DCI,
611                                  const MipsSubtarget *Subtarget) {
612   // Pattern match EXT.
613   //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
614   //  => ext $dst, $src, size, pos
615   if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
616     return SDValue();
617
618   SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
619   unsigned ShiftRightOpc = ShiftRight.getOpcode();
620
621   // Op's first operand must be a shift right.
622   if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
623     return SDValue();
624
625   // The second operand of the shift must be an immediate.
626   ConstantSDNode *CN;
627   if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
628     return SDValue();
629
630   uint64_t Pos = CN->getZExtValue();
631   uint64_t SMPos, SMSize;
632
633   // Op's second operand must be a shifted mask.
634   if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
635       !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
636     return SDValue();
637
638   // Return if the shifted mask does not start at bit 0 or the sum of its size
639   // and Pos exceeds the word's size.
640   EVT ValTy = N->getValueType(0);
641   if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
642     return SDValue();
643
644   return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
645                      ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
646                      DAG.getConstant(SMSize, MVT::i32));
647 }
648
649 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
650                                 TargetLowering::DAGCombinerInfo &DCI,
651                                 const MipsSubtarget *Subtarget) {
652   // Pattern match INS.
653   //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
654   //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1
655   //  => ins $dst, $src, size, pos, $src1
656   if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
657     return SDValue();
658
659   SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
660   uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
661   ConstantSDNode *CN;
662
663   // See if Op's first operand matches (and $src1 , mask0).
664   if (And0.getOpcode() != ISD::AND)
665     return SDValue();
666
667   if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
668       !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
669     return SDValue();
670
671   // See if Op's second operand matches (and (shl $src, pos), mask1).
672   if (And1.getOpcode() != ISD::AND)
673     return SDValue();
674
675   if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
676       !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
677     return SDValue();
678
679   // The shift masks must have the same position and size.
680   if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
681     return SDValue();
682
683   SDValue Shl = And1.getOperand(0);
684   if (Shl.getOpcode() != ISD::SHL)
685     return SDValue();
686
687   if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
688     return SDValue();
689
690   unsigned Shamt = CN->getZExtValue();
691
692   // Return if the shift amount and the first bit position of mask are not the
693   // same.
694   EVT ValTy = N->getValueType(0);
695   if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
696     return SDValue();
697
698   return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
699                      DAG.getConstant(SMPos0, MVT::i32),
700                      DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
701 }
702
703 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
704                                  TargetLowering::DAGCombinerInfo &DCI,
705                                  const MipsSubtarget *Subtarget) {
706   // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
707
708   if (DCI.isBeforeLegalizeOps())
709     return SDValue();
710
711   SDValue Add = N->getOperand(1);
712
713   if (Add.getOpcode() != ISD::ADD)
714     return SDValue();
715
716   SDValue Lo = Add.getOperand(1);
717
718   if ((Lo.getOpcode() != MipsISD::Lo) ||
719       (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
720     return SDValue();
721
722   EVT ValTy = N->getValueType(0);
723   SDLoc DL(N);
724
725   SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
726                              Add.getOperand(0));
727   return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
728 }
729
730 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
731   const {
732   SelectionDAG &DAG = DCI.DAG;
733   unsigned Opc = N->getOpcode();
734
735   switch (Opc) {
736   default: break;
737   case ISD::SDIVREM:
738   case ISD::UDIVREM:
739     return performDivRemCombine(N, DAG, DCI, Subtarget);
740   case ISD::SELECT:
741     return performSELECTCombine(N, DAG, DCI, Subtarget);
742   case ISD::AND:
743     return performANDCombine(N, DAG, DCI, Subtarget);
744   case ISD::OR:
745     return performORCombine(N, DAG, DCI, Subtarget);
746   case ISD::ADD:
747     return performADDCombine(N, DAG, DCI, Subtarget);
748   }
749
750   return SDValue();
751 }
752
753 void
754 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
755                                           SmallVectorImpl<SDValue> &Results,
756                                           SelectionDAG &DAG) const {
757   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
758
759   for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
760     Results.push_back(Res.getValue(I));
761 }
762
763 void
764 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
765                                        SmallVectorImpl<SDValue> &Results,
766                                        SelectionDAG &DAG) const {
767   return LowerOperationWrapper(N, Results, DAG);
768 }
769
770 SDValue MipsTargetLowering::
771 LowerOperation(SDValue Op, SelectionDAG &DAG) const
772 {
773   switch (Op.getOpcode())
774   {
775   case ISD::BR_JT:              return lowerBR_JT(Op, DAG);
776   case ISD::BRCOND:             return lowerBRCOND(Op, DAG);
777   case ISD::ConstantPool:       return lowerConstantPool(Op, DAG);
778   case ISD::GlobalAddress:      return lowerGlobalAddress(Op, DAG);
779   case ISD::BlockAddress:       return lowerBlockAddress(Op, DAG);
780   case ISD::GlobalTLSAddress:   return lowerGlobalTLSAddress(Op, DAG);
781   case ISD::JumpTable:          return lowerJumpTable(Op, DAG);
782   case ISD::SELECT:             return lowerSELECT(Op, DAG);
783   case ISD::SELECT_CC:          return lowerSELECT_CC(Op, DAG);
784   case ISD::SETCC:              return lowerSETCC(Op, DAG);
785   case ISD::VASTART:            return lowerVASTART(Op, DAG);
786   case ISD::FCOPYSIGN:          return lowerFCOPYSIGN(Op, DAG);
787   case ISD::FABS:               return lowerFABS(Op, DAG);
788   case ISD::FRAMEADDR:          return lowerFRAMEADDR(Op, DAG);
789   case ISD::RETURNADDR:         return lowerRETURNADDR(Op, DAG);
790   case ISD::EH_RETURN:          return lowerEH_RETURN(Op, DAG);
791   case ISD::ATOMIC_FENCE:       return lowerATOMIC_FENCE(Op, DAG);
792   case ISD::SHL_PARTS:          return lowerShiftLeftParts(Op, DAG);
793   case ISD::SRA_PARTS:          return lowerShiftRightParts(Op, DAG, true);
794   case ISD::SRL_PARTS:          return lowerShiftRightParts(Op, DAG, false);
795   case ISD::LOAD:               return lowerLOAD(Op, DAG);
796   case ISD::STORE:              return lowerSTORE(Op, DAG);
797   case ISD::ADD:                return lowerADD(Op, DAG);
798   case ISD::FP_TO_SINT:         return lowerFP_TO_SINT(Op, DAG);
799   }
800   return SDValue();
801 }
802
803 //===----------------------------------------------------------------------===//
804 //  Lower helper functions
805 //===----------------------------------------------------------------------===//
806
807 // addLiveIn - This helper function adds the specified physical register to the
808 // MachineFunction as a live in value.  It also creates a corresponding
809 // virtual register for it.
810 static unsigned
811 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
812 {
813   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
814   MF.getRegInfo().addLiveIn(PReg, VReg);
815   return VReg;
816 }
817
818 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
819                                           MachineBasicBlock &MBB,
820                                           const TargetInstrInfo &TII,
821                                           bool Is64Bit) {
822   if (NoZeroDivCheck)
823     return &MBB;
824
825   // Insert instruction "teq $divisor_reg, $zero, 7".
826   MachineBasicBlock::iterator I(MI);
827   MachineInstrBuilder MIB;
828   MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
829     .addOperand(MI->getOperand(2)).addReg(Mips::ZERO).addImm(7);
830
831   // Use the 32-bit sub-register if this is a 64-bit division.
832   if (Is64Bit)
833     MIB->getOperand(0).setSubReg(Mips::sub_32);
834
835   return &MBB;
836 }
837
838 MachineBasicBlock *
839 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
840                                                 MachineBasicBlock *BB) const {
841   switch (MI->getOpcode()) {
842   default:
843     llvm_unreachable("Unexpected instr type to insert");
844   case Mips::ATOMIC_LOAD_ADD_I8:
845     return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
846   case Mips::ATOMIC_LOAD_ADD_I16:
847     return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
848   case Mips::ATOMIC_LOAD_ADD_I32:
849     return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
850   case Mips::ATOMIC_LOAD_ADD_I64:
851     return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
852
853   case Mips::ATOMIC_LOAD_AND_I8:
854     return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
855   case Mips::ATOMIC_LOAD_AND_I16:
856     return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
857   case Mips::ATOMIC_LOAD_AND_I32:
858     return emitAtomicBinary(MI, BB, 4, Mips::AND);
859   case Mips::ATOMIC_LOAD_AND_I64:
860     return emitAtomicBinary(MI, BB, 8, Mips::AND64);
861
862   case Mips::ATOMIC_LOAD_OR_I8:
863     return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
864   case Mips::ATOMIC_LOAD_OR_I16:
865     return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
866   case Mips::ATOMIC_LOAD_OR_I32:
867     return emitAtomicBinary(MI, BB, 4, Mips::OR);
868   case Mips::ATOMIC_LOAD_OR_I64:
869     return emitAtomicBinary(MI, BB, 8, Mips::OR64);
870
871   case Mips::ATOMIC_LOAD_XOR_I8:
872     return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
873   case Mips::ATOMIC_LOAD_XOR_I16:
874     return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
875   case Mips::ATOMIC_LOAD_XOR_I32:
876     return emitAtomicBinary(MI, BB, 4, Mips::XOR);
877   case Mips::ATOMIC_LOAD_XOR_I64:
878     return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
879
880   case Mips::ATOMIC_LOAD_NAND_I8:
881     return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
882   case Mips::ATOMIC_LOAD_NAND_I16:
883     return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
884   case Mips::ATOMIC_LOAD_NAND_I32:
885     return emitAtomicBinary(MI, BB, 4, 0, true);
886   case Mips::ATOMIC_LOAD_NAND_I64:
887     return emitAtomicBinary(MI, BB, 8, 0, true);
888
889   case Mips::ATOMIC_LOAD_SUB_I8:
890     return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
891   case Mips::ATOMIC_LOAD_SUB_I16:
892     return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
893   case Mips::ATOMIC_LOAD_SUB_I32:
894     return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
895   case Mips::ATOMIC_LOAD_SUB_I64:
896     return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
897
898   case Mips::ATOMIC_SWAP_I8:
899     return emitAtomicBinaryPartword(MI, BB, 1, 0);
900   case Mips::ATOMIC_SWAP_I16:
901     return emitAtomicBinaryPartword(MI, BB, 2, 0);
902   case Mips::ATOMIC_SWAP_I32:
903     return emitAtomicBinary(MI, BB, 4, 0);
904   case Mips::ATOMIC_SWAP_I64:
905     return emitAtomicBinary(MI, BB, 8, 0);
906
907   case Mips::ATOMIC_CMP_SWAP_I8:
908     return emitAtomicCmpSwapPartword(MI, BB, 1);
909   case Mips::ATOMIC_CMP_SWAP_I16:
910     return emitAtomicCmpSwapPartword(MI, BB, 2);
911   case Mips::ATOMIC_CMP_SWAP_I32:
912     return emitAtomicCmpSwap(MI, BB, 4);
913   case Mips::ATOMIC_CMP_SWAP_I64:
914     return emitAtomicCmpSwap(MI, BB, 8);
915   case Mips::PseudoSDIV:
916   case Mips::PseudoUDIV:
917     return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
918   case Mips::PseudoDSDIV:
919   case Mips::PseudoDUDIV:
920     return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
921   }
922 }
923
924 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
925 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
926 MachineBasicBlock *
927 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
928                                      unsigned Size, unsigned BinOpcode,
929                                      bool Nand) const {
930   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
931
932   MachineFunction *MF = BB->getParent();
933   MachineRegisterInfo &RegInfo = MF->getRegInfo();
934   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
935   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
936   DebugLoc DL = MI->getDebugLoc();
937   unsigned LL, SC, AND, NOR, ZERO, BEQ;
938
939   if (Size == 4) {
940     LL = Mips::LL;
941     SC = Mips::SC;
942     AND = Mips::AND;
943     NOR = Mips::NOR;
944     ZERO = Mips::ZERO;
945     BEQ = Mips::BEQ;
946   }
947   else {
948     LL = Mips::LLD;
949     SC = Mips::SCD;
950     AND = Mips::AND64;
951     NOR = Mips::NOR64;
952     ZERO = Mips::ZERO_64;
953     BEQ = Mips::BEQ64;
954   }
955
956   unsigned OldVal = MI->getOperand(0).getReg();
957   unsigned Ptr = MI->getOperand(1).getReg();
958   unsigned Incr = MI->getOperand(2).getReg();
959
960   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
961   unsigned AndRes = RegInfo.createVirtualRegister(RC);
962   unsigned Success = RegInfo.createVirtualRegister(RC);
963
964   // insert new blocks after the current block
965   const BasicBlock *LLVM_BB = BB->getBasicBlock();
966   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
967   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
968   MachineFunction::iterator It = BB;
969   ++It;
970   MF->insert(It, loopMBB);
971   MF->insert(It, exitMBB);
972
973   // Transfer the remainder of BB and its successor edges to exitMBB.
974   exitMBB->splice(exitMBB->begin(), BB,
975                   llvm::next(MachineBasicBlock::iterator(MI)),
976                   BB->end());
977   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
978
979   //  thisMBB:
980   //    ...
981   //    fallthrough --> loopMBB
982   BB->addSuccessor(loopMBB);
983   loopMBB->addSuccessor(loopMBB);
984   loopMBB->addSuccessor(exitMBB);
985
986   //  loopMBB:
987   //    ll oldval, 0(ptr)
988   //    <binop> storeval, oldval, incr
989   //    sc success, storeval, 0(ptr)
990   //    beq success, $0, loopMBB
991   BB = loopMBB;
992   BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
993   if (Nand) {
994     //  and andres, oldval, incr
995     //  nor storeval, $0, andres
996     BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
997     BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
998   } else if (BinOpcode) {
999     //  <binop> storeval, oldval, incr
1000     BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1001   } else {
1002     StoreVal = Incr;
1003   }
1004   BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1005   BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1006
1007   MI->eraseFromParent();   // The instruction is gone now.
1008
1009   return exitMBB;
1010 }
1011
1012 MachineBasicBlock *
1013 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
1014                                              MachineBasicBlock *BB,
1015                                              unsigned Size, unsigned BinOpcode,
1016                                              bool Nand) const {
1017   assert((Size == 1 || Size == 2) &&
1018       "Unsupported size for EmitAtomicBinaryPartial.");
1019
1020   MachineFunction *MF = BB->getParent();
1021   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1022   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1023   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1024   DebugLoc DL = MI->getDebugLoc();
1025
1026   unsigned Dest = MI->getOperand(0).getReg();
1027   unsigned Ptr = MI->getOperand(1).getReg();
1028   unsigned Incr = MI->getOperand(2).getReg();
1029
1030   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1031   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1032   unsigned Mask = RegInfo.createVirtualRegister(RC);
1033   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1034   unsigned NewVal = RegInfo.createVirtualRegister(RC);
1035   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1036   unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1037   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1038   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1039   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1040   unsigned AndRes = RegInfo.createVirtualRegister(RC);
1041   unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1042   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1043   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1044   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1045   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1046   unsigned SllRes = RegInfo.createVirtualRegister(RC);
1047   unsigned Success = RegInfo.createVirtualRegister(RC);
1048
1049   // insert new blocks after the current block
1050   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1051   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1052   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1053   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1054   MachineFunction::iterator It = BB;
1055   ++It;
1056   MF->insert(It, loopMBB);
1057   MF->insert(It, sinkMBB);
1058   MF->insert(It, exitMBB);
1059
1060   // Transfer the remainder of BB and its successor edges to exitMBB.
1061   exitMBB->splice(exitMBB->begin(), BB,
1062                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1063   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1064
1065   BB->addSuccessor(loopMBB);
1066   loopMBB->addSuccessor(loopMBB);
1067   loopMBB->addSuccessor(sinkMBB);
1068   sinkMBB->addSuccessor(exitMBB);
1069
1070   //  thisMBB:
1071   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1072   //    and     alignedaddr,ptr,masklsb2
1073   //    andi    ptrlsb2,ptr,3
1074   //    sll     shiftamt,ptrlsb2,3
1075   //    ori     maskupper,$0,255               # 0xff
1076   //    sll     mask,maskupper,shiftamt
1077   //    nor     mask2,$0,mask
1078   //    sll     incr2,incr,shiftamt
1079
1080   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1081   BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1082     .addReg(Mips::ZERO).addImm(-4);
1083   BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1084     .addReg(Ptr).addReg(MaskLSB2);
1085   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1086   if (Subtarget->isLittle()) {
1087     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1088   } else {
1089     unsigned Off = RegInfo.createVirtualRegister(RC);
1090     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1091       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1092     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1093   }
1094   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1095     .addReg(Mips::ZERO).addImm(MaskImm);
1096   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1097     .addReg(MaskUpper).addReg(ShiftAmt);
1098   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1099   BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1100
1101   // atomic.load.binop
1102   // loopMBB:
1103   //   ll      oldval,0(alignedaddr)
1104   //   binop   binopres,oldval,incr2
1105   //   and     newval,binopres,mask
1106   //   and     maskedoldval0,oldval,mask2
1107   //   or      storeval,maskedoldval0,newval
1108   //   sc      success,storeval,0(alignedaddr)
1109   //   beq     success,$0,loopMBB
1110
1111   // atomic.swap
1112   // loopMBB:
1113   //   ll      oldval,0(alignedaddr)
1114   //   and     newval,incr2,mask
1115   //   and     maskedoldval0,oldval,mask2
1116   //   or      storeval,maskedoldval0,newval
1117   //   sc      success,storeval,0(alignedaddr)
1118   //   beq     success,$0,loopMBB
1119
1120   BB = loopMBB;
1121   BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1122   if (Nand) {
1123     //  and andres, oldval, incr2
1124     //  nor binopres, $0, andres
1125     //  and newval, binopres, mask
1126     BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1127     BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1128       .addReg(Mips::ZERO).addReg(AndRes);
1129     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1130   } else if (BinOpcode) {
1131     //  <binop> binopres, oldval, incr2
1132     //  and newval, binopres, mask
1133     BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1134     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1135   } else {// atomic.swap
1136     //  and newval, incr2, mask
1137     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1138   }
1139
1140   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1141     .addReg(OldVal).addReg(Mask2);
1142   BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1143     .addReg(MaskedOldVal0).addReg(NewVal);
1144   BuildMI(BB, DL, TII->get(Mips::SC), Success)
1145     .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1146   BuildMI(BB, DL, TII->get(Mips::BEQ))
1147     .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1148
1149   //  sinkMBB:
1150   //    and     maskedoldval1,oldval,mask
1151   //    srl     srlres,maskedoldval1,shiftamt
1152   //    sll     sllres,srlres,24
1153   //    sra     dest,sllres,24
1154   BB = sinkMBB;
1155   int64_t ShiftImm = (Size == 1) ? 24 : 16;
1156
1157   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1158     .addReg(OldVal).addReg(Mask);
1159   BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1160       .addReg(MaskedOldVal1).addReg(ShiftAmt);
1161   BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1162       .addReg(SrlRes).addImm(ShiftImm);
1163   BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1164       .addReg(SllRes).addImm(ShiftImm);
1165
1166   MI->eraseFromParent();   // The instruction is gone now.
1167
1168   return exitMBB;
1169 }
1170
1171 MachineBasicBlock *
1172 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1173                                       MachineBasicBlock *BB,
1174                                       unsigned Size) const {
1175   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1176
1177   MachineFunction *MF = BB->getParent();
1178   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1179   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1180   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1181   DebugLoc DL = MI->getDebugLoc();
1182   unsigned LL, SC, ZERO, BNE, BEQ;
1183
1184   if (Size == 4) {
1185     LL = Mips::LL;
1186     SC = Mips::SC;
1187     ZERO = Mips::ZERO;
1188     BNE = Mips::BNE;
1189     BEQ = Mips::BEQ;
1190   }
1191   else {
1192     LL = Mips::LLD;
1193     SC = Mips::SCD;
1194     ZERO = Mips::ZERO_64;
1195     BNE = Mips::BNE64;
1196     BEQ = Mips::BEQ64;
1197   }
1198
1199   unsigned Dest    = MI->getOperand(0).getReg();
1200   unsigned Ptr     = MI->getOperand(1).getReg();
1201   unsigned OldVal  = MI->getOperand(2).getReg();
1202   unsigned NewVal  = MI->getOperand(3).getReg();
1203
1204   unsigned Success = RegInfo.createVirtualRegister(RC);
1205
1206   // insert new blocks after the current block
1207   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1208   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1209   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1210   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1211   MachineFunction::iterator It = BB;
1212   ++It;
1213   MF->insert(It, loop1MBB);
1214   MF->insert(It, loop2MBB);
1215   MF->insert(It, exitMBB);
1216
1217   // Transfer the remainder of BB and its successor edges to exitMBB.
1218   exitMBB->splice(exitMBB->begin(), BB,
1219                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1220   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1221
1222   //  thisMBB:
1223   //    ...
1224   //    fallthrough --> loop1MBB
1225   BB->addSuccessor(loop1MBB);
1226   loop1MBB->addSuccessor(exitMBB);
1227   loop1MBB->addSuccessor(loop2MBB);
1228   loop2MBB->addSuccessor(loop1MBB);
1229   loop2MBB->addSuccessor(exitMBB);
1230
1231   // loop1MBB:
1232   //   ll dest, 0(ptr)
1233   //   bne dest, oldval, exitMBB
1234   BB = loop1MBB;
1235   BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1236   BuildMI(BB, DL, TII->get(BNE))
1237     .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1238
1239   // loop2MBB:
1240   //   sc success, newval, 0(ptr)
1241   //   beq success, $0, loop1MBB
1242   BB = loop2MBB;
1243   BuildMI(BB, DL, TII->get(SC), Success)
1244     .addReg(NewVal).addReg(Ptr).addImm(0);
1245   BuildMI(BB, DL, TII->get(BEQ))
1246     .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1247
1248   MI->eraseFromParent();   // The instruction is gone now.
1249
1250   return exitMBB;
1251 }
1252
1253 MachineBasicBlock *
1254 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1255                                               MachineBasicBlock *BB,
1256                                               unsigned Size) const {
1257   assert((Size == 1 || Size == 2) &&
1258       "Unsupported size for EmitAtomicCmpSwapPartial.");
1259
1260   MachineFunction *MF = BB->getParent();
1261   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1262   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1263   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1264   DebugLoc DL = MI->getDebugLoc();
1265
1266   unsigned Dest    = MI->getOperand(0).getReg();
1267   unsigned Ptr     = MI->getOperand(1).getReg();
1268   unsigned CmpVal  = MI->getOperand(2).getReg();
1269   unsigned NewVal  = MI->getOperand(3).getReg();
1270
1271   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1272   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1273   unsigned Mask = RegInfo.createVirtualRegister(RC);
1274   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1275   unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1276   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1277   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1278   unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1279   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1280   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1281   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1282   unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1283   unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1284   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1285   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1286   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1287   unsigned SllRes = RegInfo.createVirtualRegister(RC);
1288   unsigned Success = RegInfo.createVirtualRegister(RC);
1289
1290   // insert new blocks after the current block
1291   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1292   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1293   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1294   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1295   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1296   MachineFunction::iterator It = BB;
1297   ++It;
1298   MF->insert(It, loop1MBB);
1299   MF->insert(It, loop2MBB);
1300   MF->insert(It, sinkMBB);
1301   MF->insert(It, exitMBB);
1302
1303   // Transfer the remainder of BB and its successor edges to exitMBB.
1304   exitMBB->splice(exitMBB->begin(), BB,
1305                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1306   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1307
1308   BB->addSuccessor(loop1MBB);
1309   loop1MBB->addSuccessor(sinkMBB);
1310   loop1MBB->addSuccessor(loop2MBB);
1311   loop2MBB->addSuccessor(loop1MBB);
1312   loop2MBB->addSuccessor(sinkMBB);
1313   sinkMBB->addSuccessor(exitMBB);
1314
1315   // FIXME: computation of newval2 can be moved to loop2MBB.
1316   //  thisMBB:
1317   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1318   //    and     alignedaddr,ptr,masklsb2
1319   //    andi    ptrlsb2,ptr,3
1320   //    sll     shiftamt,ptrlsb2,3
1321   //    ori     maskupper,$0,255               # 0xff
1322   //    sll     mask,maskupper,shiftamt
1323   //    nor     mask2,$0,mask
1324   //    andi    maskedcmpval,cmpval,255
1325   //    sll     shiftedcmpval,maskedcmpval,shiftamt
1326   //    andi    maskednewval,newval,255
1327   //    sll     shiftednewval,maskednewval,shiftamt
1328   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1329   BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1330     .addReg(Mips::ZERO).addImm(-4);
1331   BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1332     .addReg(Ptr).addReg(MaskLSB2);
1333   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1334   if (Subtarget->isLittle()) {
1335     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1336   } else {
1337     unsigned Off = RegInfo.createVirtualRegister(RC);
1338     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1339       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1340     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1341   }
1342   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1343     .addReg(Mips::ZERO).addImm(MaskImm);
1344   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1345     .addReg(MaskUpper).addReg(ShiftAmt);
1346   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1347   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1348     .addReg(CmpVal).addImm(MaskImm);
1349   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1350     .addReg(MaskedCmpVal).addReg(ShiftAmt);
1351   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1352     .addReg(NewVal).addImm(MaskImm);
1353   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1354     .addReg(MaskedNewVal).addReg(ShiftAmt);
1355
1356   //  loop1MBB:
1357   //    ll      oldval,0(alginedaddr)
1358   //    and     maskedoldval0,oldval,mask
1359   //    bne     maskedoldval0,shiftedcmpval,sinkMBB
1360   BB = loop1MBB;
1361   BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1362   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1363     .addReg(OldVal).addReg(Mask);
1364   BuildMI(BB, DL, TII->get(Mips::BNE))
1365     .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1366
1367   //  loop2MBB:
1368   //    and     maskedoldval1,oldval,mask2
1369   //    or      storeval,maskedoldval1,shiftednewval
1370   //    sc      success,storeval,0(alignedaddr)
1371   //    beq     success,$0,loop1MBB
1372   BB = loop2MBB;
1373   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1374     .addReg(OldVal).addReg(Mask2);
1375   BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1376     .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1377   BuildMI(BB, DL, TII->get(Mips::SC), Success)
1378       .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1379   BuildMI(BB, DL, TII->get(Mips::BEQ))
1380       .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1381
1382   //  sinkMBB:
1383   //    srl     srlres,maskedoldval0,shiftamt
1384   //    sll     sllres,srlres,24
1385   //    sra     dest,sllres,24
1386   BB = sinkMBB;
1387   int64_t ShiftImm = (Size == 1) ? 24 : 16;
1388
1389   BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1390       .addReg(MaskedOldVal0).addReg(ShiftAmt);
1391   BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1392       .addReg(SrlRes).addImm(ShiftImm);
1393   BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1394       .addReg(SllRes).addImm(ShiftImm);
1395
1396   MI->eraseFromParent();   // The instruction is gone now.
1397
1398   return exitMBB;
1399 }
1400
1401 //===----------------------------------------------------------------------===//
1402 //  Misc Lower Operation implementation
1403 //===----------------------------------------------------------------------===//
1404 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1405   SDValue Chain = Op.getOperand(0);
1406   SDValue Table = Op.getOperand(1);
1407   SDValue Index = Op.getOperand(2);
1408   SDLoc DL(Op);
1409   EVT PTy = getPointerTy();
1410   unsigned EntrySize =
1411     DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1412
1413   Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1414                       DAG.getConstant(EntrySize, PTy));
1415   SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1416
1417   EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1418   Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1419                         MachinePointerInfo::getJumpTable(), MemVT, false, false,
1420                         0);
1421   Chain = Addr.getValue(1);
1422
1423   if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1424     // For PIC, the sequence is:
1425     // BRIND(load(Jumptable + index) + RelocBase)
1426     // RelocBase can be JumpTable, GOT or some sort of global base.
1427     Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1428                        getPICJumpTableRelocBase(Table, DAG));
1429   }
1430
1431   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1432 }
1433
1434 SDValue MipsTargetLowering::
1435 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1436 {
1437   // The first operand is the chain, the second is the condition, the third is
1438   // the block to branch to if the condition is true.
1439   SDValue Chain = Op.getOperand(0);
1440   SDValue Dest = Op.getOperand(2);
1441   SDLoc DL(Op);
1442
1443   SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1444
1445   // Return if flag is not set by a floating point comparison.
1446   if (CondRes.getOpcode() != MipsISD::FPCmp)
1447     return Op;
1448
1449   SDValue CCNode  = CondRes.getOperand(2);
1450   Mips::CondCode CC =
1451     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1452   unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1453   SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1454   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1455   return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1456                      FCC0, Dest, CondRes);
1457 }
1458
1459 SDValue MipsTargetLowering::
1460 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1461 {
1462   SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1463
1464   // Return if flag is not set by a floating point comparison.
1465   if (Cond.getOpcode() != MipsISD::FPCmp)
1466     return Op;
1467
1468   return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1469                       SDLoc(Op));
1470 }
1471
1472 SDValue MipsTargetLowering::
1473 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1474 {
1475   SDLoc DL(Op);
1476   EVT Ty = Op.getOperand(0).getValueType();
1477   SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1478                              getSetCCResultType(*DAG.getContext(), Ty),
1479                              Op.getOperand(0), Op.getOperand(1),
1480                              Op.getOperand(4));
1481
1482   return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1483                      Op.getOperand(3));
1484 }
1485
1486 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1487   SDValue Cond = createFPCmp(DAG, Op);
1488
1489   assert(Cond.getOpcode() == MipsISD::FPCmp &&
1490          "Floating point operand expected.");
1491
1492   SDValue True  = DAG.getConstant(1, MVT::i32);
1493   SDValue False = DAG.getConstant(0, MVT::i32);
1494
1495   return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1496 }
1497
1498 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1499                                                SelectionDAG &DAG) const {
1500   // FIXME there isn't actually debug info here
1501   SDLoc DL(Op);
1502   EVT Ty = Op.getValueType();
1503   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1504   const GlobalValue *GV = N->getGlobal();
1505
1506   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1507     const MipsTargetObjectFile &TLOF =
1508       (const MipsTargetObjectFile&)getObjFileLowering();
1509
1510     // %gp_rel relocation
1511     if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1512       SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1513                                               MipsII::MO_GPREL);
1514       SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1515                                       DAG.getVTList(MVT::i32), &GA, 1);
1516       SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1517       return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1518     }
1519
1520     // %hi/%lo relocation
1521     return getAddrNonPIC(N, Ty, DAG);
1522   }
1523
1524   if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1525     return getAddrLocal(N, Ty, DAG, HasMips64);
1526
1527   if (LargeGOT)
1528     return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1529                                  MipsII::MO_GOT_LO16);
1530
1531   return getAddrGlobal(N, Ty, DAG,
1532                        HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1533 }
1534
1535 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1536                                               SelectionDAG &DAG) const {
1537   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1538   EVT Ty = Op.getValueType();
1539
1540   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1541     return getAddrNonPIC(N, Ty, DAG);
1542
1543   return getAddrLocal(N, Ty, DAG, HasMips64);
1544 }
1545
1546 SDValue MipsTargetLowering::
1547 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1548 {
1549   // If the relocation model is PIC, use the General Dynamic TLS Model or
1550   // Local Dynamic TLS model, otherwise use the Initial Exec or
1551   // Local Exec TLS Model.
1552
1553   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1554   SDLoc DL(GA);
1555   const GlobalValue *GV = GA->getGlobal();
1556   EVT PtrVT = getPointerTy();
1557
1558   TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1559
1560   if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1561     // General Dynamic and Local Dynamic TLS Model.
1562     unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1563                                                       : MipsII::MO_TLSGD;
1564
1565     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1566     SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1567                                    getGlobalReg(DAG, PtrVT), TGA);
1568     unsigned PtrSize = PtrVT.getSizeInBits();
1569     IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1570
1571     SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1572
1573     ArgListTy Args;
1574     ArgListEntry Entry;
1575     Entry.Node = Argument;
1576     Entry.Ty = PtrTy;
1577     Args.push_back(Entry);
1578
1579     TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1580                   false, false, false, false, 0, CallingConv::C,
1581                   /*IsTailCall=*/false, /*doesNotRet=*/false,
1582                   /*isReturnValueUsed=*/true,
1583                   TlsGetAddr, Args, DAG, DL);
1584     std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1585
1586     SDValue Ret = CallResult.first;
1587
1588     if (model != TLSModel::LocalDynamic)
1589       return Ret;
1590
1591     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1592                                                MipsII::MO_DTPREL_HI);
1593     SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1594     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1595                                                MipsII::MO_DTPREL_LO);
1596     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1597     SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1598     return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1599   }
1600
1601   SDValue Offset;
1602   if (model == TLSModel::InitialExec) {
1603     // Initial Exec TLS Model
1604     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1605                                              MipsII::MO_GOTTPREL);
1606     TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1607                       TGA);
1608     Offset = DAG.getLoad(PtrVT, DL,
1609                          DAG.getEntryNode(), TGA, MachinePointerInfo(),
1610                          false, false, false, 0);
1611   } else {
1612     // Local Exec TLS Model
1613     assert(model == TLSModel::LocalExec);
1614     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1615                                                MipsII::MO_TPREL_HI);
1616     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1617                                                MipsII::MO_TPREL_LO);
1618     SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1619     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1620     Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1621   }
1622
1623   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1624   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1625 }
1626
1627 SDValue MipsTargetLowering::
1628 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1629 {
1630   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1631   EVT Ty = Op.getValueType();
1632
1633   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1634     return getAddrNonPIC(N, Ty, DAG);
1635
1636   return getAddrLocal(N, Ty, DAG, HasMips64);
1637 }
1638
1639 SDValue MipsTargetLowering::
1640 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1641 {
1642   // gp_rel relocation
1643   // FIXME: we should reference the constant pool using small data sections,
1644   // but the asm printer currently doesn't support this feature without
1645   // hacking it. This feature should come soon so we can uncomment the
1646   // stuff below.
1647   //if (IsInSmallSection(C->getType())) {
1648   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1649   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1650   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1651   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1652   EVT Ty = Op.getValueType();
1653
1654   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1655     return getAddrNonPIC(N, Ty, DAG);
1656
1657   return getAddrLocal(N, Ty, DAG, HasMips64);
1658 }
1659
1660 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1661   MachineFunction &MF = DAG.getMachineFunction();
1662   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1663
1664   SDLoc DL(Op);
1665   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1666                                  getPointerTy());
1667
1668   // vastart just stores the address of the VarArgsFrameIndex slot into the
1669   // memory location argument.
1670   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1671   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1672                       MachinePointerInfo(SV), false, false, 0);
1673 }
1674
1675 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1676   EVT TyX = Op.getOperand(0).getValueType();
1677   EVT TyY = Op.getOperand(1).getValueType();
1678   SDValue Const1 = DAG.getConstant(1, MVT::i32);
1679   SDValue Const31 = DAG.getConstant(31, MVT::i32);
1680   SDLoc DL(Op);
1681   SDValue Res;
1682
1683   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1684   // to i32.
1685   SDValue X = (TyX == MVT::f32) ?
1686     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1687     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1688                 Const1);
1689   SDValue Y = (TyY == MVT::f32) ?
1690     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1691     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1692                 Const1);
1693
1694   if (HasR2) {
1695     // ext  E, Y, 31, 1  ; extract bit31 of Y
1696     // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
1697     SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1698     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1699   } else {
1700     // sll SllX, X, 1
1701     // srl SrlX, SllX, 1
1702     // srl SrlY, Y, 31
1703     // sll SllY, SrlX, 31
1704     // or  Or, SrlX, SllY
1705     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1706     SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1707     SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1708     SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1709     Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1710   }
1711
1712   if (TyX == MVT::f32)
1713     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1714
1715   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1716                              Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1717   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1718 }
1719
1720 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1721   unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1722   unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1723   EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1724   SDValue Const1 = DAG.getConstant(1, MVT::i32);
1725   SDLoc DL(Op);
1726
1727   // Bitcast to integer nodes.
1728   SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1729   SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1730
1731   if (HasR2) {
1732     // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
1733     // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
1734     SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1735                             DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1736
1737     if (WidthX > WidthY)
1738       E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1739     else if (WidthY > WidthX)
1740       E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1741
1742     SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1743                             DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1744     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1745   }
1746
1747   // (d)sll SllX, X, 1
1748   // (d)srl SrlX, SllX, 1
1749   // (d)srl SrlY, Y, width(Y)-1
1750   // (d)sll SllY, SrlX, width(Y)-1
1751   // or     Or, SrlX, SllY
1752   SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1753   SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1754   SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1755                              DAG.getConstant(WidthY - 1, MVT::i32));
1756
1757   if (WidthX > WidthY)
1758     SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1759   else if (WidthY > WidthX)
1760     SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1761
1762   SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1763                              DAG.getConstant(WidthX - 1, MVT::i32));
1764   SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1765   return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1766 }
1767
1768 SDValue
1769 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1770   if (Subtarget->hasMips64())
1771     return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1772
1773   return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1774 }
1775
1776 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1777   SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1778   SDLoc DL(Op);
1779
1780   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1781   // to i32.
1782   SDValue X = (Op.getValueType() == MVT::f32) ?
1783     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1784     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1785                 Const1);
1786
1787   // Clear MSB.
1788   if (HasR2)
1789     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1790                       DAG.getRegister(Mips::ZERO, MVT::i32),
1791                       DAG.getConstant(31, MVT::i32), Const1, X);
1792   else {
1793     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1794     Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1795   }
1796
1797   if (Op.getValueType() == MVT::f32)
1798     return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1799
1800   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1801                              Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1802   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1803 }
1804
1805 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1806   SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1807   SDLoc DL(Op);
1808
1809   // Bitcast to integer node.
1810   SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1811
1812   // Clear MSB.
1813   if (HasR2)
1814     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1815                       DAG.getRegister(Mips::ZERO_64, MVT::i64),
1816                       DAG.getConstant(63, MVT::i32), Const1, X);
1817   else {
1818     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1819     Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1820   }
1821
1822   return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1823 }
1824
1825 SDValue
1826 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1827   if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1828     return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1829
1830   return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1831 }
1832
1833 SDValue MipsTargetLowering::
1834 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1835   // check the depth
1836   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1837          "Frame address can only be determined for current frame.");
1838
1839   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1840   MFI->setFrameAddressIsTaken(true);
1841   EVT VT = Op.getValueType();
1842   SDLoc DL(Op);
1843   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1844                                          IsN64 ? Mips::FP_64 : Mips::FP, VT);
1845   return FrameAddr;
1846 }
1847
1848 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1849                                             SelectionDAG &DAG) const {
1850   // check the depth
1851   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1852          "Return address can be determined only for current frame.");
1853
1854   MachineFunction &MF = DAG.getMachineFunction();
1855   MachineFrameInfo *MFI = MF.getFrameInfo();
1856   MVT VT = Op.getSimpleValueType();
1857   unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1858   MFI->setReturnAddressIsTaken(true);
1859
1860   // Return RA, which contains the return address. Mark it an implicit live-in.
1861   unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1862   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1863 }
1864
1865 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1866 // generated from __builtin_eh_return (offset, handler)
1867 // The effect of this is to adjust the stack pointer by "offset"
1868 // and then branch to "handler".
1869 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1870                                                                      const {
1871   MachineFunction &MF = DAG.getMachineFunction();
1872   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1873
1874   MipsFI->setCallsEhReturn();
1875   SDValue Chain     = Op.getOperand(0);
1876   SDValue Offset    = Op.getOperand(1);
1877   SDValue Handler   = Op.getOperand(2);
1878   SDLoc DL(Op);
1879   EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1880
1881   // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1882   // EH_RETURN nodes, so that instructions are emitted back-to-back.
1883   unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1884   unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1885   Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1886   Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1887   return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1888                      DAG.getRegister(OffsetReg, Ty),
1889                      DAG.getRegister(AddrReg, getPointerTy()),
1890                      Chain.getValue(1));
1891 }
1892
1893 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1894                                               SelectionDAG &DAG) const {
1895   // FIXME: Need pseudo-fence for 'singlethread' fences
1896   // FIXME: Set SType for weaker fences where supported/appropriate.
1897   unsigned SType = 0;
1898   SDLoc DL(Op);
1899   return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1900                      DAG.getConstant(SType, MVT::i32));
1901 }
1902
1903 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1904                                                 SelectionDAG &DAG) const {
1905   SDLoc DL(Op);
1906   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1907   SDValue Shamt = Op.getOperand(2);
1908
1909   // if shamt < 32:
1910   //  lo = (shl lo, shamt)
1911   //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1912   // else:
1913   //  lo = 0
1914   //  hi = (shl lo, shamt[4:0])
1915   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1916                             DAG.getConstant(-1, MVT::i32));
1917   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1918                                       DAG.getConstant(1, MVT::i32));
1919   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1920                                      Not);
1921   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1922   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1923   SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1924   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1925                              DAG.getConstant(0x20, MVT::i32));
1926   Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1927                    DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1928   Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1929
1930   SDValue Ops[2] = {Lo, Hi};
1931   return DAG.getMergeValues(Ops, 2, DL);
1932 }
1933
1934 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1935                                                  bool IsSRA) const {
1936   SDLoc DL(Op);
1937   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1938   SDValue Shamt = Op.getOperand(2);
1939
1940   // if shamt < 32:
1941   //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1942   //  if isSRA:
1943   //    hi = (sra hi, shamt)
1944   //  else:
1945   //    hi = (srl hi, shamt)
1946   // else:
1947   //  if isSRA:
1948   //   lo = (sra hi, shamt[4:0])
1949   //   hi = (sra hi, 31)
1950   //  else:
1951   //   lo = (srl hi, shamt[4:0])
1952   //   hi = 0
1953   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1954                             DAG.getConstant(-1, MVT::i32));
1955   SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1956                                      DAG.getConstant(1, MVT::i32));
1957   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1958   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1959   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1960   SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1961                                      Hi, Shamt);
1962   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1963                              DAG.getConstant(0x20, MVT::i32));
1964   SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1965                                 DAG.getConstant(31, MVT::i32));
1966   Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1967   Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1968                    IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1969                    ShiftRightHi);
1970
1971   SDValue Ops[2] = {Lo, Hi};
1972   return DAG.getMergeValues(Ops, 2, DL);
1973 }
1974
1975 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1976                             SDValue Chain, SDValue Src, unsigned Offset) {
1977   SDValue Ptr = LD->getBasePtr();
1978   EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1979   EVT BasePtrVT = Ptr.getValueType();
1980   SDLoc DL(LD);
1981   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1982
1983   if (Offset)
1984     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1985                       DAG.getConstant(Offset, BasePtrVT));
1986
1987   SDValue Ops[] = { Chain, Ptr, Src };
1988   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1989                                  LD->getMemOperand());
1990 }
1991
1992 // Expand an unaligned 32 or 64-bit integer load node.
1993 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1994   LoadSDNode *LD = cast<LoadSDNode>(Op);
1995   EVT MemVT = LD->getMemoryVT();
1996
1997   // Return if load is aligned or if MemVT is neither i32 nor i64.
1998   if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1999       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2000     return SDValue();
2001
2002   bool IsLittle = Subtarget->isLittle();
2003   EVT VT = Op.getValueType();
2004   ISD::LoadExtType ExtType = LD->getExtensionType();
2005   SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2006
2007   assert((VT == MVT::i32) || (VT == MVT::i64));
2008
2009   // Expand
2010   //  (set dst, (i64 (load baseptr)))
2011   // to
2012   //  (set tmp, (ldl (add baseptr, 7), undef))
2013   //  (set dst, (ldr baseptr, tmp))
2014   if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2015     SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2016                                IsLittle ? 7 : 0);
2017     return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2018                         IsLittle ? 0 : 7);
2019   }
2020
2021   SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2022                              IsLittle ? 3 : 0);
2023   SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2024                              IsLittle ? 0 : 3);
2025
2026   // Expand
2027   //  (set dst, (i32 (load baseptr))) or
2028   //  (set dst, (i64 (sextload baseptr))) or
2029   //  (set dst, (i64 (extload baseptr)))
2030   // to
2031   //  (set tmp, (lwl (add baseptr, 3), undef))
2032   //  (set dst, (lwr baseptr, tmp))
2033   if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2034       (ExtType == ISD::EXTLOAD))
2035     return LWR;
2036
2037   assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2038
2039   // Expand
2040   //  (set dst, (i64 (zextload baseptr)))
2041   // to
2042   //  (set tmp0, (lwl (add baseptr, 3), undef))
2043   //  (set tmp1, (lwr baseptr, tmp0))
2044   //  (set tmp2, (shl tmp1, 32))
2045   //  (set dst, (srl tmp2, 32))
2046   SDLoc DL(LD);
2047   SDValue Const32 = DAG.getConstant(32, MVT::i32);
2048   SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2049   SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2050   SDValue Ops[] = { SRL, LWR.getValue(1) };
2051   return DAG.getMergeValues(Ops, 2, DL);
2052 }
2053
2054 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2055                              SDValue Chain, unsigned Offset) {
2056   SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2057   EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2058   SDLoc DL(SD);
2059   SDVTList VTList = DAG.getVTList(MVT::Other);
2060
2061   if (Offset)
2062     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2063                       DAG.getConstant(Offset, BasePtrVT));
2064
2065   SDValue Ops[] = { Chain, Value, Ptr };
2066   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2067                                  SD->getMemOperand());
2068 }
2069
2070 // Expand an unaligned 32 or 64-bit integer store node.
2071 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2072                                       bool IsLittle) {
2073   SDValue Value = SD->getValue(), Chain = SD->getChain();
2074   EVT VT = Value.getValueType();
2075
2076   // Expand
2077   //  (store val, baseptr) or
2078   //  (truncstore val, baseptr)
2079   // to
2080   //  (swl val, (add baseptr, 3))
2081   //  (swr val, baseptr)
2082   if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2083     SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2084                                 IsLittle ? 3 : 0);
2085     return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2086   }
2087
2088   assert(VT == MVT::i64);
2089
2090   // Expand
2091   //  (store val, baseptr)
2092   // to
2093   //  (sdl val, (add baseptr, 7))
2094   //  (sdr val, baseptr)
2095   SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2096   return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2097 }
2098
2099 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2100 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2101   SDValue Val = SD->getValue();
2102
2103   if (Val.getOpcode() != ISD::FP_TO_SINT)
2104     return SDValue();
2105
2106   EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2107   SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2108                            Val.getOperand(0));
2109
2110   return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2111                       SD->getPointerInfo(), SD->isVolatile(),
2112                       SD->isNonTemporal(), SD->getAlignment());
2113 }
2114
2115 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2116   StoreSDNode *SD = cast<StoreSDNode>(Op);
2117   EVT MemVT = SD->getMemoryVT();
2118
2119   // Lower unaligned integer stores.
2120   if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2121       ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2122     return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2123
2124   return lowerFP_TO_SINT_STORE(SD, DAG);
2125 }
2126
2127 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2128   if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2129       || cast<ConstantSDNode>
2130         (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2131       || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2132     return SDValue();
2133
2134   // The pattern
2135   //   (add (frameaddr 0), (frame_to_args_offset))
2136   // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2137   //   (add FrameObject, 0)
2138   // where FrameObject is a fixed StackObject with offset 0 which points to
2139   // the old stack pointer.
2140   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2141   EVT ValTy = Op->getValueType(0);
2142   int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2143   SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2144   return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2145                      DAG.getConstant(0, ValTy));
2146 }
2147
2148 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2149                                             SelectionDAG &DAG) const {
2150   EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2151   SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2152                               Op.getOperand(0));
2153   return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2154 }
2155
2156 //===----------------------------------------------------------------------===//
2157 //                      Calling Convention Implementation
2158 //===----------------------------------------------------------------------===//
2159
2160 //===----------------------------------------------------------------------===//
2161 // TODO: Implement a generic logic using tblgen that can support this.
2162 // Mips O32 ABI rules:
2163 // ---
2164 // i32 - Passed in A0, A1, A2, A3 and stack
2165 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2166 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
2167 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2168 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2169 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
2170 //       go to stack.
2171 //
2172 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2173 //===----------------------------------------------------------------------===//
2174
2175 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2176                        MVT LocVT, CCValAssign::LocInfo LocInfo,
2177                        ISD::ArgFlagsTy ArgFlags, CCState &State,
2178                        const uint16_t *F64Regs) {
2179
2180   static const unsigned IntRegsSize=4, FloatRegsSize=2;
2181
2182   static const uint16_t IntRegs[] = {
2183       Mips::A0, Mips::A1, Mips::A2, Mips::A3
2184   };
2185   static const uint16_t F32Regs[] = {
2186       Mips::F12, Mips::F14
2187   };
2188
2189   // Do not process byval args here.
2190   if (ArgFlags.isByVal())
2191     return true;
2192
2193   // Promote i8 and i16
2194   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2195     LocVT = MVT::i32;
2196     if (ArgFlags.isSExt())
2197       LocInfo = CCValAssign::SExt;
2198     else if (ArgFlags.isZExt())
2199       LocInfo = CCValAssign::ZExt;
2200     else
2201       LocInfo = CCValAssign::AExt;
2202   }
2203
2204   unsigned Reg;
2205
2206   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2207   // is true: function is vararg, argument is 3rd or higher, there is previous
2208   // argument which is not f32 or f64.
2209   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2210       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2211   unsigned OrigAlign = ArgFlags.getOrigAlign();
2212   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2213
2214   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2215     Reg = State.AllocateReg(IntRegs, IntRegsSize);
2216     // If this is the first part of an i64 arg,
2217     // the allocated register must be either A0 or A2.
2218     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2219       Reg = State.AllocateReg(IntRegs, IntRegsSize);
2220     LocVT = MVT::i32;
2221   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2222     // Allocate int register and shadow next int register. If first
2223     // available register is Mips::A1 or Mips::A3, shadow it too.
2224     Reg = State.AllocateReg(IntRegs, IntRegsSize);
2225     if (Reg == Mips::A1 || Reg == Mips::A3)
2226       Reg = State.AllocateReg(IntRegs, IntRegsSize);
2227     State.AllocateReg(IntRegs, IntRegsSize);
2228     LocVT = MVT::i32;
2229   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2230     // we are guaranteed to find an available float register
2231     if (ValVT == MVT::f32) {
2232       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2233       // Shadow int register
2234       State.AllocateReg(IntRegs, IntRegsSize);
2235     } else {
2236       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2237       // Shadow int registers
2238       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2239       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2240         State.AllocateReg(IntRegs, IntRegsSize);
2241       State.AllocateReg(IntRegs, IntRegsSize);
2242     }
2243   } else
2244     llvm_unreachable("Cannot handle this ValVT.");
2245
2246   if (!Reg) {
2247     unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2248                                           OrigAlign);
2249     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2250   } else
2251     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2252
2253   return false;
2254 }
2255
2256 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2257                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2258                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2259   static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2260
2261   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2262 }
2263
2264 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2265                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2266                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2267   static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D12_64 };
2268
2269   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2270 }
2271
2272 #include "MipsGenCallingConv.inc"
2273
2274 //===----------------------------------------------------------------------===//
2275 //                  Call Calling Convention Implementation
2276 //===----------------------------------------------------------------------===//
2277
2278 // Return next O32 integer argument register.
2279 static unsigned getNextIntArgReg(unsigned Reg) {
2280   assert((Reg == Mips::A0) || (Reg == Mips::A2));
2281   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2282 }
2283
2284 SDValue
2285 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2286                                    SDValue Chain, SDValue Arg, SDLoc DL,
2287                                    bool IsTailCall, SelectionDAG &DAG) const {
2288   if (!IsTailCall) {
2289     SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2290                                  DAG.getIntPtrConstant(Offset));
2291     return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2292                         false, 0);
2293   }
2294
2295   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2296   int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2297   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2298   return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2299                       /*isVolatile=*/ true, false, 0);
2300 }
2301
2302 void MipsTargetLowering::
2303 getOpndList(SmallVectorImpl<SDValue> &Ops,
2304             std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2305             bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2306             CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2307   // Insert node "GP copy globalreg" before call to function.
2308   //
2309   // R_MIPS_CALL* operators (emitted when non-internal functions are called
2310   // in PIC mode) allow symbols to be resolved via lazy binding.
2311   // The lazy binding stub requires GP to point to the GOT.
2312   if (IsPICCall && !InternalLinkage) {
2313     unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2314     EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2315     RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2316   }
2317
2318   // Build a sequence of copy-to-reg nodes chained together with token
2319   // chain and flag operands which copy the outgoing args into registers.
2320   // The InFlag in necessary since all emitted instructions must be
2321   // stuck together.
2322   SDValue InFlag;
2323
2324   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2325     Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2326                                  RegsToPass[i].second, InFlag);
2327     InFlag = Chain.getValue(1);
2328   }
2329
2330   // Add argument registers to the end of the list so that they are
2331   // known live into the call.
2332   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2333     Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2334                                       RegsToPass[i].second.getValueType()));
2335
2336   // Add a register mask operand representing the call-preserved registers.
2337   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2338   const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2339   assert(Mask && "Missing call preserved mask for calling convention");
2340   if (Subtarget->inMips16HardFloat()) {
2341     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2342       llvm::StringRef Sym = G->getGlobal()->getName();
2343       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2344       if (F->hasFnAttribute("__Mips16RetHelper")) {
2345         Mask = MipsRegisterInfo::getMips16RetHelperMask();
2346       }
2347     }
2348   }
2349   Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2350
2351   if (InFlag.getNode())
2352     Ops.push_back(InFlag);
2353 }
2354
2355 /// LowerCall - functions arguments are copied from virtual regs to
2356 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2357 SDValue
2358 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2359                               SmallVectorImpl<SDValue> &InVals) const {
2360   SelectionDAG &DAG                     = CLI.DAG;
2361   SDLoc DL                              = CLI.DL;
2362   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2363   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2364   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2365   SDValue Chain                         = CLI.Chain;
2366   SDValue Callee                        = CLI.Callee;
2367   bool &IsTailCall                      = CLI.IsTailCall;
2368   CallingConv::ID CallConv              = CLI.CallConv;
2369   bool IsVarArg                         = CLI.IsVarArg;
2370
2371   MachineFunction &MF = DAG.getMachineFunction();
2372   MachineFrameInfo *MFI = MF.getFrameInfo();
2373   const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2374   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2375
2376   // Analyze operands of the call, assigning locations to each operand.
2377   SmallVector<CCValAssign, 16> ArgLocs;
2378   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2379                  getTargetMachine(), ArgLocs, *DAG.getContext());
2380   MipsCC::SpecialCallingConvType SpecialCallingConv =
2381     getSpecialCallingConv(Callee);
2382   MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2383                     SpecialCallingConv);
2384
2385   MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2386                                  Subtarget->mipsSEUsesSoftFloat(),
2387                                  Callee.getNode(), CLI.Args);
2388
2389   // Get a count of how many bytes are to be pushed on the stack.
2390   unsigned NextStackOffset = CCInfo.getNextStackOffset();
2391
2392   // Check if it's really possible to do a tail call.
2393   if (IsTailCall)
2394     IsTailCall =
2395       isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2396                                         *MF.getInfo<MipsFunctionInfo>());
2397
2398   if (IsTailCall)
2399     ++NumTailCalls;
2400
2401   // Chain is the output chain of the last Load/Store or CopyToReg node.
2402   // ByValChain is the output chain of the last Memcpy node created for copying
2403   // byval arguments to the stack.
2404   unsigned StackAlignment = TFL->getStackAlignment();
2405   NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2406   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2407
2408   if (!IsTailCall)
2409     Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2410
2411   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2412                                         IsN64 ? Mips::SP_64 : Mips::SP,
2413                                         getPointerTy());
2414
2415   // With EABI is it possible to have 16 args on registers.
2416   std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2417   SmallVector<SDValue, 8> MemOpChains;
2418   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2419
2420   // Walk the register/memloc assignments, inserting copies/loads.
2421   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2422     SDValue Arg = OutVals[i];
2423     CCValAssign &VA = ArgLocs[i];
2424     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2425     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2426
2427     // ByVal Arg.
2428     if (Flags.isByVal()) {
2429       assert(Flags.getByValSize() &&
2430              "ByVal args of size 0 should have been ignored by front-end.");
2431       assert(ByValArg != MipsCCInfo.byval_end());
2432       assert(!IsTailCall &&
2433              "Do not tail-call optimize if there is a byval argument.");
2434       passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2435                    MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2436       ++ByValArg;
2437       continue;
2438     }
2439
2440     // Promote the value if needed.
2441     switch (VA.getLocInfo()) {
2442     default: llvm_unreachable("Unknown loc info!");
2443     case CCValAssign::Full:
2444       if (VA.isRegLoc()) {
2445         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2446             (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2447             (ValVT == MVT::i64 && LocVT == MVT::f64))
2448           Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2449         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2450           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2451                                    Arg, DAG.getConstant(0, MVT::i32));
2452           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2453                                    Arg, DAG.getConstant(1, MVT::i32));
2454           if (!Subtarget->isLittle())
2455             std::swap(Lo, Hi);
2456           unsigned LocRegLo = VA.getLocReg();
2457           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2458           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2459           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2460           continue;
2461         }
2462       }
2463       break;
2464     case CCValAssign::SExt:
2465       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2466       break;
2467     case CCValAssign::ZExt:
2468       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2469       break;
2470     case CCValAssign::AExt:
2471       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2472       break;
2473     }
2474
2475     // Arguments that can be passed on register must be kept at
2476     // RegsToPass vector
2477     if (VA.isRegLoc()) {
2478       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2479       continue;
2480     }
2481
2482     // Register can't get to this point...
2483     assert(VA.isMemLoc());
2484
2485     // emit ISD::STORE whichs stores the
2486     // parameter value to a stack Location
2487     MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2488                                          Chain, Arg, DL, IsTailCall, DAG));
2489   }
2490
2491   // Transform all store nodes into one single node because all store
2492   // nodes are independent of each other.
2493   if (!MemOpChains.empty())
2494     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2495                         &MemOpChains[0], MemOpChains.size());
2496
2497   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2498   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2499   // node so that legalize doesn't hack it.
2500   bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2501   bool GlobalOrExternal = false, InternalLinkage = false;
2502   SDValue CalleeLo;
2503   EVT Ty = Callee.getValueType();
2504
2505   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2506     if (IsPICCall) {
2507       InternalLinkage = G->getGlobal()->hasInternalLinkage();
2508
2509       if (InternalLinkage)
2510         Callee = getAddrLocal(G, Ty, DAG, HasMips64);
2511       else if (LargeGOT)
2512         Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2513                                        MipsII::MO_CALL_LO16);
2514       else
2515         Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL);
2516     } else
2517       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2518                                           MipsII::MO_NO_FLAG);
2519     GlobalOrExternal = true;
2520   }
2521   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2522     if (!IsN64 && !IsPIC) // !N64 && static
2523       Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2524                                             MipsII::MO_NO_FLAG);
2525     else if (LargeGOT)
2526       Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2527                                      MipsII::MO_CALL_LO16);
2528     else // N64 || PIC
2529       Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL);
2530
2531     GlobalOrExternal = true;
2532   }
2533
2534   SmallVector<SDValue, 8> Ops(1, Chain);
2535   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2536
2537   getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2538               CLI, Callee, Chain);
2539
2540   if (IsTailCall)
2541     return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2542
2543   Chain  = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2544   SDValue InFlag = Chain.getValue(1);
2545
2546   // Create the CALLSEQ_END node.
2547   Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2548                              DAG.getIntPtrConstant(0, true), InFlag, DL);
2549   InFlag = Chain.getValue(1);
2550
2551   // Handle result values, copying them out of physregs into vregs that we
2552   // return.
2553   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2554                          Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2555 }
2556
2557 /// LowerCallResult - Lower the result values of a call into the
2558 /// appropriate copies out of appropriate physical registers.
2559 SDValue
2560 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2561                                     CallingConv::ID CallConv, bool IsVarArg,
2562                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2563                                     SDLoc DL, SelectionDAG &DAG,
2564                                     SmallVectorImpl<SDValue> &InVals,
2565                                     const SDNode *CallNode,
2566                                     const Type *RetTy) const {
2567   // Assign locations to each value returned by this call.
2568   SmallVector<CCValAssign, 16> RVLocs;
2569   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2570                  getTargetMachine(), RVLocs, *DAG.getContext());
2571   MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2572
2573   MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2574                                CallNode, RetTy);
2575
2576   // Copy all of the result registers out of their specified physreg.
2577   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2578     SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2579                                      RVLocs[i].getLocVT(), InFlag);
2580     Chain = Val.getValue(1);
2581     InFlag = Val.getValue(2);
2582
2583     if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2584       Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2585
2586     InVals.push_back(Val);
2587   }
2588
2589   return Chain;
2590 }
2591
2592 //===----------------------------------------------------------------------===//
2593 //             Formal Arguments Calling Convention Implementation
2594 //===----------------------------------------------------------------------===//
2595 /// LowerFormalArguments - transform physical registers into virtual registers
2596 /// and generate load operations for arguments places on the stack.
2597 SDValue
2598 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2599                                          CallingConv::ID CallConv,
2600                                          bool IsVarArg,
2601                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2602                                          SDLoc DL, SelectionDAG &DAG,
2603                                          SmallVectorImpl<SDValue> &InVals)
2604                                           const {
2605   MachineFunction &MF = DAG.getMachineFunction();
2606   MachineFrameInfo *MFI = MF.getFrameInfo();
2607   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2608
2609   MipsFI->setVarArgsFrameIndex(0);
2610
2611   // Used with vargs to acumulate store chains.
2612   std::vector<SDValue> OutChains;
2613
2614   // Assign locations to all of the incoming arguments.
2615   SmallVector<CCValAssign, 16> ArgLocs;
2616   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2617                  getTargetMachine(), ArgLocs, *DAG.getContext());
2618   MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2619   Function::const_arg_iterator FuncArg =
2620     DAG.getMachineFunction().getFunction()->arg_begin();
2621   bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2622
2623   MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2624   MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2625                            MipsCCInfo.hasByValArg());
2626
2627   unsigned CurArgIdx = 0;
2628   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2629
2630   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2631     CCValAssign &VA = ArgLocs[i];
2632     std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2633     CurArgIdx = Ins[i].OrigArgIndex;
2634     EVT ValVT = VA.getValVT();
2635     ISD::ArgFlagsTy Flags = Ins[i].Flags;
2636     bool IsRegLoc = VA.isRegLoc();
2637
2638     if (Flags.isByVal()) {
2639       assert(Flags.getByValSize() &&
2640              "ByVal args of size 0 should have been ignored by front-end.");
2641       assert(ByValArg != MipsCCInfo.byval_end());
2642       copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2643                     MipsCCInfo, *ByValArg);
2644       ++ByValArg;
2645       continue;
2646     }
2647
2648     // Arguments stored on registers
2649     if (IsRegLoc) {
2650       EVT RegVT = VA.getLocVT();
2651       unsigned ArgReg = VA.getLocReg();
2652       const TargetRegisterClass *RC;
2653
2654       if (RegVT == MVT::i32)
2655         RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2656                                         &Mips::GPR32RegClass;
2657       else if (RegVT == MVT::i64)
2658         RC = &Mips::GPR64RegClass;
2659       else if (RegVT == MVT::f32)
2660         RC = &Mips::FGR32RegClass;
2661       else if (RegVT == MVT::f64)
2662         RC = Subtarget->isFP64bit() ? &Mips::FGR64RegClass :
2663                                       &Mips::AFGR64RegClass;
2664       else
2665         llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2666
2667       // Transform the arguments stored on
2668       // physical registers into virtual ones
2669       unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2670       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2671
2672       // If this is an 8 or 16-bit value, it has been passed promoted
2673       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2674       // truncate to the right size.
2675       if (VA.getLocInfo() != CCValAssign::Full) {
2676         unsigned Opcode = 0;
2677         if (VA.getLocInfo() == CCValAssign::SExt)
2678           Opcode = ISD::AssertSext;
2679         else if (VA.getLocInfo() == CCValAssign::ZExt)
2680           Opcode = ISD::AssertZext;
2681         if (Opcode)
2682           ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2683                                  DAG.getValueType(ValVT));
2684         ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2685       }
2686
2687       // Handle floating point arguments passed in integer registers and
2688       // long double arguments passed in floating point registers.
2689       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2690           (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2691           (RegVT == MVT::f64 && ValVT == MVT::i64))
2692         ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2693       else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2694         unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2695                                   getNextIntArgReg(ArgReg), RC);
2696         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2697         if (!Subtarget->isLittle())
2698           std::swap(ArgValue, ArgValue2);
2699         ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2700                                ArgValue, ArgValue2);
2701       }
2702
2703       InVals.push_back(ArgValue);
2704     } else { // VA.isRegLoc()
2705
2706       // sanity check
2707       assert(VA.isMemLoc());
2708
2709       // The stack pointer offset is relative to the caller stack frame.
2710       int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2711                                       VA.getLocMemOffset(), true);
2712
2713       // Create load nodes to retrieve arguments from the stack
2714       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2715       InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2716                                    MachinePointerInfo::getFixedStack(FI),
2717                                    false, false, false, 0));
2718     }
2719   }
2720
2721   // The mips ABIs for returning structs by value requires that we copy
2722   // the sret argument into $v0 for the return. Save the argument into
2723   // a virtual register so that we can access it from the return points.
2724   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2725     unsigned Reg = MipsFI->getSRetReturnReg();
2726     if (!Reg) {
2727       Reg = MF.getRegInfo().
2728         createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2729       MipsFI->setSRetReturnReg(Reg);
2730     }
2731     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2732     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2733   }
2734
2735   if (IsVarArg)
2736     writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2737
2738   // All stores are grouped in one node to allow the matching between
2739   // the size of Ins and InVals. This only happens when on varg functions
2740   if (!OutChains.empty()) {
2741     OutChains.push_back(Chain);
2742     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2743                         &OutChains[0], OutChains.size());
2744   }
2745
2746   return Chain;
2747 }
2748
2749 //===----------------------------------------------------------------------===//
2750 //               Return Value Calling Convention Implementation
2751 //===----------------------------------------------------------------------===//
2752
2753 bool
2754 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2755                                    MachineFunction &MF, bool IsVarArg,
2756                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2757                                    LLVMContext &Context) const {
2758   SmallVector<CCValAssign, 16> RVLocs;
2759   CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2760                  RVLocs, Context);
2761   return CCInfo.CheckReturn(Outs, RetCC_Mips);
2762 }
2763
2764 SDValue
2765 MipsTargetLowering::LowerReturn(SDValue Chain,
2766                                 CallingConv::ID CallConv, bool IsVarArg,
2767                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
2768                                 const SmallVectorImpl<SDValue> &OutVals,
2769                                 SDLoc DL, SelectionDAG &DAG) const {
2770   // CCValAssign - represent the assignment of
2771   // the return value to a location
2772   SmallVector<CCValAssign, 16> RVLocs;
2773   MachineFunction &MF = DAG.getMachineFunction();
2774
2775   // CCState - Info about the registers and stack slot.
2776   CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2777                  *DAG.getContext());
2778   MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2779
2780   // Analyze return values.
2781   MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2782                            MF.getFunction()->getReturnType());
2783
2784   SDValue Flag;
2785   SmallVector<SDValue, 4> RetOps(1, Chain);
2786
2787   // Copy the result values into the output registers.
2788   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2789     SDValue Val = OutVals[i];
2790     CCValAssign &VA = RVLocs[i];
2791     assert(VA.isRegLoc() && "Can only return in registers!");
2792
2793     if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2794       Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2795
2796     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2797
2798     // Guarantee that all emitted copies are stuck together with flags.
2799     Flag = Chain.getValue(1);
2800     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2801   }
2802
2803   // The mips ABIs for returning structs by value requires that we copy
2804   // the sret argument into $v0 for the return. We saved the argument into
2805   // a virtual register in the entry block, so now we copy the value out
2806   // and into $v0.
2807   if (MF.getFunction()->hasStructRetAttr()) {
2808     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2809     unsigned Reg = MipsFI->getSRetReturnReg();
2810
2811     if (!Reg)
2812       llvm_unreachable("sret virtual register not created in the entry block");
2813     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2814     unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2815
2816     Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2817     Flag = Chain.getValue(1);
2818     RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2819   }
2820
2821   RetOps[0] = Chain;  // Update chain.
2822
2823   // Add the flag if we have it.
2824   if (Flag.getNode())
2825     RetOps.push_back(Flag);
2826
2827   // Return on Mips is always a "jr $ra"
2828   return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2829 }
2830
2831 //===----------------------------------------------------------------------===//
2832 //                           Mips Inline Assembly Support
2833 //===----------------------------------------------------------------------===//
2834
2835 /// getConstraintType - Given a constraint letter, return the type of
2836 /// constraint it is for this target.
2837 MipsTargetLowering::ConstraintType MipsTargetLowering::
2838 getConstraintType(const std::string &Constraint) const
2839 {
2840   // Mips specific constrainy
2841   // GCC config/mips/constraints.md
2842   //
2843   // 'd' : An address register. Equivalent to r
2844   //       unless generating MIPS16 code.
2845   // 'y' : Equivalent to r; retained for
2846   //       backwards compatibility.
2847   // 'c' : A register suitable for use in an indirect
2848   //       jump. This will always be $25 for -mabicalls.
2849   // 'l' : The lo register. 1 word storage.
2850   // 'x' : The hilo register pair. Double word storage.
2851   if (Constraint.size() == 1) {
2852     switch (Constraint[0]) {
2853       default : break;
2854       case 'd':
2855       case 'y':
2856       case 'f':
2857       case 'c':
2858       case 'l':
2859       case 'x':
2860         return C_RegisterClass;
2861       case 'R':
2862         return C_Memory;
2863     }
2864   }
2865   return TargetLowering::getConstraintType(Constraint);
2866 }
2867
2868 /// Examine constraint type and operand type and determine a weight value.
2869 /// This object must already have been set up with the operand type
2870 /// and the current alternative constraint selected.
2871 TargetLowering::ConstraintWeight
2872 MipsTargetLowering::getSingleConstraintMatchWeight(
2873     AsmOperandInfo &info, const char *constraint) const {
2874   ConstraintWeight weight = CW_Invalid;
2875   Value *CallOperandVal = info.CallOperandVal;
2876     // If we don't have a value, we can't do a match,
2877     // but allow it at the lowest weight.
2878   if (CallOperandVal == NULL)
2879     return CW_Default;
2880   Type *type = CallOperandVal->getType();
2881   // Look at the constraint type.
2882   switch (*constraint) {
2883   default:
2884     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2885     break;
2886   case 'd':
2887   case 'y':
2888     if (type->isIntegerTy())
2889       weight = CW_Register;
2890     break;
2891   case 'f':
2892     if (type->isFloatTy())
2893       weight = CW_Register;
2894     break;
2895   case 'c': // $25 for indirect jumps
2896   case 'l': // lo register
2897   case 'x': // hilo register pair
2898       if (type->isIntegerTy())
2899       weight = CW_SpecificReg;
2900       break;
2901   case 'I': // signed 16 bit immediate
2902   case 'J': // integer zero
2903   case 'K': // unsigned 16 bit immediate
2904   case 'L': // signed 32 bit immediate where lower 16 bits are 0
2905   case 'N': // immediate in the range of -65535 to -1 (inclusive)
2906   case 'O': // signed 15 bit immediate (+- 16383)
2907   case 'P': // immediate in the range of 65535 to 1 (inclusive)
2908     if (isa<ConstantInt>(CallOperandVal))
2909       weight = CW_Constant;
2910     break;
2911   case 'R':
2912     weight = CW_Memory;
2913     break;
2914   }
2915   return weight;
2916 }
2917
2918 /// This is a helper function to parse a physical register string and split it
2919 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2920 /// that is returned indicates whether parsing was successful. The second flag
2921 /// is true if the numeric part exists.
2922 static std::pair<bool, bool>
2923 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2924                  unsigned long long &Reg) {
2925   if (C.front() != '{' || C.back() != '}')
2926     return std::make_pair(false, false);
2927
2928   // Search for the first numeric character.
2929   StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2930   I = std::find_if(B, E, std::ptr_fun(isdigit));
2931
2932   Prefix.assign(B, I - B);
2933
2934   // The second flag is set to false if no numeric characters were found.
2935   if (I == E)
2936     return std::make_pair(true, false);
2937
2938   // Parse the numeric characters.
2939   return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2940                         true);
2941 }
2942
2943 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2944 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2945   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2946   const TargetRegisterClass *RC;
2947   std::string Prefix;
2948   unsigned long long Reg;
2949
2950   std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2951
2952   if (!R.first)
2953     return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2954
2955   if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2956     // No numeric characters follow "hi" or "lo".
2957     if (R.second)
2958       return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2959
2960     RC = TRI->getRegClass(Prefix == "hi" ?
2961                           Mips::HI32RegClassID : Mips::LO32RegClassID);
2962     return std::make_pair(*(RC->begin()), RC);
2963   }
2964
2965   if (!R.second)
2966     return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2967
2968   if (Prefix == "$f") { // Parse $f0-$f31.
2969     // If the size of FP registers is 64-bit or Reg is an even number, select
2970     // the 64-bit register class. Otherwise, select the 32-bit register class.
2971     if (VT == MVT::Other)
2972       VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2973
2974     RC= getRegClassFor(VT);
2975
2976     if (RC == &Mips::AFGR64RegClass) {
2977       assert(Reg % 2 == 0);
2978       Reg >>= 1;
2979     }
2980   } else if (Prefix == "$fcc") { // Parse $fcc0-$fcc7.
2981     RC = TRI->getRegClass(Mips::FCCRegClassID);
2982   } else { // Parse $0-$31.
2983     assert(Prefix == "$");
2984     RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2985   }
2986
2987   assert(Reg < RC->getNumRegs());
2988   return std::make_pair(*(RC->begin() + Reg), RC);
2989 }
2990
2991 /// Given a register class constraint, like 'r', if this corresponds directly
2992 /// to an LLVM register class, return a register of 0 and the register class
2993 /// pointer.
2994 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2995 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2996 {
2997   if (Constraint.size() == 1) {
2998     switch (Constraint[0]) {
2999     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3000     case 'y': // Same as 'r'. Exists for compatibility.
3001     case 'r':
3002       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3003         if (Subtarget->inMips16Mode())
3004           return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3005         return std::make_pair(0U, &Mips::GPR32RegClass);
3006       }
3007       if (VT == MVT::i64 && !HasMips64)
3008         return std::make_pair(0U, &Mips::GPR32RegClass);
3009       if (VT == MVT::i64 && HasMips64)
3010         return std::make_pair(0U, &Mips::GPR64RegClass);
3011       // This will generate an error message
3012       return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3013     case 'f':
3014       if (VT == MVT::f32)
3015         return std::make_pair(0U, &Mips::FGR32RegClass);
3016       if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3017         if (Subtarget->isFP64bit())
3018           return std::make_pair(0U, &Mips::FGR64RegClass);
3019         return std::make_pair(0U, &Mips::AFGR64RegClass);
3020       }
3021       break;
3022     case 'c': // register suitable for indirect jump
3023       if (VT == MVT::i32)
3024         return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3025       assert(VT == MVT::i64 && "Unexpected type.");
3026       return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3027     case 'l': // register suitable for indirect jump
3028       if (VT == MVT::i32)
3029         return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3030       return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3031     case 'x': // register suitable for indirect jump
3032       // Fixme: Not triggering the use of both hi and low
3033       // This will generate an error message
3034       return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3035     }
3036   }
3037
3038   std::pair<unsigned, const TargetRegisterClass *> R;
3039   R = parseRegForInlineAsmConstraint(Constraint, VT);
3040
3041   if (R.second)
3042     return R;
3043
3044   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3045 }
3046
3047 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3048 /// vector.  If it is invalid, don't add anything to Ops.
3049 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3050                                                      std::string &Constraint,
3051                                                      std::vector<SDValue>&Ops,
3052                                                      SelectionDAG &DAG) const {
3053   SDValue Result(0, 0);
3054
3055   // Only support length 1 constraints for now.
3056   if (Constraint.length() > 1) return;
3057
3058   char ConstraintLetter = Constraint[0];
3059   switch (ConstraintLetter) {
3060   default: break; // This will fall through to the generic implementation
3061   case 'I': // Signed 16 bit constant
3062     // If this fails, the parent routine will give an error
3063     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3064       EVT Type = Op.getValueType();
3065       int64_t Val = C->getSExtValue();
3066       if (isInt<16>(Val)) {
3067         Result = DAG.getTargetConstant(Val, Type);
3068         break;
3069       }
3070     }
3071     return;
3072   case 'J': // integer zero
3073     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3074       EVT Type = Op.getValueType();
3075       int64_t Val = C->getZExtValue();
3076       if (Val == 0) {
3077         Result = DAG.getTargetConstant(0, Type);
3078         break;
3079       }
3080     }
3081     return;
3082   case 'K': // unsigned 16 bit immediate
3083     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3084       EVT Type = Op.getValueType();
3085       uint64_t Val = (uint64_t)C->getZExtValue();
3086       if (isUInt<16>(Val)) {
3087         Result = DAG.getTargetConstant(Val, Type);
3088         break;
3089       }
3090     }
3091     return;
3092   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3093     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3094       EVT Type = Op.getValueType();
3095       int64_t Val = C->getSExtValue();
3096       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3097         Result = DAG.getTargetConstant(Val, Type);
3098         break;
3099       }
3100     }
3101     return;
3102   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3103     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3104       EVT Type = Op.getValueType();
3105       int64_t Val = C->getSExtValue();
3106       if ((Val >= -65535) && (Val <= -1)) {
3107         Result = DAG.getTargetConstant(Val, Type);
3108         break;
3109       }
3110     }
3111     return;
3112   case 'O': // signed 15 bit immediate
3113     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3114       EVT Type = Op.getValueType();
3115       int64_t Val = C->getSExtValue();
3116       if ((isInt<15>(Val))) {
3117         Result = DAG.getTargetConstant(Val, Type);
3118         break;
3119       }
3120     }
3121     return;
3122   case 'P': // immediate in the range of 1 to 65535 (inclusive)
3123     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3124       EVT Type = Op.getValueType();
3125       int64_t Val = C->getSExtValue();
3126       if ((Val <= 65535) && (Val >= 1)) {
3127         Result = DAG.getTargetConstant(Val, Type);
3128         break;
3129       }
3130     }
3131     return;
3132   }
3133
3134   if (Result.getNode()) {
3135     Ops.push_back(Result);
3136     return;
3137   }
3138
3139   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3140 }
3141
3142 bool
3143 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3144   // No global is ever allowed as a base.
3145   if (AM.BaseGV)
3146     return false;
3147
3148   switch (AM.Scale) {
3149   case 0: // "r+i" or just "i", depending on HasBaseReg.
3150     break;
3151   case 1:
3152     if (!AM.HasBaseReg) // allow "r+i".
3153       break;
3154     return false; // disallow "r+r" or "r+r+i".
3155   default:
3156     return false;
3157   }
3158
3159   return true;
3160 }
3161
3162 bool
3163 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3164   // The Mips target isn't yet aware of offsets.
3165   return false;
3166 }
3167
3168 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3169                                             unsigned SrcAlign,
3170                                             bool IsMemset, bool ZeroMemset,
3171                                             bool MemcpyStrSrc,
3172                                             MachineFunction &MF) const {
3173   if (Subtarget->hasMips64())
3174     return MVT::i64;
3175
3176   return MVT::i32;
3177 }
3178
3179 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3180   if (VT != MVT::f32 && VT != MVT::f64)
3181     return false;
3182   if (Imm.isNegZero())
3183     return false;
3184   return Imm.isZero();
3185 }
3186
3187 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3188   if (IsN64)
3189     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3190
3191   return TargetLowering::getJumpTableEncoding();
3192 }
3193
3194 /// This function returns true if CallSym is a long double emulation routine.
3195 static bool isF128SoftLibCall(const char *CallSym) {
3196   const char *const LibCalls[] =
3197     {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3198      "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3199      "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3200      "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3201      "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3202      "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3203      "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3204      "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3205      "truncl"};
3206
3207   const char * const *End = LibCalls + array_lengthof(LibCalls);
3208
3209   // Check that LibCalls is sorted alphabetically.
3210   MipsTargetLowering::LTStr Comp;
3211
3212 #ifndef NDEBUG
3213   for (const char * const *I = LibCalls; I < End - 1; ++I)
3214     assert(Comp(*I, *(I + 1)));
3215 #endif
3216
3217   return std::binary_search(LibCalls, End, CallSym, Comp);
3218 }
3219
3220 /// This function returns true if Ty is fp128 or i128 which was originally a
3221 /// fp128.
3222 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3223   if (Ty->isFP128Ty())
3224     return true;
3225
3226   const ExternalSymbolSDNode *ES =
3227     dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3228
3229   // If the Ty is i128 and the function being called is a long double emulation
3230   // routine, then the original type is f128.
3231   return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3232 }
3233
3234 MipsTargetLowering::MipsCC::SpecialCallingConvType
3235   MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3236   MipsCC::SpecialCallingConvType SpecialCallingConv =
3237     MipsCC::NoSpecialCallingConv;;
3238   if (Subtarget->inMips16HardFloat()) {
3239     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3240       llvm::StringRef Sym = G->getGlobal()->getName();
3241       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3242       if (F->hasFnAttribute("__Mips16RetHelper")) {
3243         SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3244       }
3245     }
3246   }
3247   return SpecialCallingConv;
3248 }
3249
3250 MipsTargetLowering::MipsCC::MipsCC(
3251   CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3252     MipsCC::SpecialCallingConvType SpecialCallingConv_)
3253   : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3254     SpecialCallingConv(SpecialCallingConv_){
3255   // Pre-allocate reserved argument area.
3256   CCInfo.AllocateStack(reservedArgArea(), 1);
3257 }
3258
3259
3260 void MipsTargetLowering::MipsCC::
3261 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3262                     bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3263                     std::vector<ArgListEntry> &FuncArgs) {
3264   assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3265          "CallingConv::Fast shouldn't be used for vararg functions.");
3266
3267   unsigned NumOpnds = Args.size();
3268   llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3269
3270   for (unsigned I = 0; I != NumOpnds; ++I) {
3271     MVT ArgVT = Args[I].VT;
3272     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3273     bool R;
3274
3275     if (ArgFlags.isByVal()) {
3276       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3277       continue;
3278     }
3279
3280     if (IsVarArg && !Args[I].IsFixed)
3281       R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3282     else {
3283       MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3284                            IsSoftFloat);
3285       R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3286     }
3287
3288     if (R) {
3289 #ifndef NDEBUG
3290       dbgs() << "Call operand #" << I << " has unhandled type "
3291              << EVT(ArgVT).getEVTString();
3292 #endif
3293       llvm_unreachable(0);
3294     }
3295   }
3296 }
3297
3298 void MipsTargetLowering::MipsCC::
3299 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3300                        bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3301   unsigned NumArgs = Args.size();
3302   llvm::CCAssignFn *FixedFn = fixedArgFn();
3303   unsigned CurArgIdx = 0;
3304
3305   for (unsigned I = 0; I != NumArgs; ++I) {
3306     MVT ArgVT = Args[I].VT;
3307     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3308     std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3309     CurArgIdx = Args[I].OrigArgIndex;
3310
3311     if (ArgFlags.isByVal()) {
3312       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3313       continue;
3314     }
3315
3316     MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3317
3318     if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3319       continue;
3320
3321 #ifndef NDEBUG
3322     dbgs() << "Formal Arg #" << I << " has unhandled type "
3323            << EVT(ArgVT).getEVTString();
3324 #endif
3325     llvm_unreachable(0);
3326   }
3327 }
3328
3329 template<typename Ty>
3330 void MipsTargetLowering::MipsCC::
3331 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3332               const SDNode *CallNode, const Type *RetTy) const {
3333   CCAssignFn *Fn;
3334
3335   if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3336     Fn = RetCC_F128Soft;
3337   else
3338     Fn = RetCC_Mips;
3339
3340   for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3341     MVT VT = RetVals[I].VT;
3342     ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3343     MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3344
3345     if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3346 #ifndef NDEBUG
3347       dbgs() << "Call result #" << I << " has unhandled type "
3348              << EVT(VT).getEVTString() << '\n';
3349 #endif
3350       llvm_unreachable(0);
3351     }
3352   }
3353 }
3354
3355 void MipsTargetLowering::MipsCC::
3356 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3357                   const SDNode *CallNode, const Type *RetTy) const {
3358   analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3359 }
3360
3361 void MipsTargetLowering::MipsCC::
3362 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3363               const Type *RetTy) const {
3364   analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3365 }
3366
3367 void
3368 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3369                                            MVT LocVT,
3370                                            CCValAssign::LocInfo LocInfo,
3371                                            ISD::ArgFlagsTy ArgFlags) {
3372   assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3373
3374   struct ByValArgInfo ByVal;
3375   unsigned RegSize = regSize();
3376   unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3377   unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3378                             RegSize * 2);
3379
3380   if (useRegsForByval())
3381     allocateRegs(ByVal, ByValSize, Align);
3382
3383   // Allocate space on caller's stack.
3384   ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3385                                        Align);
3386   CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3387                                     LocInfo));
3388   ByValArgs.push_back(ByVal);
3389 }
3390
3391 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3392   return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3393 }
3394
3395 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3396   return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3397 }
3398
3399 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3400   return IsO32 ? O32IntRegs : Mips64IntRegs;
3401 }
3402
3403 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3404   if (CallConv == CallingConv::Fast)
3405     return CC_Mips_FastCC;
3406
3407   if (SpecialCallingConv == Mips16RetHelperConv)
3408     return CC_Mips16RetHelper;
3409   return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3410 }
3411
3412 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3413   return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3414 }
3415
3416 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3417   return IsO32 ? O32IntRegs : Mips64DPRegs;
3418 }
3419
3420 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3421                                               unsigned ByValSize,
3422                                               unsigned Align) {
3423   unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3424   const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3425   assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3426          "Byval argument's size and alignment should be a multiple of"
3427          "RegSize.");
3428
3429   ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3430
3431   // If Align > RegSize, the first arg register must be even.
3432   if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3433     CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3434     ++ByVal.FirstIdx;
3435   }
3436
3437   // Mark the registers allocated.
3438   for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3439        ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3440     CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3441 }
3442
3443 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3444                                          const SDNode *CallNode,
3445                                          bool IsSoftFloat) const {
3446   if (IsSoftFloat || IsO32)
3447     return VT;
3448
3449   // Check if the original type was fp128.
3450   if (originalTypeIsF128(OrigTy, CallNode)) {
3451     assert(VT == MVT::i64);
3452     return MVT::f64;
3453   }
3454
3455   return VT;
3456 }
3457
3458 void MipsTargetLowering::
3459 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3460               SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3461               SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3462               const MipsCC &CC, const ByValArgInfo &ByVal) const {
3463   MachineFunction &MF = DAG.getMachineFunction();
3464   MachineFrameInfo *MFI = MF.getFrameInfo();
3465   unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3466   unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3467   int FrameObjOffset;
3468
3469   if (RegAreaSize)
3470     FrameObjOffset = (int)CC.reservedArgArea() -
3471       (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3472   else
3473     FrameObjOffset = ByVal.Address;
3474
3475   // Create frame object.
3476   EVT PtrTy = getPointerTy();
3477   int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3478   SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3479   InVals.push_back(FIN);
3480
3481   if (!ByVal.NumRegs)
3482     return;
3483
3484   // Copy arg registers.
3485   MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3486   const TargetRegisterClass *RC = getRegClassFor(RegTy);
3487
3488   for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3489     unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3490     unsigned VReg = addLiveIn(MF, ArgReg, RC);
3491     unsigned Offset = I * CC.regSize();
3492     SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3493                                    DAG.getConstant(Offset, PtrTy));
3494     SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3495                                  StorePtr, MachinePointerInfo(FuncArg, Offset),
3496                                  false, false, 0);
3497     OutChains.push_back(Store);
3498   }
3499 }
3500
3501 // Copy byVal arg to registers and stack.
3502 void MipsTargetLowering::
3503 passByValArg(SDValue Chain, SDLoc DL,
3504              std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3505              SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3506              MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3507              const MipsCC &CC, const ByValArgInfo &ByVal,
3508              const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3509   unsigned ByValSize = Flags.getByValSize();
3510   unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3511   unsigned RegSize = CC.regSize();
3512   unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3513   EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3514
3515   if (ByVal.NumRegs) {
3516     const uint16_t *ArgRegs = CC.intArgRegs();
3517     bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3518     unsigned I = 0;
3519
3520     // Copy words to registers.
3521     for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3522       SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3523                                     DAG.getConstant(Offset, PtrTy));
3524       SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3525                                     MachinePointerInfo(), false, false, false,
3526                                     Alignment);
3527       MemOpChains.push_back(LoadVal.getValue(1));
3528       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3529       RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3530     }
3531
3532     // Return if the struct has been fully copied.
3533     if (ByValSize == Offset)
3534       return;
3535
3536     // Copy the remainder of the byval argument with sub-word loads and shifts.
3537     if (LeftoverBytes) {
3538       assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3539              "Size of the remainder should be smaller than RegSize.");
3540       SDValue Val;
3541
3542       for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3543            Offset < ByValSize; LoadSize /= 2) {
3544         unsigned RemSize = ByValSize - Offset;
3545
3546         if (RemSize < LoadSize)
3547           continue;
3548
3549         // Load subword.
3550         SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3551                                       DAG.getConstant(Offset, PtrTy));
3552         SDValue LoadVal =
3553           DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3554                          MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3555                          false, false, Alignment);
3556         MemOpChains.push_back(LoadVal.getValue(1));
3557
3558         // Shift the loaded value.
3559         unsigned Shamt;
3560
3561         if (isLittle)
3562           Shamt = TotalSizeLoaded;
3563         else
3564           Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3565
3566         SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3567                                     DAG.getConstant(Shamt, MVT::i32));
3568
3569         if (Val.getNode())
3570           Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3571         else
3572           Val = Shift;
3573
3574         Offset += LoadSize;
3575         TotalSizeLoaded += LoadSize;
3576         Alignment = std::min(Alignment, LoadSize);
3577       }
3578
3579       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3580       RegsToPass.push_back(std::make_pair(ArgReg, Val));
3581       return;
3582     }
3583   }
3584
3585   // Copy remainder of byval arg to it with memcpy.
3586   unsigned MemCpySize = ByValSize - Offset;
3587   SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3588                             DAG.getConstant(Offset, PtrTy));
3589   SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3590                             DAG.getIntPtrConstant(ByVal.Address));
3591   Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3592                         DAG.getConstant(MemCpySize, PtrTy), Alignment,
3593                         /*isVolatile=*/false, /*AlwaysInline=*/false,
3594                         MachinePointerInfo(0), MachinePointerInfo(0));
3595   MemOpChains.push_back(Chain);
3596 }
3597
3598 void
3599 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3600                                     const MipsCC &CC, SDValue Chain,
3601                                     SDLoc DL, SelectionDAG &DAG) const {
3602   unsigned NumRegs = CC.numIntArgRegs();
3603   const uint16_t *ArgRegs = CC.intArgRegs();
3604   const CCState &CCInfo = CC.getCCInfo();
3605   unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3606   unsigned RegSize = CC.regSize();
3607   MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3608   const TargetRegisterClass *RC = getRegClassFor(RegTy);
3609   MachineFunction &MF = DAG.getMachineFunction();
3610   MachineFrameInfo *MFI = MF.getFrameInfo();
3611   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3612
3613   // Offset of the first variable argument from stack pointer.
3614   int VaArgOffset;
3615
3616   if (NumRegs == Idx)
3617     VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3618   else
3619     VaArgOffset =
3620       (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3621
3622   // Record the frame index of the first variable argument
3623   // which is a value necessary to VASTART.
3624   int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3625   MipsFI->setVarArgsFrameIndex(FI);
3626
3627   // Copy the integer registers that have not been used for argument passing
3628   // to the argument register save area. For O32, the save area is allocated
3629   // in the caller's stack frame, while for N32/64, it is allocated in the
3630   // callee's stack frame.
3631   for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3632     unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3633     SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3634     FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3635     SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3636     SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3637                                  MachinePointerInfo(), false, false, 0);
3638     cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3639     OutChains.push_back(Store);
3640   }
3641 }