1 //===- MipsISelLowering.cpp - Mips DAG Lowering Implementation ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that Mips uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MipsISelLowering.h"
15 #include "MCTargetDesc/MipsBaseInfo.h"
16 #include "MCTargetDesc/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsMCTargetDesc.h"
18 #include "MipsCCState.h"
19 #include "MipsInstrInfo.h"
20 #include "MipsMachineFunction.h"
21 #include "MipsRegisterInfo.h"
22 #include "MipsSubtarget.h"
23 #include "MipsTargetMachine.h"
24 #include "MipsTargetObjectFile.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/CodeGen/CallingConvLower.h"
32 #include "llvm/CodeGen/FunctionLoweringInfo.h"
33 #include "llvm/CodeGen/ISDOpcodes.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineJumpTableInfo.h"
40 #include "llvm/CodeGen/MachineMemOperand.h"
41 #include "llvm/CodeGen/MachineOperand.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/RuntimeLibcalls.h"
44 #include "llvm/CodeGen/SelectionDAG.h"
45 #include "llvm/CodeGen/SelectionDAGNodes.h"
46 #include "llvm/CodeGen/TargetFrameLowering.h"
47 #include "llvm/CodeGen/TargetInstrInfo.h"
48 #include "llvm/CodeGen/TargetRegisterInfo.h"
49 #include "llvm/CodeGen/ValueTypes.h"
50 #include "llvm/IR/CallingConv.h"
51 #include "llvm/IR/Constants.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/DebugLoc.h"
54 #include "llvm/IR/DerivedTypes.h"
55 #include "llvm/IR/Function.h"
56 #include "llvm/IR/GlobalValue.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/MC/MCContext.h"
60 #include "llvm/MC/MCRegisterInfo.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/CodeGen.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Compiler.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/MachineValueType.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Target/TargetMachine.h"
69 #include "llvm/Target/TargetOptions.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cctype>
73 #include <cstdint>
74 #include <deque>
75 #include <iterator>
76 #include <utility>
77 #include <vector>
78 
79 using namespace llvm;
80 
81 #define DEBUG_TYPE "mips-lower"
82 
83 STATISTIC(NumTailCalls, "Number of tail calls");
84 
85 static cl::opt<bool>
86 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
87                cl::desc("MIPS: Don't trap on integer division by zero."),
88                cl::init(false));
89 
90 extern cl::opt<bool> EmitJalrReloc;
91 
92 static const MCPhysReg Mips64DPRegs[8] = {
93   Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
94   Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
95 };
96 
97 // The MIPS MSA ABI passes vector arguments in the integer register set.
98 // The number of integer registers used is dependant on the ABI used.
99 MVT MipsTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
100                                                       CallingConv::ID CC,
101                                                       EVT VT) const {
102   if (!VT.isVector())
103     return getRegisterType(Context, VT);
104 
105   return Subtarget.isABI_O32() || VT.getSizeInBits() == 32 ? MVT::i32
106                                                            : MVT::i64;
107 }
108 
109 unsigned MipsTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
110                                                            CallingConv::ID CC,
111                                                            EVT VT) const {
112   if (VT.isVector())
113     return divideCeil(VT.getSizeInBits(), Subtarget.isABI_O32() ? 32 : 64);
114   return MipsTargetLowering::getNumRegisters(Context, VT);
115 }
116 
117 unsigned MipsTargetLowering::getVectorTypeBreakdownForCallingConv(
118     LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
119     unsigned &NumIntermediates, MVT &RegisterVT) const {
120   // Break down vector types to either 2 i64s or 4 i32s.
121   RegisterVT = getRegisterTypeForCallingConv(Context, CC, VT);
122   IntermediateVT = RegisterVT;
123   NumIntermediates =
124       VT.getFixedSizeInBits() < RegisterVT.getFixedSizeInBits()
125           ? VT.getVectorNumElements()
126           : divideCeil(VT.getSizeInBits(), RegisterVT.getSizeInBits());
127   return NumIntermediates;
128 }
129 
130 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
131   MachineFunction &MF = DAG.getMachineFunction();
132   MipsFunctionInfo *FI = MF.getInfo<MipsFunctionInfo>();
133   return DAG.getRegister(FI->getGlobalBaseReg(MF), Ty);
134 }
135 
136 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
137                                           SelectionDAG &DAG,
138                                           unsigned Flag) const {
139   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
140 }
141 
142 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
143                                           SelectionDAG &DAG,
144                                           unsigned Flag) const {
145   return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
146 }
147 
148 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
149                                           SelectionDAG &DAG,
150                                           unsigned Flag) const {
151   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
152 }
153 
154 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
155                                           SelectionDAG &DAG,
156                                           unsigned Flag) const {
157   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
158 }
159 
160 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
161                                           SelectionDAG &DAG,
162                                           unsigned Flag) const {
163   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
164                                    N->getOffset(), Flag);
165 }
166 
167 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
168   switch ((MipsISD::NodeType)Opcode) {
169   case MipsISD::FIRST_NUMBER:      break;
170   case MipsISD::JmpLink:           return "MipsISD::JmpLink";
171   case MipsISD::TailCall:          return "MipsISD::TailCall";
172   case MipsISD::Highest:           return "MipsISD::Highest";
173   case MipsISD::Higher:            return "MipsISD::Higher";
174   case MipsISD::Hi:                return "MipsISD::Hi";
175   case MipsISD::Lo:                return "MipsISD::Lo";
176   case MipsISD::GotHi:             return "MipsISD::GotHi";
177   case MipsISD::TlsHi:             return "MipsISD::TlsHi";
178   case MipsISD::GPRel:             return "MipsISD::GPRel";
179   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
180   case MipsISD::Ret:               return "MipsISD::Ret";
181   case MipsISD::ERet:              return "MipsISD::ERet";
182   case MipsISD::EH_RETURN:         return "MipsISD::EH_RETURN";
183   case MipsISD::FMS:               return "MipsISD::FMS";
184   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
185   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
186   case MipsISD::FSELECT:           return "MipsISD::FSELECT";
187   case MipsISD::MTC1_D64:          return "MipsISD::MTC1_D64";
188   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
189   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
190   case MipsISD::TruncIntFP:        return "MipsISD::TruncIntFP";
191   case MipsISD::MFHI:              return "MipsISD::MFHI";
192   case MipsISD::MFLO:              return "MipsISD::MFLO";
193   case MipsISD::MTLOHI:            return "MipsISD::MTLOHI";
194   case MipsISD::Mult:              return "MipsISD::Mult";
195   case MipsISD::Multu:             return "MipsISD::Multu";
196   case MipsISD::MAdd:              return "MipsISD::MAdd";
197   case MipsISD::MAddu:             return "MipsISD::MAddu";
198   case MipsISD::MSub:              return "MipsISD::MSub";
199   case MipsISD::MSubu:             return "MipsISD::MSubu";
200   case MipsISD::DivRem:            return "MipsISD::DivRem";
201   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
202   case MipsISD::DivRem16:          return "MipsISD::DivRem16";
203   case MipsISD::DivRemU16:         return "MipsISD::DivRemU16";
204   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
205   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
206   case MipsISD::Wrapper:           return "MipsISD::Wrapper";
207   case MipsISD::DynAlloc:          return "MipsISD::DynAlloc";
208   case MipsISD::Sync:              return "MipsISD::Sync";
209   case MipsISD::Ext:               return "MipsISD::Ext";
210   case MipsISD::Ins:               return "MipsISD::Ins";
211   case MipsISD::CIns:              return "MipsISD::CIns";
212   case MipsISD::LWL:               return "MipsISD::LWL";
213   case MipsISD::LWR:               return "MipsISD::LWR";
214   case MipsISD::SWL:               return "MipsISD::SWL";
215   case MipsISD::SWR:               return "MipsISD::SWR";
216   case MipsISD::LDL:               return "MipsISD::LDL";
217   case MipsISD::LDR:               return "MipsISD::LDR";
218   case MipsISD::SDL:               return "MipsISD::SDL";
219   case MipsISD::SDR:               return "MipsISD::SDR";
220   case MipsISD::EXTP:              return "MipsISD::EXTP";
221   case MipsISD::EXTPDP:            return "MipsISD::EXTPDP";
222   case MipsISD::EXTR_S_H:          return "MipsISD::EXTR_S_H";
223   case MipsISD::EXTR_W:            return "MipsISD::EXTR_W";
224   case MipsISD::EXTR_R_W:          return "MipsISD::EXTR_R_W";
225   case MipsISD::EXTR_RS_W:         return "MipsISD::EXTR_RS_W";
226   case MipsISD::SHILO:             return "MipsISD::SHILO";
227   case MipsISD::MTHLIP:            return "MipsISD::MTHLIP";
228   case MipsISD::MULSAQ_S_W_PH:     return "MipsISD::MULSAQ_S_W_PH";
229   case MipsISD::MAQ_S_W_PHL:       return "MipsISD::MAQ_S_W_PHL";
230   case MipsISD::MAQ_S_W_PHR:       return "MipsISD::MAQ_S_W_PHR";
231   case MipsISD::MAQ_SA_W_PHL:      return "MipsISD::MAQ_SA_W_PHL";
232   case MipsISD::MAQ_SA_W_PHR:      return "MipsISD::MAQ_SA_W_PHR";
233   case MipsISD::DPAU_H_QBL:        return "MipsISD::DPAU_H_QBL";
234   case MipsISD::DPAU_H_QBR:        return "MipsISD::DPAU_H_QBR";
235   case MipsISD::DPSU_H_QBL:        return "MipsISD::DPSU_H_QBL";
236   case MipsISD::DPSU_H_QBR:        return "MipsISD::DPSU_H_QBR";
237   case MipsISD::DPAQ_S_W_PH:       return "MipsISD::DPAQ_S_W_PH";
238   case MipsISD::DPSQ_S_W_PH:       return "MipsISD::DPSQ_S_W_PH";
239   case MipsISD::DPAQ_SA_L_W:       return "MipsISD::DPAQ_SA_L_W";
240   case MipsISD::DPSQ_SA_L_W:       return "MipsISD::DPSQ_SA_L_W";
241   case MipsISD::DPA_W_PH:          return "MipsISD::DPA_W_PH";
242   case MipsISD::DPS_W_PH:          return "MipsISD::DPS_W_PH";
243   case MipsISD::DPAQX_S_W_PH:      return "MipsISD::DPAQX_S_W_PH";
244   case MipsISD::DPAQX_SA_W_PH:     return "MipsISD::DPAQX_SA_W_PH";
245   case MipsISD::DPAX_W_PH:         return "MipsISD::DPAX_W_PH";
246   case MipsISD::DPSX_W_PH:         return "MipsISD::DPSX_W_PH";
247   case MipsISD::DPSQX_S_W_PH:      return "MipsISD::DPSQX_S_W_PH";
248   case MipsISD::DPSQX_SA_W_PH:     return "MipsISD::DPSQX_SA_W_PH";
249   case MipsISD::MULSA_W_PH:        return "MipsISD::MULSA_W_PH";
250   case MipsISD::MULT:              return "MipsISD::MULT";
251   case MipsISD::MULTU:             return "MipsISD::MULTU";
252   case MipsISD::MADD_DSP:          return "MipsISD::MADD_DSP";
253   case MipsISD::MADDU_DSP:         return "MipsISD::MADDU_DSP";
254   case MipsISD::MSUB_DSP:          return "MipsISD::MSUB_DSP";
255   case MipsISD::MSUBU_DSP:         return "MipsISD::MSUBU_DSP";
256   case MipsISD::SHLL_DSP:          return "MipsISD::SHLL_DSP";
257   case MipsISD::SHRA_DSP:          return "MipsISD::SHRA_DSP";
258   case MipsISD::SHRL_DSP:          return "MipsISD::SHRL_DSP";
259   case MipsISD::SETCC_DSP:         return "MipsISD::SETCC_DSP";
260   case MipsISD::SELECT_CC_DSP:     return "MipsISD::SELECT_CC_DSP";
261   case MipsISD::VALL_ZERO:         return "MipsISD::VALL_ZERO";
262   case MipsISD::VANY_ZERO:         return "MipsISD::VANY_ZERO";
263   case MipsISD::VALL_NONZERO:      return "MipsISD::VALL_NONZERO";
264   case MipsISD::VANY_NONZERO:      return "MipsISD::VANY_NONZERO";
265   case MipsISD::VCEQ:              return "MipsISD::VCEQ";
266   case MipsISD::VCLE_S:            return "MipsISD::VCLE_S";
267   case MipsISD::VCLE_U:            return "MipsISD::VCLE_U";
268   case MipsISD::VCLT_S:            return "MipsISD::VCLT_S";
269   case MipsISD::VCLT_U:            return "MipsISD::VCLT_U";
270   case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
271   case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
272   case MipsISD::VNOR:              return "MipsISD::VNOR";
273   case MipsISD::VSHF:              return "MipsISD::VSHF";
274   case MipsISD::SHF:               return "MipsISD::SHF";
275   case MipsISD::ILVEV:             return "MipsISD::ILVEV";
276   case MipsISD::ILVOD:             return "MipsISD::ILVOD";
277   case MipsISD::ILVL:              return "MipsISD::ILVL";
278   case MipsISD::ILVR:              return "MipsISD::ILVR";
279   case MipsISD::PCKEV:             return "MipsISD::PCKEV";
280   case MipsISD::PCKOD:             return "MipsISD::PCKOD";
281   case MipsISD::INSVE:             return "MipsISD::INSVE";
282   }
283   return nullptr;
284 }
285 
286 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
287                                        const MipsSubtarget &STI)
288     : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
289   // Mips does not have i1 type, so use i32 for
290   // setcc operations results (slt, sgt, ...).
291   setBooleanContents(ZeroOrOneBooleanContent);
292   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
293   // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
294   // does. Integer booleans still use 0 and 1.
295   if (Subtarget.hasMips32r6())
296     setBooleanContents(ZeroOrOneBooleanContent,
297                        ZeroOrNegativeOneBooleanContent);
298 
299   // Load extented operations for i1 types must be promoted
300   for (MVT VT : MVT::integer_valuetypes()) {
301     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1,  Promote);
302     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1,  Promote);
303     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1,  Promote);
304   }
305 
306   // MIPS doesn't have extending float->double load/store.  Set LoadExtAction
307   // for f32, f16
308   for (MVT VT : MVT::fp_valuetypes()) {
309     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
310     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
311   }
312 
313   // Set LoadExtAction for f16 vectors to Expand
314   for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
315     MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
316     if (F16VT.isValid())
317       setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
318   }
319 
320   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
321   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
322 
323   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
324 
325   // Used by legalize types to correctly generate the setcc result.
326   // Without this, every float setcc comes with a AND/OR with the result,
327   // we don't want this, since the fpcmp result goes to a flag register,
328   // which is used implicitly by brcond and select operations.
329   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
330 
331   // Mips Custom Operations
332   setOperationAction(ISD::BR_JT,              MVT::Other, Expand);
333   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
334   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
335   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
336   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
337   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
338   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
339   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
340   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
341   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
342   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
343   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
344   setOperationAction(ISD::FCOPYSIGN,          MVT::f32,   Custom);
345   setOperationAction(ISD::FCOPYSIGN,          MVT::f64,   Custom);
346   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
347 
348   if (!(TM.Options.NoNaNsFPMath || Subtarget.inAbs2008Mode())) {
349     setOperationAction(ISD::FABS, MVT::f32, Custom);
350     setOperationAction(ISD::FABS, MVT::f64, Custom);
351   }
352 
353   if (Subtarget.isGP64bit()) {
354     setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
355     setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
356     setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
357     setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
358     setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
359     setOperationAction(ISD::SELECT,             MVT::i64,   Custom);
360     setOperationAction(ISD::LOAD,               MVT::i64,   Custom);
361     setOperationAction(ISD::STORE,              MVT::i64,   Custom);
362     setOperationAction(ISD::FP_TO_SINT,         MVT::i64,   Custom);
363     setOperationAction(ISD::SHL_PARTS,          MVT::i64,   Custom);
364     setOperationAction(ISD::SRA_PARTS,          MVT::i64,   Custom);
365     setOperationAction(ISD::SRL_PARTS,          MVT::i64,   Custom);
366   }
367 
368   if (!Subtarget.isGP64bit()) {
369     setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Custom);
370     setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Custom);
371     setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Custom);
372   }
373 
374   setOperationAction(ISD::EH_DWARF_CFA,         MVT::i32,   Custom);
375   if (Subtarget.isGP64bit())
376     setOperationAction(ISD::EH_DWARF_CFA,       MVT::i64,   Custom);
377 
378   setOperationAction(ISD::SDIV, MVT::i32, Expand);
379   setOperationAction(ISD::SREM, MVT::i32, Expand);
380   setOperationAction(ISD::UDIV, MVT::i32, Expand);
381   setOperationAction(ISD::UREM, MVT::i32, Expand);
382   setOperationAction(ISD::SDIV, MVT::i64, Expand);
383   setOperationAction(ISD::SREM, MVT::i64, Expand);
384   setOperationAction(ISD::UDIV, MVT::i64, Expand);
385   setOperationAction(ISD::UREM, MVT::i64, Expand);
386 
387   // Operations not directly supported by Mips.
388   setOperationAction(ISD::BR_CC,             MVT::f32,   Expand);
389   setOperationAction(ISD::BR_CC,             MVT::f64,   Expand);
390   setOperationAction(ISD::BR_CC,             MVT::i32,   Expand);
391   setOperationAction(ISD::BR_CC,             MVT::i64,   Expand);
392   setOperationAction(ISD::SELECT_CC,         MVT::i32,   Expand);
393   setOperationAction(ISD::SELECT_CC,         MVT::i64,   Expand);
394   setOperationAction(ISD::SELECT_CC,         MVT::f32,   Expand);
395   setOperationAction(ISD::SELECT_CC,         MVT::f64,   Expand);
396   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
397   setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
398   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
399   setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
400   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
401   if (Subtarget.hasCnMips()) {
402     setOperationAction(ISD::CTPOP,           MVT::i32,   Legal);
403     setOperationAction(ISD::CTPOP,           MVT::i64,   Legal);
404   } else {
405     setOperationAction(ISD::CTPOP,           MVT::i32,   Expand);
406     setOperationAction(ISD::CTPOP,           MVT::i64,   Expand);
407   }
408   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
409   setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
410   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
411   setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
412   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,  Expand);
413   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,  Expand);
414 
415   if (!Subtarget.hasMips32r2())
416     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
417 
418   if (!Subtarget.hasMips64r2())
419     setOperationAction(ISD::ROTR, MVT::i64,   Expand);
420 
421   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
422   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
423   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
424   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
425   setOperationAction(ISD::FSINCOS,           MVT::f32,   Expand);
426   setOperationAction(ISD::FSINCOS,           MVT::f64,   Expand);
427   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
428   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
429   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
430   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
431   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
432   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
433   setOperationAction(ISD::FMA,               MVT::f32,   Expand);
434   setOperationAction(ISD::FMA,               MVT::f64,   Expand);
435   setOperationAction(ISD::FREM,              MVT::f32,   Expand);
436   setOperationAction(ISD::FREM,              MVT::f64,   Expand);
437 
438   // Lower f16 conversion operations into library calls
439   setOperationAction(ISD::FP16_TO_FP,        MVT::f32,   Expand);
440   setOperationAction(ISD::FP_TO_FP16,        MVT::f32,   Expand);
441   setOperationAction(ISD::FP16_TO_FP,        MVT::f64,   Expand);
442   setOperationAction(ISD::FP_TO_FP16,        MVT::f64,   Expand);
443 
444   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
445 
446   setOperationAction(ISD::VASTART,           MVT::Other, Custom);
447   setOperationAction(ISD::VAARG,             MVT::Other, Custom);
448   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
449   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
450 
451   // Use the default for now
452   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
453   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
454 
455   if (!Subtarget.isGP64bit()) {
456     setOperationAction(ISD::ATOMIC_LOAD,     MVT::i64,   Expand);
457     setOperationAction(ISD::ATOMIC_STORE,    MVT::i64,   Expand);
458   }
459 
460   if (!Subtarget.hasMips32r2()) {
461     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
462     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
463   }
464 
465   // MIPS16 lacks MIPS32's clz and clo instructions.
466   if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
467     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
468   if (!Subtarget.hasMips64())
469     setOperationAction(ISD::CTLZ, MVT::i64, Expand);
470 
471   if (!Subtarget.hasMips32r2())
472     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
473   if (!Subtarget.hasMips64r2())
474     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
475 
476   if (Subtarget.isGP64bit()) {
477     setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
478     setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
479     setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
480     setTruncStoreAction(MVT::i64, MVT::i32, Custom);
481   }
482 
483   setOperationAction(ISD::TRAP, MVT::Other, Legal);
484 
485   setTargetDAGCombine(ISD::SDIVREM);
486   setTargetDAGCombine(ISD::UDIVREM);
487   setTargetDAGCombine(ISD::SELECT);
488   setTargetDAGCombine(ISD::AND);
489   setTargetDAGCombine(ISD::OR);
490   setTargetDAGCombine(ISD::ADD);
491   setTargetDAGCombine(ISD::SUB);
492   setTargetDAGCombine(ISD::AssertZext);
493   setTargetDAGCombine(ISD::SHL);
494 
495   if (ABI.IsO32()) {
496     // These libcalls are not available in 32-bit.
497     setLibcallName(RTLIB::SHL_I128, nullptr);
498     setLibcallName(RTLIB::SRL_I128, nullptr);
499     setLibcallName(RTLIB::SRA_I128, nullptr);
500     setLibcallName(RTLIB::MUL_I128, nullptr);
501     setLibcallName(RTLIB::MULO_I64, nullptr);
502     setLibcallName(RTLIB::MULO_I128, nullptr);
503   }
504 
505   setMinFunctionAlignment(Subtarget.isGP64bit() ? Align(8) : Align(4));
506 
507   // The arguments on the stack are defined in terms of 4-byte slots on O32
508   // and 8-byte slots on N32/N64.
509   setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? Align(8)
510                                                             : Align(4));
511 
512   setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
513 
514   MaxStoresPerMemcpy = 16;
515 
516   isMicroMips = Subtarget.inMicroMipsMode();
517 }
518 
519 const MipsTargetLowering *
520 MipsTargetLowering::create(const MipsTargetMachine &TM,
521                            const MipsSubtarget &STI) {
522   if (STI.inMips16Mode())
523     return createMips16TargetLowering(TM, STI);
524 
525   return createMipsSETargetLowering(TM, STI);
526 }
527 
528 // Create a fast isel object.
529 FastISel *
530 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
531                                   const TargetLibraryInfo *libInfo) const {
532   const MipsTargetMachine &TM =
533       static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
534 
535   // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
536   bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
537                      !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() &&
538                      !Subtarget.inMicroMipsMode();
539 
540   // Disable if either of the following is true:
541   // We do not generate PIC, the ABI is not O32, XGOT is being used.
542   if (!TM.isPositionIndependent() || !TM.getABI().IsO32() ||
543       Subtarget.useXGOT())
544     UseFastISel = false;
545 
546   return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr;
547 }
548 
549 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
550                                            EVT VT) const {
551   if (!VT.isVector())
552     return MVT::i32;
553   return VT.changeVectorElementTypeToInteger();
554 }
555 
556 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
557                                     TargetLowering::DAGCombinerInfo &DCI,
558                                     const MipsSubtarget &Subtarget) {
559   if (DCI.isBeforeLegalizeOps())
560     return SDValue();
561 
562   EVT Ty = N->getValueType(0);
563   unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
564   unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
565   unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
566                                                   MipsISD::DivRemU16;
567   SDLoc DL(N);
568 
569   SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
570                                N->getOperand(0), N->getOperand(1));
571   SDValue InChain = DAG.getEntryNode();
572   SDValue InGlue = DivRem;
573 
574   // insert MFLO
575   if (N->hasAnyUseOfValue(0)) {
576     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
577                                             InGlue);
578     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
579     InChain = CopyFromLo.getValue(1);
580     InGlue = CopyFromLo.getValue(2);
581   }
582 
583   // insert MFHI
584   if (N->hasAnyUseOfValue(1)) {
585     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
586                                             HI, Ty, InGlue);
587     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
588   }
589 
590   return SDValue();
591 }
592 
593 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
594   switch (CC) {
595   default: llvm_unreachable("Unknown fp condition code!");
596   case ISD::SETEQ:
597   case ISD::SETOEQ: return Mips::FCOND_OEQ;
598   case ISD::SETUNE: return Mips::FCOND_UNE;
599   case ISD::SETLT:
600   case ISD::SETOLT: return Mips::FCOND_OLT;
601   case ISD::SETGT:
602   case ISD::SETOGT: return Mips::FCOND_OGT;
603   case ISD::SETLE:
604   case ISD::SETOLE: return Mips::FCOND_OLE;
605   case ISD::SETGE:
606   case ISD::SETOGE: return Mips::FCOND_OGE;
607   case ISD::SETULT: return Mips::FCOND_ULT;
608   case ISD::SETULE: return Mips::FCOND_ULE;
609   case ISD::SETUGT: return Mips::FCOND_UGT;
610   case ISD::SETUGE: return Mips::FCOND_UGE;
611   case ISD::SETUO:  return Mips::FCOND_UN;
612   case ISD::SETO:   return Mips::FCOND_OR;
613   case ISD::SETNE:
614   case ISD::SETONE: return Mips::FCOND_ONE;
615   case ISD::SETUEQ: return Mips::FCOND_UEQ;
616   }
617 }
618 
619 /// This function returns true if the floating point conditional branches and
620 /// conditional moves which use condition code CC should be inverted.
621 static bool invertFPCondCodeUser(Mips::CondCode CC) {
622   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
623     return false;
624 
625   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
626          "Illegal Condition Code");
627 
628   return true;
629 }
630 
631 // Creates and returns an FPCmp node from a setcc node.
632 // Returns Op if setcc is not a floating point comparison.
633 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
634   // must be a SETCC node
635   if (Op.getOpcode() != ISD::SETCC)
636     return Op;
637 
638   SDValue LHS = Op.getOperand(0);
639 
640   if (!LHS.getValueType().isFloatingPoint())
641     return Op;
642 
643   SDValue RHS = Op.getOperand(1);
644   SDLoc DL(Op);
645 
646   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
647   // node if necessary.
648   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
649 
650   return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
651                      DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
652 }
653 
654 // Creates and returns a CMovFPT/F node.
655 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
656                             SDValue False, const SDLoc &DL) {
657   ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
658   bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
659   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
660 
661   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
662                      True.getValueType(), True, FCC0, False, Cond);
663 }
664 
665 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
666                                     TargetLowering::DAGCombinerInfo &DCI,
667                                     const MipsSubtarget &Subtarget) {
668   if (DCI.isBeforeLegalizeOps())
669     return SDValue();
670 
671   SDValue SetCC = N->getOperand(0);
672 
673   if ((SetCC.getOpcode() != ISD::SETCC) ||
674       !SetCC.getOperand(0).getValueType().isInteger())
675     return SDValue();
676 
677   SDValue False = N->getOperand(2);
678   EVT FalseTy = False.getValueType();
679 
680   if (!FalseTy.isInteger())
681     return SDValue();
682 
683   ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
684 
685   // If the RHS (False) is 0, we swap the order of the operands
686   // of ISD::SELECT (obviously also inverting the condition) so that we can
687   // take advantage of conditional moves using the $0 register.
688   // Example:
689   //   return (a != 0) ? x : 0;
690   //     load $reg, x
691   //     movz $reg, $0, a
692   if (!FalseC)
693     return SDValue();
694 
695   const SDLoc DL(N);
696 
697   if (!FalseC->getZExtValue()) {
698     ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
699     SDValue True = N->getOperand(1);
700 
701     SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
702                          SetCC.getOperand(1),
703                          ISD::getSetCCInverse(CC, SetCC.getValueType()));
704 
705     return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
706   }
707 
708   // If both operands are integer constants there's a possibility that we
709   // can do some interesting optimizations.
710   SDValue True = N->getOperand(1);
711   ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
712 
713   if (!TrueC || !True.getValueType().isInteger())
714     return SDValue();
715 
716   // We'll also ignore MVT::i64 operands as this optimizations proves
717   // to be ineffective because of the required sign extensions as the result
718   // of a SETCC operator is always MVT::i32 for non-vector types.
719   if (True.getValueType() == MVT::i64)
720     return SDValue();
721 
722   int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
723 
724   // 1)  (a < x) ? y : y-1
725   //  slti $reg1, a, x
726   //  addiu $reg2, $reg1, y-1
727   if (Diff == 1)
728     return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
729 
730   // 2)  (a < x) ? y-1 : y
731   //  slti $reg1, a, x
732   //  xor $reg1, $reg1, 1
733   //  addiu $reg2, $reg1, y-1
734   if (Diff == -1) {
735     ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
736     SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
737                          SetCC.getOperand(1),
738                          ISD::getSetCCInverse(CC, SetCC.getValueType()));
739     return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
740   }
741 
742   // Could not optimize.
743   return SDValue();
744 }
745 
746 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
747                                     TargetLowering::DAGCombinerInfo &DCI,
748                                     const MipsSubtarget &Subtarget) {
749   if (DCI.isBeforeLegalizeOps())
750     return SDValue();
751 
752   SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
753 
754   ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
755   if (!FalseC || FalseC->getZExtValue())
756     return SDValue();
757 
758   // Since RHS (False) is 0, we swap the order of the True/False operands
759   // (obviously also inverting the condition) so that we can
760   // take advantage of conditional moves using the $0 register.
761   // Example:
762   //   return (a != 0) ? x : 0;
763   //     load $reg, x
764   //     movz $reg, $0, a
765   unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
766                                                          MipsISD::CMovFP_T;
767 
768   SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
769   return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
770                      ValueIfFalse, FCC, ValueIfTrue, Glue);
771 }
772 
773 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
774                                  TargetLowering::DAGCombinerInfo &DCI,
775                                  const MipsSubtarget &Subtarget) {
776   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
777     return SDValue();
778 
779   SDValue FirstOperand = N->getOperand(0);
780   unsigned FirstOperandOpc = FirstOperand.getOpcode();
781   SDValue Mask = N->getOperand(1);
782   EVT ValTy = N->getValueType(0);
783   SDLoc DL(N);
784 
785   uint64_t Pos = 0;
786   unsigned SMPos, SMSize;
787   ConstantSDNode *CN;
788   SDValue NewOperand;
789   unsigned Opc;
790 
791   // Op's second operand must be a shifted mask.
792   if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
793       !isShiftedMask_64(CN->getZExtValue(), SMPos, SMSize))
794     return SDValue();
795 
796   if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
797     // Pattern match EXT.
798     //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
799     //  => ext $dst, $src, pos, size
800 
801     // The second operand of the shift must be an immediate.
802     if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
803       return SDValue();
804 
805     Pos = CN->getZExtValue();
806 
807     // Return if the shifted mask does not start at bit 0 or the sum of its size
808     // and Pos exceeds the word's size.
809     if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
810       return SDValue();
811 
812     Opc = MipsISD::Ext;
813     NewOperand = FirstOperand.getOperand(0);
814   } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
815     // Pattern match CINS.
816     //  $dst = and (shl $src , pos), mask
817     //  => cins $dst, $src, pos, size
818     // mask is a shifted mask with consecutive 1's, pos = shift amount,
819     // size = population count.
820 
821     // The second operand of the shift must be an immediate.
822     if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
823       return SDValue();
824 
825     Pos = CN->getZExtValue();
826 
827     if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
828         Pos + SMSize > ValTy.getSizeInBits())
829       return SDValue();
830 
831     NewOperand = FirstOperand.getOperand(0);
832     // SMSize is 'location' (position) in this case, not size.
833     SMSize--;
834     Opc = MipsISD::CIns;
835   } else {
836     // Pattern match EXT.
837     //  $dst = and $src, (2**size - 1) , if size > 16
838     //  => ext $dst, $src, pos, size , pos = 0
839 
840     // If the mask is <= 0xffff, andi can be used instead.
841     if (CN->getZExtValue() <= 0xffff)
842       return SDValue();
843 
844     // Return if the mask doesn't start at position 0.
845     if (SMPos)
846       return SDValue();
847 
848     Opc = MipsISD::Ext;
849     NewOperand = FirstOperand;
850   }
851   return DAG.getNode(Opc, DL, ValTy, NewOperand,
852                      DAG.getConstant(Pos, DL, MVT::i32),
853                      DAG.getConstant(SMSize, DL, MVT::i32));
854 }
855 
856 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
857                                 TargetLowering::DAGCombinerInfo &DCI,
858                                 const MipsSubtarget &Subtarget) {
859   // Pattern match INS.
860   //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
861   //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1
862   //  => ins $dst, $src, size, pos, $src1
863   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
864     return SDValue();
865 
866   SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
867   unsigned SMPos0, SMSize0, SMPos1, SMSize1;
868   ConstantSDNode *CN, *CN1;
869 
870   // See if Op's first operand matches (and $src1 , mask0).
871   if (And0.getOpcode() != ISD::AND)
872     return SDValue();
873 
874   if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
875       !isShiftedMask_64(~CN->getSExtValue(), SMPos0, SMSize0))
876     return SDValue();
877 
878   // See if Op's second operand matches (and (shl $src, pos), mask1).
879   if (And1.getOpcode() == ISD::AND &&
880       And1.getOperand(0).getOpcode() == ISD::SHL) {
881 
882     if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
883         !isShiftedMask_64(CN->getZExtValue(), SMPos1, SMSize1))
884       return SDValue();
885 
886     // The shift masks must have the same position and size.
887     if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
888       return SDValue();
889 
890     SDValue Shl = And1.getOperand(0);
891 
892     if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
893       return SDValue();
894 
895     unsigned Shamt = CN->getZExtValue();
896 
897     // Return if the shift amount and the first bit position of mask are not the
898     // same.
899     EVT ValTy = N->getValueType(0);
900     if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
901       return SDValue();
902 
903     SDLoc DL(N);
904     return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
905                        DAG.getConstant(SMPos0, DL, MVT::i32),
906                        DAG.getConstant(SMSize0, DL, MVT::i32),
907                        And0.getOperand(0));
908   } else {
909     // Pattern match DINS.
910     //  $dst = or (and $src, mask0), mask1
911     //  where mask0 = ((1 << SMSize0) -1) << SMPos0
912     //  => dins $dst, $src, pos, size
913     if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) &&
914         ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
915          (SMSize0 + SMPos0 <= 32))) {
916       // Check if AND instruction has constant as argument
917       bool isConstCase = And1.getOpcode() != ISD::AND;
918       if (And1.getOpcode() == ISD::AND) {
919         if (!(CN1 = dyn_cast<ConstantSDNode>(And1->getOperand(1))))
920           return SDValue();
921       } else {
922         if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
923           return SDValue();
924       }
925       // Don't generate INS if constant OR operand doesn't fit into bits
926       // cleared by constant AND operand.
927       if (CN->getSExtValue() & CN1->getSExtValue())
928         return SDValue();
929 
930       SDLoc DL(N);
931       EVT ValTy = N->getOperand(0)->getValueType(0);
932       SDValue Const1;
933       SDValue SrlX;
934       if (!isConstCase) {
935         Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
936         SrlX = DAG.getNode(ISD::SRL, DL, And1->getValueType(0), And1, Const1);
937       }
938       return DAG.getNode(
939           MipsISD::Ins, DL, N->getValueType(0),
940           isConstCase
941               ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
942               : SrlX,
943           DAG.getConstant(SMPos0, DL, MVT::i32),
944           DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
945                                                         : SMSize0,
946                           DL, MVT::i32),
947           And0->getOperand(0));
948 
949     }
950     return SDValue();
951   }
952 }
953 
954 static SDValue performMADD_MSUBCombine(SDNode *ROOTNode, SelectionDAG &CurDAG,
955                                        const MipsSubtarget &Subtarget) {
956   // ROOTNode must have a multiplication as an operand for the match to be
957   // successful.
958   if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL &&
959       ROOTNode->getOperand(1).getOpcode() != ISD::MUL)
960     return SDValue();
961 
962   // We don't handle vector types here.
963   if (ROOTNode->getValueType(0).isVector())
964     return SDValue();
965 
966   // For MIPS64, madd / msub instructions are inefficent to use with 64 bit
967   // arithmetic. E.g.
968   // (add (mul a b) c) =>
969   //   let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in
970   //   MIPS64:   (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32)
971   //   or
972   //   MIPS64R2: (dins (mflo res) (mfhi res) 32 32)
973   //
974   // The overhead of setting up the Hi/Lo registers and reassembling the
975   // result makes this a dubious optimzation for MIPS64. The core of the
976   // problem is that Hi/Lo contain the upper and lower 32 bits of the
977   // operand and result.
978   //
979   // It requires a chain of 4 add/mul for MIPS64R2 to get better code
980   // density than doing it naively, 5 for MIPS64. Additionally, using
981   // madd/msub on MIPS64 requires the operands actually be 32 bit sign
982   // extended operands, not true 64 bit values.
983   //
984   // FIXME: For the moment, disable this completely for MIPS64.
985   if (Subtarget.hasMips64())
986     return SDValue();
987 
988   SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
989                      ? ROOTNode->getOperand(0)
990                      : ROOTNode->getOperand(1);
991 
992   SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
993                      ? ROOTNode->getOperand(1)
994                      : ROOTNode->getOperand(0);
995 
996   // Transform this to a MADD only if the user of this node is the add.
997   // If there are other users of the mul, this function returns here.
998   if (!Mult.hasOneUse())
999     return SDValue();
1000 
1001   // maddu and madd are unusual instructions in that on MIPS64 bits 63..31
1002   // must be in canonical form, i.e. sign extended. For MIPS32, the operands
1003   // of the multiply must have 32 or more sign bits, otherwise we cannot
1004   // perform this optimization. We have to check this here as we're performing
1005   // this optimization pre-legalization.
1006   SDValue MultLHS = Mult->getOperand(0);
1007   SDValue MultRHS = Mult->getOperand(1);
1008 
1009   bool IsSigned = MultLHS->getOpcode() == ISD::SIGN_EXTEND &&
1010                   MultRHS->getOpcode() == ISD::SIGN_EXTEND;
1011   bool IsUnsigned = MultLHS->getOpcode() == ISD::ZERO_EXTEND &&
1012                     MultRHS->getOpcode() == ISD::ZERO_EXTEND;
1013 
1014   if (!IsSigned && !IsUnsigned)
1015     return SDValue();
1016 
1017   // Initialize accumulator.
1018   SDLoc DL(ROOTNode);
1019   SDValue TopHalf;
1020   SDValue BottomHalf;
1021   BottomHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1022                               CurDAG.getIntPtrConstant(0, DL));
1023 
1024   TopHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1025                            CurDAG.getIntPtrConstant(1, DL));
1026   SDValue ACCIn = CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped,
1027                                   BottomHalf,
1028                                   TopHalf);
1029 
1030   // Create MipsMAdd(u) / MipsMSub(u) node.
1031   bool IsAdd = ROOTNode->getOpcode() == ISD::ADD;
1032   unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd)
1033                           : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub);
1034   SDValue MAddOps[3] = {
1035       CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)),
1036       CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn};
1037   EVT VTs[2] = {MVT::i32, MVT::i32};
1038   SDValue MAdd = CurDAG.getNode(Opcode, DL, VTs, MAddOps);
1039 
1040   SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
1041   SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
1042   SDValue Combined =
1043       CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi);
1044   return Combined;
1045 }
1046 
1047 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG,
1048                                  TargetLowering::DAGCombinerInfo &DCI,
1049                                  const MipsSubtarget &Subtarget) {
1050   // (sub v0 (mul v1, v2)) => (msub v1, v2, v0)
1051   if (DCI.isBeforeLegalizeOps()) {
1052     if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1053         !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1054       return performMADD_MSUBCombine(N, DAG, Subtarget);
1055 
1056     return SDValue();
1057   }
1058 
1059   return SDValue();
1060 }
1061 
1062 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
1063                                  TargetLowering::DAGCombinerInfo &DCI,
1064                                  const MipsSubtarget &Subtarget) {
1065   // (add v0 (mul v1, v2)) => (madd v1, v2, v0)
1066   if (DCI.isBeforeLegalizeOps()) {
1067     if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1068         !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1069       return performMADD_MSUBCombine(N, DAG, Subtarget);
1070 
1071     return SDValue();
1072   }
1073 
1074   // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
1075   SDValue Add = N->getOperand(1);
1076 
1077   if (Add.getOpcode() != ISD::ADD)
1078     return SDValue();
1079 
1080   SDValue Lo = Add.getOperand(1);
1081 
1082   if ((Lo.getOpcode() != MipsISD::Lo) ||
1083       (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
1084     return SDValue();
1085 
1086   EVT ValTy = N->getValueType(0);
1087   SDLoc DL(N);
1088 
1089   SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
1090                              Add.getOperand(0));
1091   return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
1092 }
1093 
1094 static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG,
1095                                  TargetLowering::DAGCombinerInfo &DCI,
1096                                  const MipsSubtarget &Subtarget) {
1097   // Pattern match CINS.
1098   //  $dst = shl (and $src , imm), pos
1099   //  => cins $dst, $src, pos, size
1100 
1101   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
1102     return SDValue();
1103 
1104   SDValue FirstOperand = N->getOperand(0);
1105   unsigned FirstOperandOpc = FirstOperand.getOpcode();
1106   SDValue SecondOperand = N->getOperand(1);
1107   EVT ValTy = N->getValueType(0);
1108   SDLoc DL(N);
1109 
1110   uint64_t Pos = 0;
1111   unsigned SMPos, SMSize;
1112   ConstantSDNode *CN;
1113   SDValue NewOperand;
1114 
1115   // The second operand of the shift must be an immediate.
1116   if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
1117     return SDValue();
1118 
1119   Pos = CN->getZExtValue();
1120 
1121   if (Pos >= ValTy.getSizeInBits())
1122     return SDValue();
1123 
1124   if (FirstOperandOpc != ISD::AND)
1125     return SDValue();
1126 
1127   // AND's second operand must be a shifted mask.
1128   if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
1129       !isShiftedMask_64(CN->getZExtValue(), SMPos, SMSize))
1130     return SDValue();
1131 
1132   // Return if the shifted mask does not start at bit 0 or the sum of its size
1133   // and Pos exceeds the word's size.
1134   if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
1135     return SDValue();
1136 
1137   NewOperand = FirstOperand.getOperand(0);
1138   // SMSize is 'location' (position) in this case, not size.
1139   SMSize--;
1140 
1141   return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
1142                      DAG.getConstant(Pos, DL, MVT::i32),
1143                      DAG.getConstant(SMSize, DL, MVT::i32));
1144 }
1145 
1146 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
1147   const {
1148   SelectionDAG &DAG = DCI.DAG;
1149   unsigned Opc = N->getOpcode();
1150 
1151   switch (Opc) {
1152   default: break;
1153   case ISD::SDIVREM:
1154   case ISD::UDIVREM:
1155     return performDivRemCombine(N, DAG, DCI, Subtarget);
1156   case ISD::SELECT:
1157     return performSELECTCombine(N, DAG, DCI, Subtarget);
1158   case MipsISD::CMovFP_F:
1159   case MipsISD::CMovFP_T:
1160     return performCMovFPCombine(N, DAG, DCI, Subtarget);
1161   case ISD::AND:
1162     return performANDCombine(N, DAG, DCI, Subtarget);
1163   case ISD::OR:
1164     return performORCombine(N, DAG, DCI, Subtarget);
1165   case ISD::ADD:
1166     return performADDCombine(N, DAG, DCI, Subtarget);
1167   case ISD::SHL:
1168     return performSHLCombine(N, DAG, DCI, Subtarget);
1169   case ISD::SUB:
1170     return performSUBCombine(N, DAG, DCI, Subtarget);
1171   }
1172 
1173   return SDValue();
1174 }
1175 
1176 bool MipsTargetLowering::isCheapToSpeculateCttz() const {
1177   return Subtarget.hasMips32();
1178 }
1179 
1180 bool MipsTargetLowering::isCheapToSpeculateCtlz() const {
1181   return Subtarget.hasMips32();
1182 }
1183 
1184 bool MipsTargetLowering::shouldFoldConstantShiftPairToMask(
1185     const SDNode *N, CombineLevel Level) const {
1186   if (N->getOperand(0).getValueType().isVector())
1187     return false;
1188   return true;
1189 }
1190 
1191 void
1192 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1193                                        SmallVectorImpl<SDValue> &Results,
1194                                        SelectionDAG &DAG) const {
1195   return LowerOperationWrapper(N, Results, DAG);
1196 }
1197 
1198 SDValue MipsTargetLowering::
1199 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1200 {
1201   switch (Op.getOpcode())
1202   {
1203   case ISD::BRCOND:             return lowerBRCOND(Op, DAG);
1204   case ISD::ConstantPool:       return lowerConstantPool(Op, DAG);
1205   case ISD::GlobalAddress:      return lowerGlobalAddress(Op, DAG);
1206   case ISD::BlockAddress:       return lowerBlockAddress(Op, DAG);
1207   case ISD::GlobalTLSAddress:   return lowerGlobalTLSAddress(Op, DAG);
1208   case ISD::JumpTable:          return lowerJumpTable(Op, DAG);
1209   case ISD::SELECT:             return lowerSELECT(Op, DAG);
1210   case ISD::SETCC:              return lowerSETCC(Op, DAG);
1211   case ISD::VASTART:            return lowerVASTART(Op, DAG);
1212   case ISD::VAARG:              return lowerVAARG(Op, DAG);
1213   case ISD::FCOPYSIGN:          return lowerFCOPYSIGN(Op, DAG);
1214   case ISD::FABS:               return lowerFABS(Op, DAG);
1215   case ISD::FRAMEADDR:          return lowerFRAMEADDR(Op, DAG);
1216   case ISD::RETURNADDR:         return lowerRETURNADDR(Op, DAG);
1217   case ISD::EH_RETURN:          return lowerEH_RETURN(Op, DAG);
1218   case ISD::ATOMIC_FENCE:       return lowerATOMIC_FENCE(Op, DAG);
1219   case ISD::SHL_PARTS:          return lowerShiftLeftParts(Op, DAG);
1220   case ISD::SRA_PARTS:          return lowerShiftRightParts(Op, DAG, true);
1221   case ISD::SRL_PARTS:          return lowerShiftRightParts(Op, DAG, false);
1222   case ISD::LOAD:               return lowerLOAD(Op, DAG);
1223   case ISD::STORE:              return lowerSTORE(Op, DAG);
1224   case ISD::EH_DWARF_CFA:       return lowerEH_DWARF_CFA(Op, DAG);
1225   case ISD::FP_TO_SINT:         return lowerFP_TO_SINT(Op, DAG);
1226   }
1227   return SDValue();
1228 }
1229 
1230 //===----------------------------------------------------------------------===//
1231 //  Lower helper functions
1232 //===----------------------------------------------------------------------===//
1233 
1234 // addLiveIn - This helper function adds the specified physical register to the
1235 // MachineFunction as a live in value.  It also creates a corresponding
1236 // virtual register for it.
1237 static unsigned
1238 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1239 {
1240   Register VReg = MF.getRegInfo().createVirtualRegister(RC);
1241   MF.getRegInfo().addLiveIn(PReg, VReg);
1242   return VReg;
1243 }
1244 
1245 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr &MI,
1246                                               MachineBasicBlock &MBB,
1247                                               const TargetInstrInfo &TII,
1248                                               bool Is64Bit, bool IsMicroMips) {
1249   if (NoZeroDivCheck)
1250     return &MBB;
1251 
1252   // Insert instruction "teq $divisor_reg, $zero, 7".
1253   MachineBasicBlock::iterator I(MI);
1254   MachineInstrBuilder MIB;
1255   MachineOperand &Divisor = MI.getOperand(2);
1256   MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1257                 TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ))
1258             .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1259             .addReg(Mips::ZERO)
1260             .addImm(7);
1261 
1262   // Use the 32-bit sub-register if this is a 64-bit division.
1263   if (Is64Bit)
1264     MIB->getOperand(0).setSubReg(Mips::sub_32);
1265 
1266   // Clear Divisor's kill flag.
1267   Divisor.setIsKill(false);
1268 
1269   // We would normally delete the original instruction here but in this case
1270   // we only needed to inject an additional instruction rather than replace it.
1271 
1272   return &MBB;
1273 }
1274 
1275 MachineBasicBlock *
1276 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1277                                                 MachineBasicBlock *BB) const {
1278   switch (MI.getOpcode()) {
1279   default:
1280     llvm_unreachable("Unexpected instr type to insert");
1281   case Mips::ATOMIC_LOAD_ADD_I8:
1282     return emitAtomicBinaryPartword(MI, BB, 1);
1283   case Mips::ATOMIC_LOAD_ADD_I16:
1284     return emitAtomicBinaryPartword(MI, BB, 2);
1285   case Mips::ATOMIC_LOAD_ADD_I32:
1286     return emitAtomicBinary(MI, BB);
1287   case Mips::ATOMIC_LOAD_ADD_I64:
1288     return emitAtomicBinary(MI, BB);
1289 
1290   case Mips::ATOMIC_LOAD_AND_I8:
1291     return emitAtomicBinaryPartword(MI, BB, 1);
1292   case Mips::ATOMIC_LOAD_AND_I16:
1293     return emitAtomicBinaryPartword(MI, BB, 2);
1294   case Mips::ATOMIC_LOAD_AND_I32:
1295     return emitAtomicBinary(MI, BB);
1296   case Mips::ATOMIC_LOAD_AND_I64:
1297     return emitAtomicBinary(MI, BB);
1298 
1299   case Mips::ATOMIC_LOAD_OR_I8:
1300     return emitAtomicBinaryPartword(MI, BB, 1);
1301   case Mips::ATOMIC_LOAD_OR_I16:
1302     return emitAtomicBinaryPartword(MI, BB, 2);
1303   case Mips::ATOMIC_LOAD_OR_I32:
1304     return emitAtomicBinary(MI, BB);
1305   case Mips::ATOMIC_LOAD_OR_I64:
1306     return emitAtomicBinary(MI, BB);
1307 
1308   case Mips::ATOMIC_LOAD_XOR_I8:
1309     return emitAtomicBinaryPartword(MI, BB, 1);
1310   case Mips::ATOMIC_LOAD_XOR_I16:
1311     return emitAtomicBinaryPartword(MI, BB, 2);
1312   case Mips::ATOMIC_LOAD_XOR_I32:
1313     return emitAtomicBinary(MI, BB);
1314   case Mips::ATOMIC_LOAD_XOR_I64:
1315     return emitAtomicBinary(MI, BB);
1316 
1317   case Mips::ATOMIC_LOAD_NAND_I8:
1318     return emitAtomicBinaryPartword(MI, BB, 1);
1319   case Mips::ATOMIC_LOAD_NAND_I16:
1320     return emitAtomicBinaryPartword(MI, BB, 2);
1321   case Mips::ATOMIC_LOAD_NAND_I32:
1322     return emitAtomicBinary(MI, BB);
1323   case Mips::ATOMIC_LOAD_NAND_I64:
1324     return emitAtomicBinary(MI, BB);
1325 
1326   case Mips::ATOMIC_LOAD_SUB_I8:
1327     return emitAtomicBinaryPartword(MI, BB, 1);
1328   case Mips::ATOMIC_LOAD_SUB_I16:
1329     return emitAtomicBinaryPartword(MI, BB, 2);
1330   case Mips::ATOMIC_LOAD_SUB_I32:
1331     return emitAtomicBinary(MI, BB);
1332   case Mips::ATOMIC_LOAD_SUB_I64:
1333     return emitAtomicBinary(MI, BB);
1334 
1335   case Mips::ATOMIC_SWAP_I8:
1336     return emitAtomicBinaryPartword(MI, BB, 1);
1337   case Mips::ATOMIC_SWAP_I16:
1338     return emitAtomicBinaryPartword(MI, BB, 2);
1339   case Mips::ATOMIC_SWAP_I32:
1340     return emitAtomicBinary(MI, BB);
1341   case Mips::ATOMIC_SWAP_I64:
1342     return emitAtomicBinary(MI, BB);
1343 
1344   case Mips::ATOMIC_CMP_SWAP_I8:
1345     return emitAtomicCmpSwapPartword(MI, BB, 1);
1346   case Mips::ATOMIC_CMP_SWAP_I16:
1347     return emitAtomicCmpSwapPartword(MI, BB, 2);
1348   case Mips::ATOMIC_CMP_SWAP_I32:
1349     return emitAtomicCmpSwap(MI, BB);
1350   case Mips::ATOMIC_CMP_SWAP_I64:
1351     return emitAtomicCmpSwap(MI, BB);
1352 
1353   case Mips::ATOMIC_LOAD_MIN_I8:
1354     return emitAtomicBinaryPartword(MI, BB, 1);
1355   case Mips::ATOMIC_LOAD_MIN_I16:
1356     return emitAtomicBinaryPartword(MI, BB, 2);
1357   case Mips::ATOMIC_LOAD_MIN_I32:
1358     return emitAtomicBinary(MI, BB);
1359   case Mips::ATOMIC_LOAD_MIN_I64:
1360     return emitAtomicBinary(MI, BB);
1361 
1362   case Mips::ATOMIC_LOAD_MAX_I8:
1363     return emitAtomicBinaryPartword(MI, BB, 1);
1364   case Mips::ATOMIC_LOAD_MAX_I16:
1365     return emitAtomicBinaryPartword(MI, BB, 2);
1366   case Mips::ATOMIC_LOAD_MAX_I32:
1367     return emitAtomicBinary(MI, BB);
1368   case Mips::ATOMIC_LOAD_MAX_I64:
1369     return emitAtomicBinary(MI, BB);
1370 
1371   case Mips::ATOMIC_LOAD_UMIN_I8:
1372     return emitAtomicBinaryPartword(MI, BB, 1);
1373   case Mips::ATOMIC_LOAD_UMIN_I16:
1374     return emitAtomicBinaryPartword(MI, BB, 2);
1375   case Mips::ATOMIC_LOAD_UMIN_I32:
1376     return emitAtomicBinary(MI, BB);
1377   case Mips::ATOMIC_LOAD_UMIN_I64:
1378     return emitAtomicBinary(MI, BB);
1379 
1380   case Mips::ATOMIC_LOAD_UMAX_I8:
1381     return emitAtomicBinaryPartword(MI, BB, 1);
1382   case Mips::ATOMIC_LOAD_UMAX_I16:
1383     return emitAtomicBinaryPartword(MI, BB, 2);
1384   case Mips::ATOMIC_LOAD_UMAX_I32:
1385     return emitAtomicBinary(MI, BB);
1386   case Mips::ATOMIC_LOAD_UMAX_I64:
1387     return emitAtomicBinary(MI, BB);
1388 
1389   case Mips::PseudoSDIV:
1390   case Mips::PseudoUDIV:
1391   case Mips::DIV:
1392   case Mips::DIVU:
1393   case Mips::MOD:
1394   case Mips::MODU:
1395     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1396                                false);
1397   case Mips::SDIV_MM_Pseudo:
1398   case Mips::UDIV_MM_Pseudo:
1399   case Mips::SDIV_MM:
1400   case Mips::UDIV_MM:
1401   case Mips::DIV_MMR6:
1402   case Mips::DIVU_MMR6:
1403   case Mips::MOD_MMR6:
1404   case Mips::MODU_MMR6:
1405     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true);
1406   case Mips::PseudoDSDIV:
1407   case Mips::PseudoDUDIV:
1408   case Mips::DDIV:
1409   case Mips::DDIVU:
1410   case Mips::DMOD:
1411   case Mips::DMODU:
1412     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false);
1413 
1414   case Mips::PseudoSELECT_I:
1415   case Mips::PseudoSELECT_I64:
1416   case Mips::PseudoSELECT_S:
1417   case Mips::PseudoSELECT_D32:
1418   case Mips::PseudoSELECT_D64:
1419     return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1420   case Mips::PseudoSELECTFP_F_I:
1421   case Mips::PseudoSELECTFP_F_I64:
1422   case Mips::PseudoSELECTFP_F_S:
1423   case Mips::PseudoSELECTFP_F_D32:
1424   case Mips::PseudoSELECTFP_F_D64:
1425     return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1426   case Mips::PseudoSELECTFP_T_I:
1427   case Mips::PseudoSELECTFP_T_I64:
1428   case Mips::PseudoSELECTFP_T_S:
1429   case Mips::PseudoSELECTFP_T_D32:
1430   case Mips::PseudoSELECTFP_T_D64:
1431     return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1432   case Mips::PseudoD_SELECT_I:
1433   case Mips::PseudoD_SELECT_I64:
1434     return emitPseudoD_SELECT(MI, BB);
1435   case Mips::LDR_W:
1436     return emitLDR_W(MI, BB);
1437   case Mips::LDR_D:
1438     return emitLDR_D(MI, BB);
1439   case Mips::STR_W:
1440     return emitSTR_W(MI, BB);
1441   case Mips::STR_D:
1442     return emitSTR_D(MI, BB);
1443   }
1444 }
1445 
1446 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1447 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1448 MachineBasicBlock *
1449 MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1450                                      MachineBasicBlock *BB) const {
1451 
1452   MachineFunction *MF = BB->getParent();
1453   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1454   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1455   DebugLoc DL = MI.getDebugLoc();
1456 
1457   unsigned AtomicOp;
1458   bool NeedsAdditionalReg = false;
1459   switch (MI.getOpcode()) {
1460   case Mips::ATOMIC_LOAD_ADD_I32:
1461     AtomicOp = Mips::ATOMIC_LOAD_ADD_I32_POSTRA;
1462     break;
1463   case Mips::ATOMIC_LOAD_SUB_I32:
1464     AtomicOp = Mips::ATOMIC_LOAD_SUB_I32_POSTRA;
1465     break;
1466   case Mips::ATOMIC_LOAD_AND_I32:
1467     AtomicOp = Mips::ATOMIC_LOAD_AND_I32_POSTRA;
1468     break;
1469   case Mips::ATOMIC_LOAD_OR_I32:
1470     AtomicOp = Mips::ATOMIC_LOAD_OR_I32_POSTRA;
1471     break;
1472   case Mips::ATOMIC_LOAD_XOR_I32:
1473     AtomicOp = Mips::ATOMIC_LOAD_XOR_I32_POSTRA;
1474     break;
1475   case Mips::ATOMIC_LOAD_NAND_I32:
1476     AtomicOp = Mips::ATOMIC_LOAD_NAND_I32_POSTRA;
1477     break;
1478   case Mips::ATOMIC_SWAP_I32:
1479     AtomicOp = Mips::ATOMIC_SWAP_I32_POSTRA;
1480     break;
1481   case Mips::ATOMIC_LOAD_ADD_I64:
1482     AtomicOp = Mips::ATOMIC_LOAD_ADD_I64_POSTRA;
1483     break;
1484   case Mips::ATOMIC_LOAD_SUB_I64:
1485     AtomicOp = Mips::ATOMIC_LOAD_SUB_I64_POSTRA;
1486     break;
1487   case Mips::ATOMIC_LOAD_AND_I64:
1488     AtomicOp = Mips::ATOMIC_LOAD_AND_I64_POSTRA;
1489     break;
1490   case Mips::ATOMIC_LOAD_OR_I64:
1491     AtomicOp = Mips::ATOMIC_LOAD_OR_I64_POSTRA;
1492     break;
1493   case Mips::ATOMIC_LOAD_XOR_I64:
1494     AtomicOp = Mips::ATOMIC_LOAD_XOR_I64_POSTRA;
1495     break;
1496   case Mips::ATOMIC_LOAD_NAND_I64:
1497     AtomicOp = Mips::ATOMIC_LOAD_NAND_I64_POSTRA;
1498     break;
1499   case Mips::ATOMIC_SWAP_I64:
1500     AtomicOp = Mips::ATOMIC_SWAP_I64_POSTRA;
1501     break;
1502   case Mips::ATOMIC_LOAD_MIN_I32:
1503     AtomicOp = Mips::ATOMIC_LOAD_MIN_I32_POSTRA;
1504     NeedsAdditionalReg = true;
1505     break;
1506   case Mips::ATOMIC_LOAD_MAX_I32:
1507     AtomicOp = Mips::ATOMIC_LOAD_MAX_I32_POSTRA;
1508     NeedsAdditionalReg = true;
1509     break;
1510   case Mips::ATOMIC_LOAD_UMIN_I32:
1511     AtomicOp = Mips::ATOMIC_LOAD_UMIN_I32_POSTRA;
1512     NeedsAdditionalReg = true;
1513     break;
1514   case Mips::ATOMIC_LOAD_UMAX_I32:
1515     AtomicOp = Mips::ATOMIC_LOAD_UMAX_I32_POSTRA;
1516     NeedsAdditionalReg = true;
1517     break;
1518   case Mips::ATOMIC_LOAD_MIN_I64:
1519     AtomicOp = Mips::ATOMIC_LOAD_MIN_I64_POSTRA;
1520     NeedsAdditionalReg = true;
1521     break;
1522   case Mips::ATOMIC_LOAD_MAX_I64:
1523     AtomicOp = Mips::ATOMIC_LOAD_MAX_I64_POSTRA;
1524     NeedsAdditionalReg = true;
1525     break;
1526   case Mips::ATOMIC_LOAD_UMIN_I64:
1527     AtomicOp = Mips::ATOMIC_LOAD_UMIN_I64_POSTRA;
1528     NeedsAdditionalReg = true;
1529     break;
1530   case Mips::ATOMIC_LOAD_UMAX_I64:
1531     AtomicOp = Mips::ATOMIC_LOAD_UMAX_I64_POSTRA;
1532     NeedsAdditionalReg = true;
1533     break;
1534   default:
1535     llvm_unreachable("Unknown pseudo atomic for replacement!");
1536   }
1537 
1538   Register OldVal = MI.getOperand(0).getReg();
1539   Register Ptr = MI.getOperand(1).getReg();
1540   Register Incr = MI.getOperand(2).getReg();
1541   Register Scratch = RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1542 
1543   MachineBasicBlock::iterator II(MI);
1544 
1545   // The scratch registers here with the EarlyClobber | Define | Implicit
1546   // flags is used to persuade the register allocator and the machine
1547   // verifier to accept the usage of this register. This has to be a real
1548   // register which has an UNDEF value but is dead after the instruction which
1549   // is unique among the registers chosen for the instruction.
1550 
1551   // The EarlyClobber flag has the semantic properties that the operand it is
1552   // attached to is clobbered before the rest of the inputs are read. Hence it
1553   // must be unique among the operands to the instruction.
1554   // The Define flag is needed to coerce the machine verifier that an Undef
1555   // value isn't a problem.
1556   // The Dead flag is needed as the value in scratch isn't used by any other
1557   // instruction. Kill isn't used as Dead is more precise.
1558   // The implicit flag is here due to the interaction between the other flags
1559   // and the machine verifier.
1560 
1561   // For correctness purpose, a new pseudo is introduced here. We need this
1562   // new pseudo, so that FastRegisterAllocator does not see an ll/sc sequence
1563   // that is spread over >1 basic blocks. A register allocator which
1564   // introduces (or any codegen infact) a store, can violate the expectations
1565   // of the hardware.
1566   //
1567   // An atomic read-modify-write sequence starts with a linked load
1568   // instruction and ends with a store conditional instruction. The atomic
1569   // read-modify-write sequence fails if any of the following conditions
1570   // occur between the execution of ll and sc:
1571   //   * A coherent store is completed by another process or coherent I/O
1572   //     module into the block of synchronizable physical memory containing
1573   //     the word. The size and alignment of the block is
1574   //     implementation-dependent.
1575   //   * A coherent store is executed between an LL and SC sequence on the
1576   //     same processor to the block of synchornizable physical memory
1577   //     containing the word.
1578   //
1579 
1580   Register PtrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Ptr));
1581   Register IncrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Incr));
1582 
1583   BuildMI(*BB, II, DL, TII->get(Mips::COPY), IncrCopy).addReg(Incr);
1584   BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1585 
1586   MachineInstrBuilder MIB =
1587       BuildMI(*BB, II, DL, TII->get(AtomicOp))
1588           .addReg(OldVal, RegState::Define | RegState::EarlyClobber)
1589           .addReg(PtrCopy)
1590           .addReg(IncrCopy)
1591           .addReg(Scratch, RegState::Define | RegState::EarlyClobber |
1592                                RegState::Implicit | RegState::Dead);
1593   if (NeedsAdditionalReg) {
1594     Register Scratch2 =
1595         RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1596     MIB.addReg(Scratch2, RegState::Define | RegState::EarlyClobber |
1597                              RegState::Implicit | RegState::Dead);
1598   }
1599 
1600   MI.eraseFromParent();
1601 
1602   return BB;
1603 }
1604 
1605 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1606     MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1607     unsigned SrcReg) const {
1608   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1609   const DebugLoc &DL = MI.getDebugLoc();
1610 
1611   if (Subtarget.hasMips32r2() && Size == 1) {
1612     BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1613     return BB;
1614   }
1615 
1616   if (Subtarget.hasMips32r2() && Size == 2) {
1617     BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1618     return BB;
1619   }
1620 
1621   MachineFunction *MF = BB->getParent();
1622   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1623   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1624   Register ScrReg = RegInfo.createVirtualRegister(RC);
1625 
1626   assert(Size < 32);
1627   int64_t ShiftImm = 32 - (Size * 8);
1628 
1629   BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1630   BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1631 
1632   return BB;
1633 }
1634 
1635 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1636     MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1637   assert((Size == 1 || Size == 2) &&
1638          "Unsupported size for EmitAtomicBinaryPartial.");
1639 
1640   MachineFunction *MF = BB->getParent();
1641   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1642   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1643   const bool ArePtrs64bit = ABI.ArePtrs64bit();
1644   const TargetRegisterClass *RCp =
1645     getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1646   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1647   DebugLoc DL = MI.getDebugLoc();
1648 
1649   Register Dest = MI.getOperand(0).getReg();
1650   Register Ptr = MI.getOperand(1).getReg();
1651   Register Incr = MI.getOperand(2).getReg();
1652 
1653   Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1654   Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1655   Register Mask = RegInfo.createVirtualRegister(RC);
1656   Register Mask2 = RegInfo.createVirtualRegister(RC);
1657   Register Incr2 = RegInfo.createVirtualRegister(RC);
1658   Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1659   Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1660   Register MaskUpper = RegInfo.createVirtualRegister(RC);
1661   Register Scratch = RegInfo.createVirtualRegister(RC);
1662   Register Scratch2 = RegInfo.createVirtualRegister(RC);
1663   Register Scratch3 = RegInfo.createVirtualRegister(RC);
1664 
1665   unsigned AtomicOp = 0;
1666   bool NeedsAdditionalReg = false;
1667   switch (MI.getOpcode()) {
1668   case Mips::ATOMIC_LOAD_NAND_I8:
1669     AtomicOp = Mips::ATOMIC_LOAD_NAND_I8_POSTRA;
1670     break;
1671   case Mips::ATOMIC_LOAD_NAND_I16:
1672     AtomicOp = Mips::ATOMIC_LOAD_NAND_I16_POSTRA;
1673     break;
1674   case Mips::ATOMIC_SWAP_I8:
1675     AtomicOp = Mips::ATOMIC_SWAP_I8_POSTRA;
1676     break;
1677   case Mips::ATOMIC_SWAP_I16:
1678     AtomicOp = Mips::ATOMIC_SWAP_I16_POSTRA;
1679     break;
1680   case Mips::ATOMIC_LOAD_ADD_I8:
1681     AtomicOp = Mips::ATOMIC_LOAD_ADD_I8_POSTRA;
1682     break;
1683   case Mips::ATOMIC_LOAD_ADD_I16:
1684     AtomicOp = Mips::ATOMIC_LOAD_ADD_I16_POSTRA;
1685     break;
1686   case Mips::ATOMIC_LOAD_SUB_I8:
1687     AtomicOp = Mips::ATOMIC_LOAD_SUB_I8_POSTRA;
1688     break;
1689   case Mips::ATOMIC_LOAD_SUB_I16:
1690     AtomicOp = Mips::ATOMIC_LOAD_SUB_I16_POSTRA;
1691     break;
1692   case Mips::ATOMIC_LOAD_AND_I8:
1693     AtomicOp = Mips::ATOMIC_LOAD_AND_I8_POSTRA;
1694     break;
1695   case Mips::ATOMIC_LOAD_AND_I16:
1696     AtomicOp = Mips::ATOMIC_LOAD_AND_I16_POSTRA;
1697     break;
1698   case Mips::ATOMIC_LOAD_OR_I8:
1699     AtomicOp = Mips::ATOMIC_LOAD_OR_I8_POSTRA;
1700     break;
1701   case Mips::ATOMIC_LOAD_OR_I16:
1702     AtomicOp = Mips::ATOMIC_LOAD_OR_I16_POSTRA;
1703     break;
1704   case Mips::ATOMIC_LOAD_XOR_I8:
1705     AtomicOp = Mips::ATOMIC_LOAD_XOR_I8_POSTRA;
1706     break;
1707   case Mips::ATOMIC_LOAD_XOR_I16:
1708     AtomicOp = Mips::ATOMIC_LOAD_XOR_I16_POSTRA;
1709     break;
1710   case Mips::ATOMIC_LOAD_MIN_I8:
1711     AtomicOp = Mips::ATOMIC_LOAD_MIN_I8_POSTRA;
1712     NeedsAdditionalReg = true;
1713     break;
1714   case Mips::ATOMIC_LOAD_MIN_I16:
1715     AtomicOp = Mips::ATOMIC_LOAD_MIN_I16_POSTRA;
1716     NeedsAdditionalReg = true;
1717     break;
1718   case Mips::ATOMIC_LOAD_MAX_I8:
1719     AtomicOp = Mips::ATOMIC_LOAD_MAX_I8_POSTRA;
1720     NeedsAdditionalReg = true;
1721     break;
1722   case Mips::ATOMIC_LOAD_MAX_I16:
1723     AtomicOp = Mips::ATOMIC_LOAD_MAX_I16_POSTRA;
1724     NeedsAdditionalReg = true;
1725     break;
1726   case Mips::ATOMIC_LOAD_UMIN_I8:
1727     AtomicOp = Mips::ATOMIC_LOAD_UMIN_I8_POSTRA;
1728     NeedsAdditionalReg = true;
1729     break;
1730   case Mips::ATOMIC_LOAD_UMIN_I16:
1731     AtomicOp = Mips::ATOMIC_LOAD_UMIN_I16_POSTRA;
1732     NeedsAdditionalReg = true;
1733     break;
1734   case Mips::ATOMIC_LOAD_UMAX_I8:
1735     AtomicOp = Mips::ATOMIC_LOAD_UMAX_I8_POSTRA;
1736     NeedsAdditionalReg = true;
1737     break;
1738   case Mips::ATOMIC_LOAD_UMAX_I16:
1739     AtomicOp = Mips::ATOMIC_LOAD_UMAX_I16_POSTRA;
1740     NeedsAdditionalReg = true;
1741     break;
1742   default:
1743     llvm_unreachable("Unknown subword atomic pseudo for expansion!");
1744   }
1745 
1746   // insert new blocks after the current block
1747   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1748   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1749   MachineFunction::iterator It = ++BB->getIterator();
1750   MF->insert(It, exitMBB);
1751 
1752   // Transfer the remainder of BB and its successor edges to exitMBB.
1753   exitMBB->splice(exitMBB->begin(), BB,
1754                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1755   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1756 
1757   BB->addSuccessor(exitMBB, BranchProbability::getOne());
1758 
1759   //  thisMBB:
1760   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1761   //    and     alignedaddr,ptr,masklsb2
1762   //    andi    ptrlsb2,ptr,3
1763   //    sll     shiftamt,ptrlsb2,3
1764   //    ori     maskupper,$0,255               # 0xff
1765   //    sll     mask,maskupper,shiftamt
1766   //    nor     mask2,$0,mask
1767   //    sll     incr2,incr,shiftamt
1768 
1769   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1770   BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1771     .addReg(ABI.GetNullPtr()).addImm(-4);
1772   BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1773     .addReg(Ptr).addReg(MaskLSB2);
1774   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1775       .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1776   if (Subtarget.isLittle()) {
1777     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1778   } else {
1779     Register Off = RegInfo.createVirtualRegister(RC);
1780     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1781       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1782     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1783   }
1784   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1785     .addReg(Mips::ZERO).addImm(MaskImm);
1786   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1787     .addReg(MaskUpper).addReg(ShiftAmt);
1788   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1789   BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1790 
1791 
1792   // The purposes of the flags on the scratch registers is explained in
1793   // emitAtomicBinary. In summary, we need a scratch register which is going to
1794   // be undef, that is unique among registers chosen for the instruction.
1795 
1796   MachineInstrBuilder MIB =
1797       BuildMI(BB, DL, TII->get(AtomicOp))
1798           .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1799           .addReg(AlignedAddr)
1800           .addReg(Incr2)
1801           .addReg(Mask)
1802           .addReg(Mask2)
1803           .addReg(ShiftAmt)
1804           .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
1805                                RegState::Dead | RegState::Implicit)
1806           .addReg(Scratch2, RegState::EarlyClobber | RegState::Define |
1807                                 RegState::Dead | RegState::Implicit)
1808           .addReg(Scratch3, RegState::EarlyClobber | RegState::Define |
1809                                 RegState::Dead | RegState::Implicit);
1810   if (NeedsAdditionalReg) {
1811     Register Scratch4 = RegInfo.createVirtualRegister(RC);
1812     MIB.addReg(Scratch4, RegState::EarlyClobber | RegState::Define |
1813                              RegState::Dead | RegState::Implicit);
1814   }
1815 
1816   MI.eraseFromParent(); // The instruction is gone now.
1817 
1818   return exitMBB;
1819 }
1820 
1821 // Lower atomic compare and swap to a pseudo instruction, taking care to
1822 // define a scratch register for the pseudo instruction's expansion. The
1823 // instruction is expanded after the register allocator as to prevent
1824 // the insertion of stores between the linked load and the store conditional.
1825 
1826 MachineBasicBlock *
1827 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1828                                       MachineBasicBlock *BB) const {
1829 
1830   assert((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ||
1831           MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) &&
1832          "Unsupported atomic pseudo for EmitAtomicCmpSwap.");
1833 
1834   const unsigned Size = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ? 4 : 8;
1835 
1836   MachineFunction *MF = BB->getParent();
1837   MachineRegisterInfo &MRI = MF->getRegInfo();
1838   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1839   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1840   DebugLoc DL = MI.getDebugLoc();
1841 
1842   unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
1843                           ? Mips::ATOMIC_CMP_SWAP_I32_POSTRA
1844                           : Mips::ATOMIC_CMP_SWAP_I64_POSTRA;
1845   Register Dest = MI.getOperand(0).getReg();
1846   Register Ptr = MI.getOperand(1).getReg();
1847   Register OldVal = MI.getOperand(2).getReg();
1848   Register NewVal = MI.getOperand(3).getReg();
1849 
1850   Register Scratch = MRI.createVirtualRegister(RC);
1851   MachineBasicBlock::iterator II(MI);
1852 
1853   // We need to create copies of the various registers and kill them at the
1854   // atomic pseudo. If the copies are not made, when the atomic is expanded
1855   // after fast register allocation, the spills will end up outside of the
1856   // blocks that their values are defined in, causing livein errors.
1857 
1858   Register PtrCopy = MRI.createVirtualRegister(MRI.getRegClass(Ptr));
1859   Register OldValCopy = MRI.createVirtualRegister(MRI.getRegClass(OldVal));
1860   Register NewValCopy = MRI.createVirtualRegister(MRI.getRegClass(NewVal));
1861 
1862   BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1863   BuildMI(*BB, II, DL, TII->get(Mips::COPY), OldValCopy).addReg(OldVal);
1864   BuildMI(*BB, II, DL, TII->get(Mips::COPY), NewValCopy).addReg(NewVal);
1865 
1866   // The purposes of the flags on the scratch registers is explained in
1867   // emitAtomicBinary. In summary, we need a scratch register which is going to
1868   // be undef, that is unique among registers chosen for the instruction.
1869 
1870   BuildMI(*BB, II, DL, TII->get(AtomicOp))
1871       .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1872       .addReg(PtrCopy, RegState::Kill)
1873       .addReg(OldValCopy, RegState::Kill)
1874       .addReg(NewValCopy, RegState::Kill)
1875       .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
1876                            RegState::Dead | RegState::Implicit);
1877 
1878   MI.eraseFromParent(); // The instruction is gone now.
1879 
1880   return BB;
1881 }
1882 
1883 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1884     MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1885   assert((Size == 1 || Size == 2) &&
1886       "Unsupported size for EmitAtomicCmpSwapPartial.");
1887 
1888   MachineFunction *MF = BB->getParent();
1889   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1890   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1891   const bool ArePtrs64bit = ABI.ArePtrs64bit();
1892   const TargetRegisterClass *RCp =
1893     getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1894   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1895   DebugLoc DL = MI.getDebugLoc();
1896 
1897   Register Dest = MI.getOperand(0).getReg();
1898   Register Ptr = MI.getOperand(1).getReg();
1899   Register CmpVal = MI.getOperand(2).getReg();
1900   Register NewVal = MI.getOperand(3).getReg();
1901 
1902   Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1903   Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1904   Register Mask = RegInfo.createVirtualRegister(RC);
1905   Register Mask2 = RegInfo.createVirtualRegister(RC);
1906   Register ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1907   Register ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1908   Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1909   Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1910   Register MaskUpper = RegInfo.createVirtualRegister(RC);
1911   Register MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1912   Register MaskedNewVal = RegInfo.createVirtualRegister(RC);
1913   unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I8
1914                           ? Mips::ATOMIC_CMP_SWAP_I8_POSTRA
1915                           : Mips::ATOMIC_CMP_SWAP_I16_POSTRA;
1916 
1917   // The scratch registers here with the EarlyClobber | Define | Dead | Implicit
1918   // flags are used to coerce the register allocator and the machine verifier to
1919   // accept the usage of these registers.
1920   // The EarlyClobber flag has the semantic properties that the operand it is
1921   // attached to is clobbered before the rest of the inputs are read. Hence it
1922   // must be unique among the operands to the instruction.
1923   // The Define flag is needed to coerce the machine verifier that an Undef
1924   // value isn't a problem.
1925   // The Dead flag is needed as the value in scratch isn't used by any other
1926   // instruction. Kill isn't used as Dead is more precise.
1927   Register Scratch = RegInfo.createVirtualRegister(RC);
1928   Register Scratch2 = RegInfo.createVirtualRegister(RC);
1929 
1930   // insert new blocks after the current block
1931   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1932   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1933   MachineFunction::iterator It = ++BB->getIterator();
1934   MF->insert(It, exitMBB);
1935 
1936   // Transfer the remainder of BB and its successor edges to exitMBB.
1937   exitMBB->splice(exitMBB->begin(), BB,
1938                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1939   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1940 
1941   BB->addSuccessor(exitMBB, BranchProbability::getOne());
1942 
1943   //  thisMBB:
1944   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1945   //    and     alignedaddr,ptr,masklsb2
1946   //    andi    ptrlsb2,ptr,3
1947   //    xori    ptrlsb2,ptrlsb2,3              # Only for BE
1948   //    sll     shiftamt,ptrlsb2,3
1949   //    ori     maskupper,$0,255               # 0xff
1950   //    sll     mask,maskupper,shiftamt
1951   //    nor     mask2,$0,mask
1952   //    andi    maskedcmpval,cmpval,255
1953   //    sll     shiftedcmpval,maskedcmpval,shiftamt
1954   //    andi    maskednewval,newval,255
1955   //    sll     shiftednewval,maskednewval,shiftamt
1956   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1957   BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1958     .addReg(ABI.GetNullPtr()).addImm(-4);
1959   BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1960     .addReg(Ptr).addReg(MaskLSB2);
1961   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1962       .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1963   if (Subtarget.isLittle()) {
1964     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1965   } else {
1966     Register Off = RegInfo.createVirtualRegister(RC);
1967     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1968       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1969     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1970   }
1971   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1972     .addReg(Mips::ZERO).addImm(MaskImm);
1973   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1974     .addReg(MaskUpper).addReg(ShiftAmt);
1975   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1976   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1977     .addReg(CmpVal).addImm(MaskImm);
1978   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1979     .addReg(MaskedCmpVal).addReg(ShiftAmt);
1980   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1981     .addReg(NewVal).addImm(MaskImm);
1982   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1983     .addReg(MaskedNewVal).addReg(ShiftAmt);
1984 
1985   // The purposes of the flags on the scratch registers are explained in
1986   // emitAtomicBinary. In summary, we need a scratch register which is going to
1987   // be undef, that is unique among the register chosen for the instruction.
1988 
1989   BuildMI(BB, DL, TII->get(AtomicOp))
1990       .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1991       .addReg(AlignedAddr)
1992       .addReg(Mask)
1993       .addReg(ShiftedCmpVal)
1994       .addReg(Mask2)
1995       .addReg(ShiftedNewVal)
1996       .addReg(ShiftAmt)
1997       .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
1998                            RegState::Dead | RegState::Implicit)
1999       .addReg(Scratch2, RegState::EarlyClobber | RegState::Define |
2000                             RegState::Dead | RegState::Implicit);
2001 
2002   MI.eraseFromParent(); // The instruction is gone now.
2003 
2004   return exitMBB;
2005 }
2006 
2007 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
2008   // The first operand is the chain, the second is the condition, the third is
2009   // the block to branch to if the condition is true.
2010   SDValue Chain = Op.getOperand(0);
2011   SDValue Dest = Op.getOperand(2);
2012   SDLoc DL(Op);
2013 
2014   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2015   SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
2016 
2017   // Return if flag is not set by a floating point comparison.
2018   if (CondRes.getOpcode() != MipsISD::FPCmp)
2019     return Op;
2020 
2021   SDValue CCNode  = CondRes.getOperand(2);
2022   Mips::CondCode CC =
2023     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
2024   unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
2025   SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
2026   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
2027   return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
2028                      FCC0, Dest, CondRes);
2029 }
2030 
2031 SDValue MipsTargetLowering::
2032 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
2033 {
2034   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2035   SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
2036 
2037   // Return if flag is not set by a floating point comparison.
2038   if (Cond.getOpcode() != MipsISD::FPCmp)
2039     return Op;
2040 
2041   return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2042                       SDLoc(Op));
2043 }
2044 
2045 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2046   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2047   SDValue Cond = createFPCmp(DAG, Op);
2048 
2049   assert(Cond.getOpcode() == MipsISD::FPCmp &&
2050          "Floating point operand expected.");
2051 
2052   SDLoc DL(Op);
2053   SDValue True  = DAG.getConstant(1, DL, MVT::i32);
2054   SDValue False = DAG.getConstant(0, DL, MVT::i32);
2055 
2056   return createCMovFP(DAG, Cond, True, False, DL);
2057 }
2058 
2059 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
2060                                                SelectionDAG &DAG) const {
2061   EVT Ty = Op.getValueType();
2062   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2063   const GlobalValue *GV = N->getGlobal();
2064 
2065   if (!isPositionIndependent()) {
2066     const MipsTargetObjectFile *TLOF =
2067         static_cast<const MipsTargetObjectFile *>(
2068             getTargetMachine().getObjFileLowering());
2069     const GlobalObject *GO = GV->getAliaseeObject();
2070     if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
2071       // %gp_rel relocation
2072       return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2073 
2074                                 // %hi/%lo relocation
2075     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2076                                 // %highest/%higher/%hi/%lo relocation
2077                                 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2078   }
2079 
2080   // Every other architecture would use shouldAssumeDSOLocal in here, but
2081   // mips is special.
2082   // * In PIC code mips requires got loads even for local statics!
2083   // * To save on got entries, for local statics the got entry contains the
2084   //   page and an additional add instruction takes care of the low bits.
2085   // * It is legal to access a hidden symbol with a non hidden undefined,
2086   //   so one cannot guarantee that all access to a hidden symbol will know
2087   //   it is hidden.
2088   // * Mips linkers don't support creating a page and a full got entry for
2089   //   the same symbol.
2090   // * Given all that, we have to use a full got entry for hidden symbols :-(
2091   if (GV->hasLocalLinkage())
2092     return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2093 
2094   if (Subtarget.useXGOT())
2095     return getAddrGlobalLargeGOT(
2096         N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
2097         DAG.getEntryNode(),
2098         MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2099 
2100   return getAddrGlobal(
2101       N, SDLoc(N), Ty, DAG,
2102       (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT,
2103       DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2104 }
2105 
2106 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2107                                               SelectionDAG &DAG) const {
2108   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2109   EVT Ty = Op.getValueType();
2110 
2111   if (!isPositionIndependent())
2112     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2113                                 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2114 
2115   return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2116 }
2117 
2118 SDValue MipsTargetLowering::
2119 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2120 {
2121   // If the relocation model is PIC, use the General Dynamic TLS Model or
2122   // Local Dynamic TLS model, otherwise use the Initial Exec or
2123   // Local Exec TLS Model.
2124 
2125   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2126   if (DAG.getTarget().useEmulatedTLS())
2127     return LowerToTLSEmulatedModel(GA, DAG);
2128 
2129   SDLoc DL(GA);
2130   const GlobalValue *GV = GA->getGlobal();
2131   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2132 
2133   TLSModel::Model model = getTargetMachine().getTLSModel(GV);
2134 
2135   if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2136     // General Dynamic and Local Dynamic TLS Model.
2137     unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2138                                                       : MipsII::MO_TLSGD;
2139 
2140     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2141     SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2142                                    getGlobalReg(DAG, PtrVT), TGA);
2143     unsigned PtrSize = PtrVT.getSizeInBits();
2144     IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2145 
2146     SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2147 
2148     ArgListTy Args;
2149     ArgListEntry Entry;
2150     Entry.Node = Argument;
2151     Entry.Ty = PtrTy;
2152     Args.push_back(Entry);
2153 
2154     TargetLowering::CallLoweringInfo CLI(DAG);
2155     CLI.setDebugLoc(DL)
2156         .setChain(DAG.getEntryNode())
2157         .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2158     std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2159 
2160     SDValue Ret = CallResult.first;
2161 
2162     if (model != TLSModel::LocalDynamic)
2163       return Ret;
2164 
2165     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2166                                                MipsII::MO_DTPREL_HI);
2167     SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2168     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2169                                                MipsII::MO_DTPREL_LO);
2170     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2171     SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2172     return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2173   }
2174 
2175   SDValue Offset;
2176   if (model == TLSModel::InitialExec) {
2177     // Initial Exec TLS Model
2178     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2179                                              MipsII::MO_GOTTPREL);
2180     TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2181                       TGA);
2182     Offset =
2183         DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2184   } else {
2185     // Local Exec TLS Model
2186     assert(model == TLSModel::LocalExec);
2187     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2188                                                MipsII::MO_TPREL_HI);
2189     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2190                                                MipsII::MO_TPREL_LO);
2191     SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2192     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2193     Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2194   }
2195 
2196   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2197   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2198 }
2199 
2200 SDValue MipsTargetLowering::
2201 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2202 {
2203   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2204   EVT Ty = Op.getValueType();
2205 
2206   if (!isPositionIndependent())
2207     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2208                                 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2209 
2210   return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2211 }
2212 
2213 SDValue MipsTargetLowering::
2214 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2215 {
2216   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2217   EVT Ty = Op.getValueType();
2218 
2219   if (!isPositionIndependent()) {
2220     const MipsTargetObjectFile *TLOF =
2221         static_cast<const MipsTargetObjectFile *>(
2222             getTargetMachine().getObjFileLowering());
2223 
2224     if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2225                                        getTargetMachine()))
2226       // %gp_rel relocation
2227       return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2228 
2229     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2230                                 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2231   }
2232 
2233  return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2234 }
2235 
2236 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2237   MachineFunction &MF = DAG.getMachineFunction();
2238   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2239 
2240   SDLoc DL(Op);
2241   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2242                                  getPointerTy(MF.getDataLayout()));
2243 
2244   // vastart just stores the address of the VarArgsFrameIndex slot into the
2245   // memory location argument.
2246   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2247   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2248                       MachinePointerInfo(SV));
2249 }
2250 
2251 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2252   SDNode *Node = Op.getNode();
2253   EVT VT = Node->getValueType(0);
2254   SDValue Chain = Node->getOperand(0);
2255   SDValue VAListPtr = Node->getOperand(1);
2256   const Align Align =
2257       llvm::MaybeAlign(Node->getConstantOperandVal(3)).valueOrOne();
2258   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2259   SDLoc DL(Node);
2260   unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2261 
2262   SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2263                                    VAListPtr, MachinePointerInfo(SV));
2264   SDValue VAList = VAListLoad;
2265 
2266   // Re-align the pointer if necessary.
2267   // It should only ever be necessary for 64-bit types on O32 since the minimum
2268   // argument alignment is the same as the maximum type alignment for N32/N64.
2269   //
2270   // FIXME: We currently align too often. The code generator doesn't notice
2271   //        when the pointer is still aligned from the last va_arg (or pair of
2272   //        va_args for the i64 on O32 case).
2273   if (Align > getMinStackArgumentAlignment()) {
2274     VAList = DAG.getNode(
2275         ISD::ADD, DL, VAList.getValueType(), VAList,
2276         DAG.getConstant(Align.value() - 1, DL, VAList.getValueType()));
2277 
2278     VAList = DAG.getNode(
2279         ISD::AND, DL, VAList.getValueType(), VAList,
2280         DAG.getConstant(-(int64_t)Align.value(), DL, VAList.getValueType()));
2281   }
2282 
2283   // Increment the pointer, VAList, to the next vaarg.
2284   auto &TD = DAG.getDataLayout();
2285   unsigned ArgSizeInBytes =
2286       TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
2287   SDValue Tmp3 =
2288       DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2289                   DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2290                                   DL, VAList.getValueType()));
2291   // Store the incremented VAList to the legalized pointer
2292   Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2293                        MachinePointerInfo(SV));
2294 
2295   // In big-endian mode we must adjust the pointer when the load size is smaller
2296   // than the argument slot size. We must also reduce the known alignment to
2297   // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2298   // the correct half of the slot, and reduce the alignment from 8 (slot
2299   // alignment) down to 4 (type alignment).
2300   if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2301     unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2302     VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2303                          DAG.getIntPtrConstant(Adjustment, DL));
2304   }
2305   // Load the actual argument out of the pointer VAList
2306   return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2307 }
2308 
2309 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
2310                                 bool HasExtractInsert) {
2311   EVT TyX = Op.getOperand(0).getValueType();
2312   EVT TyY = Op.getOperand(1).getValueType();
2313   SDLoc DL(Op);
2314   SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2315   SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2316   SDValue Res;
2317 
2318   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2319   // to i32.
2320   SDValue X = (TyX == MVT::f32) ?
2321     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2322     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2323                 Const1);
2324   SDValue Y = (TyY == MVT::f32) ?
2325     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2326     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2327                 Const1);
2328 
2329   if (HasExtractInsert) {
2330     // ext  E, Y, 31, 1  ; extract bit31 of Y
2331     // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
2332     SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2333     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2334   } else {
2335     // sll SllX, X, 1
2336     // srl SrlX, SllX, 1
2337     // srl SrlY, Y, 31
2338     // sll SllY, SrlX, 31
2339     // or  Or, SrlX, SllY
2340     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2341     SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2342     SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2343     SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2344     Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2345   }
2346 
2347   if (TyX == MVT::f32)
2348     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2349 
2350   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2351                              Op.getOperand(0),
2352                              DAG.getConstant(0, DL, MVT::i32));
2353   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2354 }
2355 
2356 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
2357                                 bool HasExtractInsert) {
2358   unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2359   unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2360   EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2361   SDLoc DL(Op);
2362   SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2363 
2364   // Bitcast to integer nodes.
2365   SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2366   SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2367 
2368   if (HasExtractInsert) {
2369     // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
2370     // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
2371     SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2372                             DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2373 
2374     if (WidthX > WidthY)
2375       E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2376     else if (WidthY > WidthX)
2377       E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2378 
2379     SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2380                             DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2381                             X);
2382     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2383   }
2384 
2385   // (d)sll SllX, X, 1
2386   // (d)srl SrlX, SllX, 1
2387   // (d)srl SrlY, Y, width(Y)-1
2388   // (d)sll SllY, SrlX, width(Y)-1
2389   // or     Or, SrlX, SllY
2390   SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2391   SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2392   SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2393                              DAG.getConstant(WidthY - 1, DL, MVT::i32));
2394 
2395   if (WidthX > WidthY)
2396     SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2397   else if (WidthY > WidthX)
2398     SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2399 
2400   SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2401                              DAG.getConstant(WidthX - 1, DL, MVT::i32));
2402   SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2403   return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2404 }
2405 
2406 SDValue
2407 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2408   if (Subtarget.isGP64bit())
2409     return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2410 
2411   return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2412 }
2413 
2414 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG,
2415                            bool HasExtractInsert) {
2416   SDLoc DL(Op);
2417   SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2418 
2419   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2420   // to i32.
2421   SDValue X = (Op.getValueType() == MVT::f32)
2422                   ? DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0))
2423                   : DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2424                                 Op.getOperand(0), Const1);
2425 
2426   // Clear MSB.
2427   if (HasExtractInsert)
2428     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2429                       DAG.getRegister(Mips::ZERO, MVT::i32),
2430                       DAG.getConstant(31, DL, MVT::i32), Const1, X);
2431   else {
2432     // TODO: Provide DAG patterns which transform (and x, cst)
2433     // back to a (shl (srl x (clz cst)) (clz cst)) sequence.
2434     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2435     Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2436   }
2437 
2438   if (Op.getValueType() == MVT::f32)
2439     return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2440 
2441   // FIXME: For mips32r2, the sequence of (BuildPairF64 (ins (ExtractElementF64
2442   // Op 1), $zero, 31 1) (ExtractElementF64 Op 0)) and the Op has one use, we
2443   // should be able to drop the usage of mfc1/mtc1 and rewrite the register in
2444   // place.
2445   SDValue LowX =
2446       DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2447                   DAG.getConstant(0, DL, MVT::i32));
2448   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2449 }
2450 
2451 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG,
2452                            bool HasExtractInsert) {
2453   SDLoc DL(Op);
2454   SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2455 
2456   // Bitcast to integer node.
2457   SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2458 
2459   // Clear MSB.
2460   if (HasExtractInsert)
2461     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2462                       DAG.getRegister(Mips::ZERO_64, MVT::i64),
2463                       DAG.getConstant(63, DL, MVT::i32), Const1, X);
2464   else {
2465     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2466     Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2467   }
2468 
2469   return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2470 }
2471 
2472 SDValue MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
2473   if ((ABI.IsN32() || ABI.IsN64()) && (Op.getValueType() == MVT::f64))
2474     return lowerFABS64(Op, DAG, Subtarget.hasExtractInsert());
2475 
2476   return lowerFABS32(Op, DAG, Subtarget.hasExtractInsert());
2477 }
2478 
2479 SDValue MipsTargetLowering::
2480 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2481   // check the depth
2482   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2483     DAG.getContext()->emitError(
2484         "return address can be determined only for current frame");
2485     return SDValue();
2486   }
2487 
2488   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2489   MFI.setFrameAddressIsTaken(true);
2490   EVT VT = Op.getValueType();
2491   SDLoc DL(Op);
2492   SDValue FrameAddr = DAG.getCopyFromReg(
2493       DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2494   return FrameAddr;
2495 }
2496 
2497 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2498                                             SelectionDAG &DAG) const {
2499   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2500     return SDValue();
2501 
2502   // check the depth
2503   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2504     DAG.getContext()->emitError(
2505         "return address can be determined only for current frame");
2506     return SDValue();
2507   }
2508 
2509   MachineFunction &MF = DAG.getMachineFunction();
2510   MachineFrameInfo &MFI = MF.getFrameInfo();
2511   MVT VT = Op.getSimpleValueType();
2512   unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2513   MFI.setReturnAddressIsTaken(true);
2514 
2515   // Return RA, which contains the return address. Mark it an implicit live-in.
2516   Register Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2517   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2518 }
2519 
2520 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2521 // generated from __builtin_eh_return (offset, handler)
2522 // The effect of this is to adjust the stack pointer by "offset"
2523 // and then branch to "handler".
2524 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2525                                                                      const {
2526   MachineFunction &MF = DAG.getMachineFunction();
2527   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2528 
2529   MipsFI->setCallsEhReturn();
2530   SDValue Chain     = Op.getOperand(0);
2531   SDValue Offset    = Op.getOperand(1);
2532   SDValue Handler   = Op.getOperand(2);
2533   SDLoc DL(Op);
2534   EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2535 
2536   // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2537   // EH_RETURN nodes, so that instructions are emitted back-to-back.
2538   unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2539   unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2540   Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2541   Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2542   return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2543                      DAG.getRegister(OffsetReg, Ty),
2544                      DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2545                      Chain.getValue(1));
2546 }
2547 
2548 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2549                                               SelectionDAG &DAG) const {
2550   // FIXME: Need pseudo-fence for 'singlethread' fences
2551   // FIXME: Set SType for weaker fences where supported/appropriate.
2552   unsigned SType = 0;
2553   SDLoc DL(Op);
2554   return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2555                      DAG.getConstant(SType, DL, MVT::i32));
2556 }
2557 
2558 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2559                                                 SelectionDAG &DAG) const {
2560   SDLoc DL(Op);
2561   MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2562 
2563   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2564   SDValue Shamt = Op.getOperand(2);
2565   // if shamt < (VT.bits):
2566   //  lo = (shl lo, shamt)
2567   //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2568   // else:
2569   //  lo = 0
2570   //  hi = (shl lo, shamt[4:0])
2571   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2572                             DAG.getConstant(-1, DL, MVT::i32));
2573   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2574                                       DAG.getConstant(1, DL, VT));
2575   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2576   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2577   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2578   SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2579   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2580                              DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2581   Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2582                    DAG.getConstant(0, DL, VT), ShiftLeftLo);
2583   Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2584 
2585   SDValue Ops[2] = {Lo, Hi};
2586   return DAG.getMergeValues(Ops, DL);
2587 }
2588 
2589 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2590                                                  bool IsSRA) const {
2591   SDLoc DL(Op);
2592   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2593   SDValue Shamt = Op.getOperand(2);
2594   MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2595 
2596   // if shamt < (VT.bits):
2597   //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2598   //  if isSRA:
2599   //    hi = (sra hi, shamt)
2600   //  else:
2601   //    hi = (srl hi, shamt)
2602   // else:
2603   //  if isSRA:
2604   //   lo = (sra hi, shamt[4:0])
2605   //   hi = (sra hi, 31)
2606   //  else:
2607   //   lo = (srl hi, shamt[4:0])
2608   //   hi = 0
2609   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2610                             DAG.getConstant(-1, DL, MVT::i32));
2611   SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2612                                      DAG.getConstant(1, DL, VT));
2613   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2614   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2615   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2616   SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2617                                      DL, VT, Hi, Shamt);
2618   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2619                              DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2620   SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2621                             DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2622 
2623   if (!(Subtarget.hasMips4() || Subtarget.hasMips32())) {
2624     SDVTList VTList = DAG.getVTList(VT, VT);
2625     return DAG.getNode(Subtarget.isGP64bit() ? Mips::PseudoD_SELECT_I64
2626                                              : Mips::PseudoD_SELECT_I,
2627                        DL, VTList, Cond, ShiftRightHi,
2628                        IsSRA ? Ext : DAG.getConstant(0, DL, VT), Or,
2629                        ShiftRightHi);
2630   }
2631 
2632   Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2633   Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2634                    IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2635 
2636   SDValue Ops[2] = {Lo, Hi};
2637   return DAG.getMergeValues(Ops, DL);
2638 }
2639 
2640 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2641                             SDValue Chain, SDValue Src, unsigned Offset) {
2642   SDValue Ptr = LD->getBasePtr();
2643   EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2644   EVT BasePtrVT = Ptr.getValueType();
2645   SDLoc DL(LD);
2646   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2647 
2648   if (Offset)
2649     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2650                       DAG.getConstant(Offset, DL, BasePtrVT));
2651 
2652   SDValue Ops[] = { Chain, Ptr, Src };
2653   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2654                                  LD->getMemOperand());
2655 }
2656 
2657 // Expand an unaligned 32 or 64-bit integer load node.
2658 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2659   LoadSDNode *LD = cast<LoadSDNode>(Op);
2660   EVT MemVT = LD->getMemoryVT();
2661 
2662   if (Subtarget.systemSupportsUnalignedAccess())
2663     return Op;
2664 
2665   // Return if load is aligned or if MemVT is neither i32 nor i64.
2666   if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2667       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2668     return SDValue();
2669 
2670   bool IsLittle = Subtarget.isLittle();
2671   EVT VT = Op.getValueType();
2672   ISD::LoadExtType ExtType = LD->getExtensionType();
2673   SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2674 
2675   assert((VT == MVT::i32) || (VT == MVT::i64));
2676 
2677   // Expand
2678   //  (set dst, (i64 (load baseptr)))
2679   // to
2680   //  (set tmp, (ldl (add baseptr, 7), undef))
2681   //  (set dst, (ldr baseptr, tmp))
2682   if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2683     SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2684                                IsLittle ? 7 : 0);
2685     return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2686                         IsLittle ? 0 : 7);
2687   }
2688 
2689   SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2690                              IsLittle ? 3 : 0);
2691   SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2692                              IsLittle ? 0 : 3);
2693 
2694   // Expand
2695   //  (set dst, (i32 (load baseptr))) or
2696   //  (set dst, (i64 (sextload baseptr))) or
2697   //  (set dst, (i64 (extload baseptr)))
2698   // to
2699   //  (set tmp, (lwl (add baseptr, 3), undef))
2700   //  (set dst, (lwr baseptr, tmp))
2701   if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2702       (ExtType == ISD::EXTLOAD))
2703     return LWR;
2704 
2705   assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2706 
2707   // Expand
2708   //  (set dst, (i64 (zextload baseptr)))
2709   // to
2710   //  (set tmp0, (lwl (add baseptr, 3), undef))
2711   //  (set tmp1, (lwr baseptr, tmp0))
2712   //  (set tmp2, (shl tmp1, 32))
2713   //  (set dst, (srl tmp2, 32))
2714   SDLoc DL(LD);
2715   SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2716   SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2717   SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2718   SDValue Ops[] = { SRL, LWR.getValue(1) };
2719   return DAG.getMergeValues(Ops, DL);
2720 }
2721 
2722 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2723                              SDValue Chain, unsigned Offset) {
2724   SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2725   EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2726   SDLoc DL(SD);
2727   SDVTList VTList = DAG.getVTList(MVT::Other);
2728 
2729   if (Offset)
2730     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2731                       DAG.getConstant(Offset, DL, BasePtrVT));
2732 
2733   SDValue Ops[] = { Chain, Value, Ptr };
2734   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2735                                  SD->getMemOperand());
2736 }
2737 
2738 // Expand an unaligned 32 or 64-bit integer store node.
2739 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2740                                       bool IsLittle) {
2741   SDValue Value = SD->getValue(), Chain = SD->getChain();
2742   EVT VT = Value.getValueType();
2743 
2744   // Expand
2745   //  (store val, baseptr) or
2746   //  (truncstore val, baseptr)
2747   // to
2748   //  (swl val, (add baseptr, 3))
2749   //  (swr val, baseptr)
2750   if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2751     SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2752                                 IsLittle ? 3 : 0);
2753     return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2754   }
2755 
2756   assert(VT == MVT::i64);
2757 
2758   // Expand
2759   //  (store val, baseptr)
2760   // to
2761   //  (sdl val, (add baseptr, 7))
2762   //  (sdr val, baseptr)
2763   SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2764   return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2765 }
2766 
2767 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2768 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG,
2769                                      bool SingleFloat) {
2770   SDValue Val = SD->getValue();
2771 
2772   if (Val.getOpcode() != ISD::FP_TO_SINT ||
2773       (Val.getValueSizeInBits() > 32 && SingleFloat))
2774     return SDValue();
2775 
2776   EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2777   SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2778                            Val.getOperand(0));
2779   return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2780                       SD->getPointerInfo(), SD->getAlignment(),
2781                       SD->getMemOperand()->getFlags());
2782 }
2783 
2784 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2785   StoreSDNode *SD = cast<StoreSDNode>(Op);
2786   EVT MemVT = SD->getMemoryVT();
2787 
2788   // Lower unaligned integer stores.
2789   if (!Subtarget.systemSupportsUnalignedAccess() &&
2790       (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2791       ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2792     return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2793 
2794   return lowerFP_TO_SINT_STORE(SD, DAG, Subtarget.isSingleFloat());
2795 }
2796 
2797 SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2798                                               SelectionDAG &DAG) const {
2799 
2800   // Return a fixed StackObject with offset 0 which points to the old stack
2801   // pointer.
2802   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2803   EVT ValTy = Op->getValueType(0);
2804   int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2805   return DAG.getFrameIndex(FI, ValTy);
2806 }
2807 
2808 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2809                                             SelectionDAG &DAG) const {
2810   if (Op.getValueSizeInBits() > 32 && Subtarget.isSingleFloat())
2811     return SDValue();
2812 
2813   EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2814   SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2815                               Op.getOperand(0));
2816   return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2817 }
2818 
2819 //===----------------------------------------------------------------------===//
2820 //                      Calling Convention Implementation
2821 //===----------------------------------------------------------------------===//
2822 
2823 //===----------------------------------------------------------------------===//
2824 // TODO: Implement a generic logic using tblgen that can support this.
2825 // Mips O32 ABI rules:
2826 // ---
2827 // i32 - Passed in A0, A1, A2, A3 and stack
2828 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2829 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
2830 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2831 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2832 //       not used, it must be shadowed. If only A3 is available, shadow it and
2833 //       go to stack.
2834 // vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
2835 // vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
2836 //         with the remainder spilled to the stack.
2837 // vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
2838 //         spilling the remainder to the stack.
2839 //
2840 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2841 //===----------------------------------------------------------------------===//
2842 
2843 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2844                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2845                        CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2846   const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2847       State.getMachineFunction().getSubtarget());
2848 
2849   static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2850 
2851   const MipsCCState * MipsState = static_cast<MipsCCState *>(&State);
2852 
2853   static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2854 
2855   static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 };
2856 
2857   // Do not process byval args here.
2858   if (ArgFlags.isByVal())
2859     return true;
2860 
2861   // Promote i8 and i16
2862   if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2863     if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2864       LocVT = MVT::i32;
2865       if (ArgFlags.isSExt())
2866         LocInfo = CCValAssign::SExtUpper;
2867       else if (ArgFlags.isZExt())
2868         LocInfo = CCValAssign::ZExtUpper;
2869       else
2870         LocInfo = CCValAssign::AExtUpper;
2871     }
2872   }
2873 
2874   // Promote i8 and i16
2875   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2876     LocVT = MVT::i32;
2877     if (ArgFlags.isSExt())
2878       LocInfo = CCValAssign::SExt;
2879     else if (ArgFlags.isZExt())
2880       LocInfo = CCValAssign::ZExt;
2881     else
2882       LocInfo = CCValAssign::AExt;
2883   }
2884 
2885   unsigned Reg;
2886 
2887   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2888   // is true: function is vararg, argument is 3rd or higher, there is previous
2889   // argument which is not f32 or f64.
2890   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2891                                 State.getFirstUnallocated(F32Regs) != ValNo;
2892   Align OrigAlign = ArgFlags.getNonZeroOrigAlign();
2893   bool isI64 = (ValVT == MVT::i32 && OrigAlign == Align(8));
2894   bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo);
2895 
2896   // The MIPS vector ABI for floats passes them in a pair of registers
2897   if (ValVT == MVT::i32 && isVectorFloat) {
2898     // This is the start of an vector that was scalarized into an unknown number
2899     // of components. It doesn't matter how many there are. Allocate one of the
2900     // notional 8 byte aligned registers which map onto the argument stack, and
2901     // shadow the register lost to alignment requirements.
2902     if (ArgFlags.isSplit()) {
2903       Reg = State.AllocateReg(FloatVectorIntRegs);
2904       if (Reg == Mips::A2)
2905         State.AllocateReg(Mips::A1);
2906       else if (Reg == 0)
2907         State.AllocateReg(Mips::A3);
2908     } else {
2909       // If we're an intermediate component of the split, we can just attempt to
2910       // allocate a register directly.
2911       Reg = State.AllocateReg(IntRegs);
2912     }
2913   } else if (ValVT == MVT::i32 ||
2914              (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2915     Reg = State.AllocateReg(IntRegs);
2916     // If this is the first part of an i64 arg,
2917     // the allocated register must be either A0 or A2.
2918     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2919       Reg = State.AllocateReg(IntRegs);
2920     LocVT = MVT::i32;
2921   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2922     LocVT = MVT::i32;
2923 
2924     // Allocate int register and shadow next int register. If first
2925     // available register is Mips::A1 or Mips::A3, shadow it too.
2926     Reg = State.AllocateReg(IntRegs);
2927     if (Reg == Mips::A1 || Reg == Mips::A3)
2928       Reg = State.AllocateReg(IntRegs);
2929 
2930     if (Reg) {
2931       State.addLoc(
2932           CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2933       MCRegister HiReg = State.AllocateReg(IntRegs);
2934       assert(HiReg);
2935       State.addLoc(
2936           CCValAssign::getCustomReg(ValNo, ValVT, HiReg, LocVT, LocInfo));
2937       return false;
2938     }
2939   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2940     // we are guaranteed to find an available float register
2941     if (ValVT == MVT::f32) {
2942       Reg = State.AllocateReg(F32Regs);
2943       // Shadow int register
2944       State.AllocateReg(IntRegs);
2945     } else {
2946       Reg = State.AllocateReg(F64Regs);
2947       // Shadow int registers
2948       unsigned Reg2 = State.AllocateReg(IntRegs);
2949       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2950         State.AllocateReg(IntRegs);
2951       State.AllocateReg(IntRegs);
2952     }
2953   } else
2954     llvm_unreachable("Cannot handle this ValVT.");
2955 
2956   if (!Reg) {
2957     unsigned Offset = State.AllocateStack(ValVT.getStoreSize(), OrigAlign);
2958     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2959   } else
2960     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2961 
2962   return false;
2963 }
2964 
2965 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2966                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2967                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2968   static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2969 
2970   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2971 }
2972 
2973 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2974                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2975                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2976   static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2977 
2978   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2979 }
2980 
2981 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2982                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2983                        CCState &State) LLVM_ATTRIBUTE_UNUSED;
2984 
2985 #include "MipsGenCallingConv.inc"
2986 
2987  CCAssignFn *MipsTargetLowering::CCAssignFnForCall() const{
2988    return CC_Mips_FixedArg;
2989  }
2990 
2991  CCAssignFn *MipsTargetLowering::CCAssignFnForReturn() const{
2992    return RetCC_Mips;
2993  }
2994 //===----------------------------------------------------------------------===//
2995 //                  Call Calling Convention Implementation
2996 //===----------------------------------------------------------------------===//
2997 
2998 SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2999                                            SDValue Chain, SDValue Arg,
3000                                            const SDLoc &DL, bool IsTailCall,
3001                                            SelectionDAG &DAG) const {
3002   if (!IsTailCall) {
3003     SDValue PtrOff =
3004         DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
3005                     DAG.getIntPtrConstant(Offset, DL));
3006     return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
3007   }
3008 
3009   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3010   int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
3011   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3012   return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(), MaybeAlign(),
3013                       MachineMemOperand::MOVolatile);
3014 }
3015 
3016 void MipsTargetLowering::
3017 getOpndList(SmallVectorImpl<SDValue> &Ops,
3018             std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3019             bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
3020             bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
3021             SDValue Chain) const {
3022   // Insert node "GP copy globalreg" before call to function.
3023   //
3024   // R_MIPS_CALL* operators (emitted when non-internal functions are called
3025   // in PIC mode) allow symbols to be resolved via lazy binding.
3026   // The lazy binding stub requires GP to point to the GOT.
3027   // Note that we don't need GP to point to the GOT for indirect calls
3028   // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
3029   // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
3030   // used for the function (that is, Mips linker doesn't generate lazy binding
3031   // stub for a function whose address is taken in the program).
3032   if (IsPICCall && !InternalLinkage && IsCallReloc) {
3033     unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
3034     EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
3035     RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
3036   }
3037 
3038   // Build a sequence of copy-to-reg nodes chained together with token
3039   // chain and flag operands which copy the outgoing args into registers.
3040   // The InFlag in necessary since all emitted instructions must be
3041   // stuck together.
3042   SDValue InFlag;
3043 
3044   for (auto &R : RegsToPass) {
3045     Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, R.first, R.second, InFlag);
3046     InFlag = Chain.getValue(1);
3047   }
3048 
3049   // Add argument registers to the end of the list so that they are
3050   // known live into the call.
3051   for (auto &R : RegsToPass)
3052     Ops.push_back(CLI.DAG.getRegister(R.first, R.second.getValueType()));
3053 
3054   // Add a register mask operand representing the call-preserved registers.
3055   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3056   const uint32_t *Mask =
3057       TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
3058   assert(Mask && "Missing call preserved mask for calling convention");
3059   if (Subtarget.inMips16HardFloat()) {
3060     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
3061       StringRef Sym = G->getGlobal()->getName();
3062       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3063       if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3064         Mask = MipsRegisterInfo::getMips16RetHelperMask();
3065       }
3066     }
3067   }
3068   Ops.push_back(CLI.DAG.getRegisterMask(Mask));
3069 
3070   if (InFlag.getNode())
3071     Ops.push_back(InFlag);
3072 }
3073 
3074 void MipsTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
3075                                                        SDNode *Node) const {
3076   switch (MI.getOpcode()) {
3077     default:
3078       return;
3079     case Mips::JALR:
3080     case Mips::JALRPseudo:
3081     case Mips::JALR64:
3082     case Mips::JALR64Pseudo:
3083     case Mips::JALR16_MM:
3084     case Mips::JALRC16_MMR6:
3085     case Mips::TAILCALLREG:
3086     case Mips::TAILCALLREG64:
3087     case Mips::TAILCALLR6REG:
3088     case Mips::TAILCALL64R6REG:
3089     case Mips::TAILCALLREG_MM:
3090     case Mips::TAILCALLREG_MMR6: {
3091       if (!EmitJalrReloc ||
3092           Subtarget.inMips16Mode() ||
3093           !isPositionIndependent() ||
3094           Node->getNumOperands() < 1 ||
3095           Node->getOperand(0).getNumOperands() < 2) {
3096         return;
3097       }
3098       // We are after the callee address, set by LowerCall().
3099       // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the
3100       // symbol.
3101       const SDValue TargetAddr = Node->getOperand(0).getOperand(1);
3102       StringRef Sym;
3103       if (const GlobalAddressSDNode *G =
3104               dyn_cast_or_null<const GlobalAddressSDNode>(TargetAddr)) {
3105         // We must not emit the R_MIPS_JALR relocation against data symbols
3106         // since this will cause run-time crashes if the linker replaces the
3107         // call instruction with a relative branch to the data symbol.
3108         if (!isa<Function>(G->getGlobal())) {
3109           LLVM_DEBUG(dbgs() << "Not adding R_MIPS_JALR against data symbol "
3110                             << G->getGlobal()->getName() << "\n");
3111           return;
3112         }
3113         Sym = G->getGlobal()->getName();
3114       }
3115       else if (const ExternalSymbolSDNode *ES =
3116                    dyn_cast_or_null<const ExternalSymbolSDNode>(TargetAddr)) {
3117         Sym = ES->getSymbol();
3118       }
3119 
3120       if (Sym.empty())
3121         return;
3122 
3123       MachineFunction *MF = MI.getParent()->getParent();
3124       MCSymbol *S = MF->getContext().getOrCreateSymbol(Sym);
3125       LLVM_DEBUG(dbgs() << "Adding R_MIPS_JALR against " << Sym << "\n");
3126       MI.addOperand(MachineOperand::CreateMCSymbol(S, MipsII::MO_JALR));
3127     }
3128   }
3129 }
3130 
3131 /// LowerCall - functions arguments are copied from virtual regs to
3132 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3133 SDValue
3134 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3135                               SmallVectorImpl<SDValue> &InVals) const {
3136   SelectionDAG &DAG                     = CLI.DAG;
3137   SDLoc DL                              = CLI.DL;
3138   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3139   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3140   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3141   SDValue Chain                         = CLI.Chain;
3142   SDValue Callee                        = CLI.Callee;
3143   bool &IsTailCall                      = CLI.IsTailCall;
3144   CallingConv::ID CallConv              = CLI.CallConv;
3145   bool IsVarArg                         = CLI.IsVarArg;
3146 
3147   MachineFunction &MF = DAG.getMachineFunction();
3148   MachineFrameInfo &MFI = MF.getFrameInfo();
3149   const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3150   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
3151   bool IsPIC = isPositionIndependent();
3152 
3153   // Analyze operands of the call, assigning locations to each operand.
3154   SmallVector<CCValAssign, 16> ArgLocs;
3155   MipsCCState CCInfo(
3156       CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
3157       MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
3158 
3159   const ExternalSymbolSDNode *ES =
3160       dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
3161 
3162   // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which
3163   // is during the lowering of a call with a byval argument which produces
3164   // a call to memcpy. For the O32 case, this causes the caller to allocate
3165   // stack space for the reserved argument area for the callee, then recursively
3166   // again for the memcpy call. In the NEWABI case, this doesn't occur as those
3167   // ABIs mandate that the callee allocates the reserved argument area. We do
3168   // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though.
3169   //
3170   // If the callee has a byval argument and memcpy is used, we are mandated
3171   // to already have produced a reserved argument area for the callee for O32.
3172   // Therefore, the reserved argument area can be reused for both calls.
3173   //
3174   // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START
3175   // present, as we have yet to hook that node onto the chain.
3176   //
3177   // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this
3178   // case. GCC does a similar trick, in that wherever possible, it calculates
3179   // the maximum out going argument area (including the reserved area), and
3180   // preallocates the stack space on entrance to the caller.
3181   //
3182   // FIXME: We should do the same for efficiency and space.
3183 
3184   // Note: The check on the calling convention below must match
3185   //       MipsABIInfo::GetCalleeAllocdArgSizeInBytes().
3186   bool MemcpyInByVal = ES &&
3187                        StringRef(ES->getSymbol()) == StringRef("memcpy") &&
3188                        CallConv != CallingConv::Fast &&
3189                        Chain.getOpcode() == ISD::CALLSEQ_START;
3190 
3191   // Allocate the reserved argument area. It seems strange to do this from the
3192   // caller side but removing it breaks the frame size calculation.
3193   unsigned ReservedArgArea =
3194       MemcpyInByVal ? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv);
3195   CCInfo.AllocateStack(ReservedArgArea, Align(1));
3196 
3197   CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
3198                              ES ? ES->getSymbol() : nullptr);
3199 
3200   // Get a count of how many bytes are to be pushed on the stack.
3201   unsigned NextStackOffset = CCInfo.getNextStackOffset();
3202 
3203   // Call site info for function parameters tracking.
3204   MachineFunction::CallSiteInfo CSInfo;
3205 
3206   // Check if it's really possible to do a tail call. Restrict it to functions
3207   // that are part of this compilation unit.
3208   bool InternalLinkage = false;
3209   if (IsTailCall) {
3210     IsTailCall = isEligibleForTailCallOptimization(
3211         CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
3212      if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3213       InternalLinkage = G->getGlobal()->hasInternalLinkage();
3214       IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
3215                      G->getGlobal()->hasPrivateLinkage() ||
3216                      G->getGlobal()->hasHiddenVisibility() ||
3217                      G->getGlobal()->hasProtectedVisibility());
3218      }
3219   }
3220   if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
3221     report_fatal_error("failed to perform tail call elimination on a call "
3222                        "site marked musttail");
3223 
3224   if (IsTailCall)
3225     ++NumTailCalls;
3226 
3227   // Chain is the output chain of the last Load/Store or CopyToReg node.
3228   // ByValChain is the output chain of the last Memcpy node created for copying
3229   // byval arguments to the stack.
3230   unsigned StackAlignment = TFL->getStackAlignment();
3231   NextStackOffset = alignTo(NextStackOffset, StackAlignment);
3232   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
3233 
3234   if (!(IsTailCall || MemcpyInByVal))
3235     Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL);
3236 
3237   SDValue StackPtr =
3238       DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
3239                          getPointerTy(DAG.getDataLayout()));
3240 
3241   std::deque<std::pair<unsigned, SDValue>> RegsToPass;
3242   SmallVector<SDValue, 8> MemOpChains;
3243 
3244   CCInfo.rewindByValRegsInfo();
3245 
3246   // Walk the register/memloc assignments, inserting copies/loads.
3247   for (unsigned i = 0, e = ArgLocs.size(), OutIdx = 0; i != e; ++i, ++OutIdx) {
3248     SDValue Arg = OutVals[OutIdx];
3249     CCValAssign &VA = ArgLocs[i];
3250     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3251     ISD::ArgFlagsTy Flags = Outs[OutIdx].Flags;
3252     bool UseUpperBits = false;
3253 
3254     // ByVal Arg.
3255     if (Flags.isByVal()) {
3256       unsigned FirstByValReg, LastByValReg;
3257       unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3258       CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3259 
3260       assert(Flags.getByValSize() &&
3261              "ByVal args of size 0 should have been ignored by front-end.");
3262       assert(ByValIdx < CCInfo.getInRegsParamsCount());
3263       assert(!IsTailCall &&
3264              "Do not tail-call optimize if there is a byval argument.");
3265       passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3266                    FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3267                    VA);
3268       CCInfo.nextInRegsParam();
3269       continue;
3270     }
3271 
3272     // Promote the value if needed.
3273     switch (VA.getLocInfo()) {
3274     default:
3275       llvm_unreachable("Unknown loc info!");
3276     case CCValAssign::Full:
3277       if (VA.isRegLoc()) {
3278         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3279             (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3280             (ValVT == MVT::i64 && LocVT == MVT::f64))
3281           Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3282         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3283           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3284                                    Arg, DAG.getConstant(0, DL, MVT::i32));
3285           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3286                                    Arg, DAG.getConstant(1, DL, MVT::i32));
3287           if (!Subtarget.isLittle())
3288             std::swap(Lo, Hi);
3289 
3290           assert(VA.needsCustom());
3291 
3292           Register LocRegLo = VA.getLocReg();
3293           Register LocRegHigh = ArgLocs[++i].getLocReg();
3294           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3295           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3296           continue;
3297         }
3298       }
3299       break;
3300     case CCValAssign::BCvt:
3301       Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3302       break;
3303     case CCValAssign::SExtUpper:
3304       UseUpperBits = true;
3305       LLVM_FALLTHROUGH;
3306     case CCValAssign::SExt:
3307       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3308       break;
3309     case CCValAssign::ZExtUpper:
3310       UseUpperBits = true;
3311       LLVM_FALLTHROUGH;
3312     case CCValAssign::ZExt:
3313       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3314       break;
3315     case CCValAssign::AExtUpper:
3316       UseUpperBits = true;
3317       LLVM_FALLTHROUGH;
3318     case CCValAssign::AExt:
3319       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3320       break;
3321     }
3322 
3323     if (UseUpperBits) {
3324       unsigned ValSizeInBits = Outs[OutIdx].ArgVT.getSizeInBits();
3325       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3326       Arg = DAG.getNode(
3327           ISD::SHL, DL, VA.getLocVT(), Arg,
3328           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3329     }
3330 
3331     // Arguments that can be passed on register must be kept at
3332     // RegsToPass vector
3333     if (VA.isRegLoc()) {
3334       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3335 
3336       // If the parameter is passed through reg $D, which splits into
3337       // two physical registers, avoid creating call site info.
3338       if (Mips::AFGR64RegClass.contains(VA.getLocReg()))
3339         continue;
3340 
3341       // Collect CSInfo about which register passes which parameter.
3342       const TargetOptions &Options = DAG.getTarget().Options;
3343       if (Options.SupportsDebugEntryValues)
3344         CSInfo.emplace_back(VA.getLocReg(), i);
3345 
3346       continue;
3347     }
3348 
3349     // Register can't get to this point...
3350     assert(VA.isMemLoc());
3351 
3352     // emit ISD::STORE whichs stores the
3353     // parameter value to a stack Location
3354     MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3355                                          Chain, Arg, DL, IsTailCall, DAG));
3356   }
3357 
3358   // Transform all store nodes into one single node because all store
3359   // nodes are independent of each other.
3360   if (!MemOpChains.empty())
3361     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3362 
3363   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3364   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3365   // node so that legalize doesn't hack it.
3366 
3367   EVT Ty = Callee.getValueType();
3368   bool GlobalOrExternal = false, IsCallReloc = false;
3369 
3370   // The long-calls feature is ignored in case of PIC.
3371   // While we do not support -mshared / -mno-shared properly,
3372   // ignore long-calls in case of -mabicalls too.
3373   if (!Subtarget.isABICalls() && !IsPIC) {
3374     // If the function should be called using "long call",
3375     // get its address into a register to prevent using
3376     // of the `jal` instruction for the direct call.
3377     if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3378       if (Subtarget.useLongCalls())
3379         Callee = Subtarget.hasSym32()
3380                      ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3381                      : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3382     } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) {
3383       bool UseLongCalls = Subtarget.useLongCalls();
3384       // If the function has long-call/far/near attribute
3385       // it overrides command line switch pased to the backend.
3386       if (auto *F = dyn_cast<Function>(N->getGlobal())) {
3387         if (F->hasFnAttribute("long-call"))
3388           UseLongCalls = true;
3389         else if (F->hasFnAttribute("short-call"))
3390           UseLongCalls = false;
3391       }
3392       if (UseLongCalls)
3393         Callee = Subtarget.hasSym32()
3394                      ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3395                      : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3396     }
3397   }
3398 
3399   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3400     if (IsPIC) {
3401       const GlobalValue *Val = G->getGlobal();
3402       InternalLinkage = Val->hasInternalLinkage();
3403 
3404       if (InternalLinkage)
3405         Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3406       else if (Subtarget.useXGOT()) {
3407         Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3408                                        MipsII::MO_CALL_LO16, Chain,
3409                                        FuncInfo->callPtrInfo(MF, Val));
3410         IsCallReloc = true;
3411       } else {
3412         Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3413                                FuncInfo->callPtrInfo(MF, Val));
3414         IsCallReloc = true;
3415       }
3416     } else
3417       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3418                                           getPointerTy(DAG.getDataLayout()), 0,
3419                                           MipsII::MO_NO_FLAG);
3420     GlobalOrExternal = true;
3421   }
3422   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3423     const char *Sym = S->getSymbol();
3424 
3425     if (!IsPIC) // static
3426       Callee = DAG.getTargetExternalSymbol(
3427           Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
3428     else if (Subtarget.useXGOT()) {
3429       Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3430                                      MipsII::MO_CALL_LO16, Chain,
3431                                      FuncInfo->callPtrInfo(MF, Sym));
3432       IsCallReloc = true;
3433     } else { // PIC
3434       Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3435                              FuncInfo->callPtrInfo(MF, Sym));
3436       IsCallReloc = true;
3437     }
3438 
3439     GlobalOrExternal = true;
3440   }
3441 
3442   SmallVector<SDValue, 8> Ops(1, Chain);
3443   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3444 
3445   getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3446               IsCallReloc, CLI, Callee, Chain);
3447 
3448   if (IsTailCall) {
3449     MF.getFrameInfo().setHasTailCall();
3450     SDValue Ret = DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3451     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
3452     return Ret;
3453   }
3454 
3455   Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3456   SDValue InFlag = Chain.getValue(1);
3457 
3458   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
3459 
3460   // Create the CALLSEQ_END node in the case of where it is not a call to
3461   // memcpy.
3462   if (!(MemcpyInByVal)) {
3463     Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3464                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3465     InFlag = Chain.getValue(1);
3466   }
3467 
3468   // Handle result values, copying them out of physregs into vregs that we
3469   // return.
3470   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3471                          InVals, CLI);
3472 }
3473 
3474 /// LowerCallResult - Lower the result values of a call into the
3475 /// appropriate copies out of appropriate physical registers.
3476 SDValue MipsTargetLowering::LowerCallResult(
3477     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
3478     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3479     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3480     TargetLowering::CallLoweringInfo &CLI) const {
3481   // Assign locations to each value returned by this call.
3482   SmallVector<CCValAssign, 16> RVLocs;
3483   MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3484                      *DAG.getContext());
3485 
3486   const ExternalSymbolSDNode *ES =
3487       dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3488   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3489                            ES ? ES->getSymbol() : nullptr);
3490 
3491   // Copy all of the result registers out of their specified physreg.
3492   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3493     CCValAssign &VA = RVLocs[i];
3494     assert(VA.isRegLoc() && "Can only return in registers!");
3495 
3496     SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3497                                      RVLocs[i].getLocVT(), InFlag);
3498     Chain = Val.getValue(1);
3499     InFlag = Val.getValue(2);
3500 
3501     if (VA.isUpperBitsInLoc()) {
3502       unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3503       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3504       unsigned Shift =
3505           VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3506       Val = DAG.getNode(
3507           Shift, DL, VA.getLocVT(), Val,
3508           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3509     }
3510 
3511     switch (VA.getLocInfo()) {
3512     default:
3513       llvm_unreachable("Unknown loc info!");
3514     case CCValAssign::Full:
3515       break;
3516     case CCValAssign::BCvt:
3517       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3518       break;
3519     case CCValAssign::AExt:
3520     case CCValAssign::AExtUpper:
3521       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3522       break;
3523     case CCValAssign::ZExt:
3524     case CCValAssign::ZExtUpper:
3525       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3526                         DAG.getValueType(VA.getValVT()));
3527       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3528       break;
3529     case CCValAssign::SExt:
3530     case CCValAssign::SExtUpper:
3531       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3532                         DAG.getValueType(VA.getValVT()));
3533       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3534       break;
3535     }
3536 
3537     InVals.push_back(Val);
3538   }
3539 
3540   return Chain;
3541 }
3542 
3543 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
3544                                       EVT ArgVT, const SDLoc &DL,
3545                                       SelectionDAG &DAG) {
3546   MVT LocVT = VA.getLocVT();
3547   EVT ValVT = VA.getValVT();
3548 
3549   // Shift into the upper bits if necessary.
3550   switch (VA.getLocInfo()) {
3551   default:
3552     break;
3553   case CCValAssign::AExtUpper:
3554   case CCValAssign::SExtUpper:
3555   case CCValAssign::ZExtUpper: {
3556     unsigned ValSizeInBits = ArgVT.getSizeInBits();
3557     unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3558     unsigned Opcode =
3559         VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3560     Val = DAG.getNode(
3561         Opcode, DL, VA.getLocVT(), Val,
3562         DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3563     break;
3564   }
3565   }
3566 
3567   // If this is an value smaller than the argument slot size (32-bit for O32,
3568   // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3569   // size. Extract the value and insert any appropriate assertions regarding
3570   // sign/zero extension.
3571   switch (VA.getLocInfo()) {
3572   default:
3573     llvm_unreachable("Unknown loc info!");
3574   case CCValAssign::Full:
3575     break;
3576   case CCValAssign::AExtUpper:
3577   case CCValAssign::AExt:
3578     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3579     break;
3580   case CCValAssign::SExtUpper:
3581   case CCValAssign::SExt:
3582     Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3583     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3584     break;
3585   case CCValAssign::ZExtUpper:
3586   case CCValAssign::ZExt:
3587     Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3588     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3589     break;
3590   case CCValAssign::BCvt:
3591     Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3592     break;
3593   }
3594 
3595   return Val;
3596 }
3597 
3598 //===----------------------------------------------------------------------===//
3599 //             Formal Arguments Calling Convention Implementation
3600 //===----------------------------------------------------------------------===//
3601 /// LowerFormalArguments - transform physical registers into virtual registers
3602 /// and generate load operations for arguments places on the stack.
3603 SDValue MipsTargetLowering::LowerFormalArguments(
3604     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3605     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3606     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3607   MachineFunction &MF = DAG.getMachineFunction();
3608   MachineFrameInfo &MFI = MF.getFrameInfo();
3609   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3610 
3611   MipsFI->setVarArgsFrameIndex(0);
3612 
3613   // Used with vargs to acumulate store chains.
3614   std::vector<SDValue> OutChains;
3615 
3616   // Assign locations to all of the incoming arguments.
3617   SmallVector<CCValAssign, 16> ArgLocs;
3618   MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3619                      *DAG.getContext());
3620   CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), Align(1));
3621   const Function &Func = DAG.getMachineFunction().getFunction();
3622   Function::const_arg_iterator FuncArg = Func.arg_begin();
3623 
3624   if (Func.hasFnAttribute("interrupt") && !Func.arg_empty())
3625     report_fatal_error(
3626         "Functions with the interrupt attribute cannot have arguments!");
3627 
3628   CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3629   MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3630                            CCInfo.getInRegsParamsCount() > 0);
3631 
3632   unsigned CurArgIdx = 0;
3633   CCInfo.rewindByValRegsInfo();
3634 
3635   for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3636     CCValAssign &VA = ArgLocs[i];
3637     if (Ins[InsIdx].isOrigArg()) {
3638       std::advance(FuncArg, Ins[InsIdx].getOrigArgIndex() - CurArgIdx);
3639       CurArgIdx = Ins[InsIdx].getOrigArgIndex();
3640     }
3641     EVT ValVT = VA.getValVT();
3642     ISD::ArgFlagsTy Flags = Ins[InsIdx].Flags;
3643     bool IsRegLoc = VA.isRegLoc();
3644 
3645     if (Flags.isByVal()) {
3646       assert(Ins[InsIdx].isOrigArg() && "Byval arguments cannot be implicit");
3647       unsigned FirstByValReg, LastByValReg;
3648       unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3649       CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3650 
3651       assert(Flags.getByValSize() &&
3652              "ByVal args of size 0 should have been ignored by front-end.");
3653       assert(ByValIdx < CCInfo.getInRegsParamsCount());
3654       copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3655                     FirstByValReg, LastByValReg, VA, CCInfo);
3656       CCInfo.nextInRegsParam();
3657       continue;
3658     }
3659 
3660     // Arguments stored on registers
3661     if (IsRegLoc) {
3662       MVT RegVT = VA.getLocVT();
3663       Register ArgReg = VA.getLocReg();
3664       const TargetRegisterClass *RC = getRegClassFor(RegVT);
3665 
3666       // Transform the arguments stored on
3667       // physical registers into virtual ones
3668       unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3669       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3670 
3671       ArgValue =
3672           UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3673 
3674       // Handle floating point arguments passed in integer registers and
3675       // long double arguments passed in floating point registers.
3676       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3677           (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3678           (RegVT == MVT::f64 && ValVT == MVT::i64))
3679         ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3680       else if (ABI.IsO32() && RegVT == MVT::i32 &&
3681                ValVT == MVT::f64) {
3682         assert(VA.needsCustom() && "Expected custom argument for f64 split");
3683         CCValAssign &NextVA = ArgLocs[++i];
3684         unsigned Reg2 =
3685             addLiveIn(DAG.getMachineFunction(), NextVA.getLocReg(), RC);
3686         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3687         if (!Subtarget.isLittle())
3688           std::swap(ArgValue, ArgValue2);
3689         ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3690                                ArgValue, ArgValue2);
3691       }
3692 
3693       InVals.push_back(ArgValue);
3694     } else { // VA.isRegLoc()
3695       MVT LocVT = VA.getLocVT();
3696 
3697       assert(!VA.needsCustom() && "unexpected custom memory argument");
3698 
3699       if (ABI.IsO32()) {
3700         // We ought to be able to use LocVT directly but O32 sets it to i32
3701         // when allocating floating point values to integer registers.
3702         // This shouldn't influence how we load the value into registers unless
3703         // we are targeting softfloat.
3704         if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3705           LocVT = VA.getValVT();
3706       }
3707 
3708       // Only arguments pased on the stack should make it here.
3709       assert(VA.isMemLoc());
3710 
3711       // The stack pointer offset is relative to the caller stack frame.
3712       int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3713                                      VA.getLocMemOffset(), true);
3714 
3715       // Create load nodes to retrieve arguments from the stack
3716       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3717       SDValue ArgValue = DAG.getLoad(
3718           LocVT, DL, Chain, FIN,
3719           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3720       OutChains.push_back(ArgValue.getValue(1));
3721 
3722       ArgValue =
3723           UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3724 
3725       InVals.push_back(ArgValue);
3726     }
3727   }
3728 
3729   for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3730 
3731     if (ArgLocs[i].needsCustom()) {
3732       ++i;
3733       continue;
3734     }
3735 
3736     // The mips ABIs for returning structs by value requires that we copy
3737     // the sret argument into $v0 for the return. Save the argument into
3738     // a virtual register so that we can access it from the return points.
3739     if (Ins[InsIdx].Flags.isSRet()) {
3740       unsigned Reg = MipsFI->getSRetReturnReg();
3741       if (!Reg) {
3742         Reg = MF.getRegInfo().createVirtualRegister(
3743             getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3744         MipsFI->setSRetReturnReg(Reg);
3745       }
3746       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3747       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3748       break;
3749     }
3750   }
3751 
3752   if (IsVarArg)
3753     writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3754 
3755   // All stores are grouped in one node to allow the matching between
3756   // the size of Ins and InVals. This only happens when on varg functions
3757   if (!OutChains.empty()) {
3758     OutChains.push_back(Chain);
3759     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3760   }
3761 
3762   return Chain;
3763 }
3764 
3765 //===----------------------------------------------------------------------===//
3766 //               Return Value Calling Convention Implementation
3767 //===----------------------------------------------------------------------===//
3768 
3769 bool
3770 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3771                                    MachineFunction &MF, bool IsVarArg,
3772                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3773                                    LLVMContext &Context) const {
3774   SmallVector<CCValAssign, 16> RVLocs;
3775   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3776   return CCInfo.CheckReturn(Outs, RetCC_Mips);
3777 }
3778 
3779 bool MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type,
3780                                                        bool IsSigned) const {
3781   if ((ABI.IsN32() || ABI.IsN64()) && Type == MVT::i32)
3782       return true;
3783 
3784   return IsSigned;
3785 }
3786 
3787 SDValue
3788 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3789                                          const SDLoc &DL,
3790                                          SelectionDAG &DAG) const {
3791   MachineFunction &MF = DAG.getMachineFunction();
3792   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3793 
3794   MipsFI->setISR();
3795 
3796   return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3797 }
3798 
3799 SDValue
3800 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3801                                 bool IsVarArg,
3802                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
3803                                 const SmallVectorImpl<SDValue> &OutVals,
3804                                 const SDLoc &DL, SelectionDAG &DAG) const {
3805   // CCValAssign - represent the assignment of
3806   // the return value to a location
3807   SmallVector<CCValAssign, 16> RVLocs;
3808   MachineFunction &MF = DAG.getMachineFunction();
3809 
3810   // CCState - Info about the registers and stack slot.
3811   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3812 
3813   // Analyze return values.
3814   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3815 
3816   SDValue Flag;
3817   SmallVector<SDValue, 4> RetOps(1, Chain);
3818 
3819   // Copy the result values into the output registers.
3820   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3821     SDValue Val = OutVals[i];
3822     CCValAssign &VA = RVLocs[i];
3823     assert(VA.isRegLoc() && "Can only return in registers!");
3824     bool UseUpperBits = false;
3825 
3826     switch (VA.getLocInfo()) {
3827     default:
3828       llvm_unreachable("Unknown loc info!");
3829     case CCValAssign::Full:
3830       break;
3831     case CCValAssign::BCvt:
3832       Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3833       break;
3834     case CCValAssign::AExtUpper:
3835       UseUpperBits = true;
3836       LLVM_FALLTHROUGH;
3837     case CCValAssign::AExt:
3838       Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3839       break;
3840     case CCValAssign::ZExtUpper:
3841       UseUpperBits = true;
3842       LLVM_FALLTHROUGH;
3843     case CCValAssign::ZExt:
3844       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3845       break;
3846     case CCValAssign::SExtUpper:
3847       UseUpperBits = true;
3848       LLVM_FALLTHROUGH;
3849     case CCValAssign::SExt:
3850       Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3851       break;
3852     }
3853 
3854     if (UseUpperBits) {
3855       unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3856       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3857       Val = DAG.getNode(
3858           ISD::SHL, DL, VA.getLocVT(), Val,
3859           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3860     }
3861 
3862     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3863 
3864     // Guarantee that all emitted copies are stuck together with flags.
3865     Flag = Chain.getValue(1);
3866     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3867   }
3868 
3869   // The mips ABIs for returning structs by value requires that we copy
3870   // the sret argument into $v0 for the return. We saved the argument into
3871   // a virtual register in the entry block, so now we copy the value out
3872   // and into $v0.
3873   if (MF.getFunction().hasStructRetAttr()) {
3874     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3875     unsigned Reg = MipsFI->getSRetReturnReg();
3876 
3877     if (!Reg)
3878       llvm_unreachable("sret virtual register not created in the entry block");
3879     SDValue Val =
3880         DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3881     unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3882 
3883     Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3884     Flag = Chain.getValue(1);
3885     RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3886   }
3887 
3888   RetOps[0] = Chain;  // Update chain.
3889 
3890   // Add the flag if we have it.
3891   if (Flag.getNode())
3892     RetOps.push_back(Flag);
3893 
3894   // ISRs must use "eret".
3895   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt"))
3896     return LowerInterruptReturn(RetOps, DL, DAG);
3897 
3898   // Standard return on Mips is a "jr $ra"
3899   return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3900 }
3901 
3902 //===----------------------------------------------------------------------===//
3903 //                           Mips Inline Assembly Support
3904 //===----------------------------------------------------------------------===//
3905 
3906 /// getConstraintType - Given a constraint letter, return the type of
3907 /// constraint it is for this target.
3908 MipsTargetLowering::ConstraintType
3909 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3910   // Mips specific constraints
3911   // GCC config/mips/constraints.md
3912   //
3913   // 'd' : An address register. Equivalent to r
3914   //       unless generating MIPS16 code.
3915   // 'y' : Equivalent to r; retained for
3916   //       backwards compatibility.
3917   // 'c' : A register suitable for use in an indirect
3918   //       jump. This will always be $25 for -mabicalls.
3919   // 'l' : The lo register. 1 word storage.
3920   // 'x' : The hilo register pair. Double word storage.
3921   if (Constraint.size() == 1) {
3922     switch (Constraint[0]) {
3923       default : break;
3924       case 'd':
3925       case 'y':
3926       case 'f':
3927       case 'c':
3928       case 'l':
3929       case 'x':
3930         return C_RegisterClass;
3931       case 'R':
3932         return C_Memory;
3933     }
3934   }
3935 
3936   if (Constraint == "ZC")
3937     return C_Memory;
3938 
3939   return TargetLowering::getConstraintType(Constraint);
3940 }
3941 
3942 /// Examine constraint type and operand type and determine a weight value.
3943 /// This object must already have been set up with the operand type
3944 /// and the current alternative constraint selected.
3945 TargetLowering::ConstraintWeight
3946 MipsTargetLowering::getSingleConstraintMatchWeight(
3947     AsmOperandInfo &info, const char *constraint) const {
3948   ConstraintWeight weight = CW_Invalid;
3949   Value *CallOperandVal = info.CallOperandVal;
3950     // If we don't have a value, we can't do a match,
3951     // but allow it at the lowest weight.
3952   if (!CallOperandVal)
3953     return CW_Default;
3954   Type *type = CallOperandVal->getType();
3955   // Look at the constraint type.
3956   switch (*constraint) {
3957   default:
3958     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3959     break;
3960   case 'd':
3961   case 'y':
3962     if (type->isIntegerTy())
3963       weight = CW_Register;
3964     break;
3965   case 'f': // FPU or MSA register
3966     if (Subtarget.hasMSA() && type->isVectorTy() &&
3967         type->getPrimitiveSizeInBits().getFixedSize() == 128)
3968       weight = CW_Register;
3969     else if (type->isFloatTy())
3970       weight = CW_Register;
3971     break;
3972   case 'c': // $25 for indirect jumps
3973   case 'l': // lo register
3974   case 'x': // hilo register pair
3975     if (type->isIntegerTy())
3976       weight = CW_SpecificReg;
3977     break;
3978   case 'I': // signed 16 bit immediate
3979   case 'J': // integer zero
3980   case 'K': // unsigned 16 bit immediate
3981   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3982   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3983   case 'O': // signed 15 bit immediate (+- 16383)
3984   case 'P': // immediate in the range of 65535 to 1 (inclusive)
3985     if (isa<ConstantInt>(CallOperandVal))
3986       weight = CW_Constant;
3987     break;
3988   case 'R':
3989     weight = CW_Memory;
3990     break;
3991   }
3992   return weight;
3993 }
3994 
3995 /// This is a helper function to parse a physical register string and split it
3996 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3997 /// that is returned indicates whether parsing was successful. The second flag
3998 /// is true if the numeric part exists.
3999 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
4000                                               unsigned long long &Reg) {
4001   if (C.front() != '{' || C.back() != '}')
4002     return std::make_pair(false, false);
4003 
4004   // Search for the first numeric character.
4005   StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
4006   I = std::find_if(B, E, isdigit);
4007 
4008   Prefix = StringRef(B, I - B);
4009 
4010   // The second flag is set to false if no numeric characters were found.
4011   if (I == E)
4012     return std::make_pair(true, false);
4013 
4014   // Parse the numeric characters.
4015   return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
4016                         true);
4017 }
4018 
4019 EVT MipsTargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
4020                                             ISD::NodeType) const {
4021   bool Cond = !Subtarget.isABI_O32() && VT.getSizeInBits() == 32;
4022   EVT MinVT = getRegisterType(Context, Cond ? MVT::i64 : MVT::i32);
4023   return VT.bitsLT(MinVT) ? MinVT : VT;
4024 }
4025 
4026 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
4027 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
4028   const TargetRegisterInfo *TRI =
4029       Subtarget.getRegisterInfo();
4030   const TargetRegisterClass *RC;
4031   StringRef Prefix;
4032   unsigned long long Reg;
4033 
4034   std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
4035 
4036   if (!R.first)
4037     return std::make_pair(0U, nullptr);
4038 
4039   if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
4040     // No numeric characters follow "hi" or "lo".
4041     if (R.second)
4042       return std::make_pair(0U, nullptr);
4043 
4044     RC = TRI->getRegClass(Prefix == "hi" ?
4045                           Mips::HI32RegClassID : Mips::LO32RegClassID);
4046     return std::make_pair(*(RC->begin()), RC);
4047   } else if (Prefix.startswith("$msa")) {
4048     // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
4049 
4050     // No numeric characters follow the name.
4051     if (R.second)
4052       return std::make_pair(0U, nullptr);
4053 
4054     Reg = StringSwitch<unsigned long long>(Prefix)
4055               .Case("$msair", Mips::MSAIR)
4056               .Case("$msacsr", Mips::MSACSR)
4057               .Case("$msaaccess", Mips::MSAAccess)
4058               .Case("$msasave", Mips::MSASave)
4059               .Case("$msamodify", Mips::MSAModify)
4060               .Case("$msarequest", Mips::MSARequest)
4061               .Case("$msamap", Mips::MSAMap)
4062               .Case("$msaunmap", Mips::MSAUnmap)
4063               .Default(0);
4064 
4065     if (!Reg)
4066       return std::make_pair(0U, nullptr);
4067 
4068     RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
4069     return std::make_pair(Reg, RC);
4070   }
4071 
4072   if (!R.second)
4073     return std::make_pair(0U, nullptr);
4074 
4075   if (Prefix == "$f") { // Parse $f0-$f31.
4076     // If the size of FP registers is 64-bit or Reg is an even number, select
4077     // the 64-bit register class. Otherwise, select the 32-bit register class.
4078     if (VT == MVT::Other)
4079       VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
4080 
4081     RC = getRegClassFor(VT);
4082 
4083     if (RC == &Mips::AFGR64RegClass) {
4084       assert(Reg % 2 == 0);
4085       Reg >>= 1;
4086     }
4087   } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
4088     RC = TRI->getRegClass(Mips::FCCRegClassID);
4089   else if (Prefix == "$w") { // Parse $w0-$w31.
4090     RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
4091   } else { // Parse $0-$31.
4092     assert(Prefix == "$");
4093     RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
4094   }
4095 
4096   assert(Reg < RC->getNumRegs());
4097   return std::make_pair(*(RC->begin() + Reg), RC);
4098 }
4099 
4100 /// Given a register class constraint, like 'r', if this corresponds directly
4101 /// to an LLVM register class, return a register of 0 and the register class
4102 /// pointer.
4103 std::pair<unsigned, const TargetRegisterClass *>
4104 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4105                                                  StringRef Constraint,
4106                                                  MVT VT) const {
4107   if (Constraint.size() == 1) {
4108     switch (Constraint[0]) {
4109     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
4110     case 'y': // Same as 'r'. Exists for compatibility.
4111     case 'r':
4112       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8 || VT == MVT::i1) {
4113         if (Subtarget.inMips16Mode())
4114           return std::make_pair(0U, &Mips::CPU16RegsRegClass);
4115         return std::make_pair(0U, &Mips::GPR32RegClass);
4116       }
4117       if (VT == MVT::i64 && !Subtarget.isGP64bit())
4118         return std::make_pair(0U, &Mips::GPR32RegClass);
4119       if (VT == MVT::i64 && Subtarget.isGP64bit())
4120         return std::make_pair(0U, &Mips::GPR64RegClass);
4121       // This will generate an error message
4122       return std::make_pair(0U, nullptr);
4123     case 'f': // FPU or MSA register
4124       if (VT == MVT::v16i8)
4125         return std::make_pair(0U, &Mips::MSA128BRegClass);
4126       else if (VT == MVT::v8i16 || VT == MVT::v8f16)
4127         return std::make_pair(0U, &Mips::MSA128HRegClass);
4128       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
4129         return std::make_pair(0U, &Mips::MSA128WRegClass);
4130       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
4131         return std::make_pair(0U, &Mips::MSA128DRegClass);
4132       else if (VT == MVT::f32)
4133         return std::make_pair(0U, &Mips::FGR32RegClass);
4134       else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
4135         if (Subtarget.isFP64bit())
4136           return std::make_pair(0U, &Mips::FGR64RegClass);
4137         return std::make_pair(0U, &Mips::AFGR64RegClass);
4138       }
4139       break;
4140     case 'c': // register suitable for indirect jump
4141       if (VT == MVT::i32)
4142         return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
4143       if (VT == MVT::i64)
4144         return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
4145       // This will generate an error message
4146       return std::make_pair(0U, nullptr);
4147     case 'l': // use the `lo` register to store values
4148               // that are no bigger than a word
4149       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
4150         return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
4151       return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
4152     case 'x': // use the concatenated `hi` and `lo` registers
4153               // to store doubleword values
4154       // Fixme: Not triggering the use of both hi and low
4155       // This will generate an error message
4156       return std::make_pair(0U, nullptr);
4157     }
4158   }
4159 
4160   if (!Constraint.empty()) {
4161     std::pair<unsigned, const TargetRegisterClass *> R;
4162     R = parseRegForInlineAsmConstraint(Constraint, VT);
4163 
4164     if (R.second)
4165       return R;
4166   }
4167 
4168   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4169 }
4170 
4171 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4172 /// vector.  If it is invalid, don't add anything to Ops.
4173 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4174                                                      std::string &Constraint,
4175                                                      std::vector<SDValue>&Ops,
4176                                                      SelectionDAG &DAG) const {
4177   SDLoc DL(Op);
4178   SDValue Result;
4179 
4180   // Only support length 1 constraints for now.
4181   if (Constraint.length() > 1) return;
4182 
4183   char ConstraintLetter = Constraint[0];
4184   switch (ConstraintLetter) {
4185   default: break; // This will fall through to the generic implementation
4186   case 'I': // Signed 16 bit constant
4187     // If this fails, the parent routine will give an error
4188     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4189       EVT Type = Op.getValueType();
4190       int64_t Val = C->getSExtValue();
4191       if (isInt<16>(Val)) {
4192         Result = DAG.getTargetConstant(Val, DL, Type);
4193         break;
4194       }
4195     }
4196     return;
4197   case 'J': // integer zero
4198     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4199       EVT Type = Op.getValueType();
4200       int64_t Val = C->getZExtValue();
4201       if (Val == 0) {
4202         Result = DAG.getTargetConstant(0, DL, Type);
4203         break;
4204       }
4205     }
4206     return;
4207   case 'K': // unsigned 16 bit immediate
4208     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4209       EVT Type = Op.getValueType();
4210       uint64_t Val = (uint64_t)C->getZExtValue();
4211       if (isUInt<16>(Val)) {
4212         Result = DAG.getTargetConstant(Val, DL, Type);
4213         break;
4214       }
4215     }
4216     return;
4217   case 'L': // signed 32 bit immediate where lower 16 bits are 0
4218     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4219       EVT Type = Op.getValueType();
4220       int64_t Val = C->getSExtValue();
4221       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
4222         Result = DAG.getTargetConstant(Val, DL, Type);
4223         break;
4224       }
4225     }
4226     return;
4227   case 'N': // immediate in the range of -65535 to -1 (inclusive)
4228     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4229       EVT Type = Op.getValueType();
4230       int64_t Val = C->getSExtValue();
4231       if ((Val >= -65535) && (Val <= -1)) {
4232         Result = DAG.getTargetConstant(Val, DL, Type);
4233         break;
4234       }
4235     }
4236     return;
4237   case 'O': // signed 15 bit immediate
4238     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4239       EVT Type = Op.getValueType();
4240       int64_t Val = C->getSExtValue();
4241       if ((isInt<15>(Val))) {
4242         Result = DAG.getTargetConstant(Val, DL, Type);
4243         break;
4244       }
4245     }
4246     return;
4247   case 'P': // immediate in the range of 1 to 65535 (inclusive)
4248     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4249       EVT Type = Op.getValueType();
4250       int64_t Val = C->getSExtValue();
4251       if ((Val <= 65535) && (Val >= 1)) {
4252         Result = DAG.getTargetConstant(Val, DL, Type);
4253         break;
4254       }
4255     }
4256     return;
4257   }
4258 
4259   if (Result.getNode()) {
4260     Ops.push_back(Result);
4261     return;
4262   }
4263 
4264   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4265 }
4266 
4267 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
4268                                                const AddrMode &AM, Type *Ty,
4269                                                unsigned AS,
4270                                                Instruction *I) const {
4271   // No global is ever allowed as a base.
4272   if (AM.BaseGV)
4273     return false;
4274 
4275   switch (AM.Scale) {
4276   case 0: // "r+i" or just "i", depending on HasBaseReg.
4277     break;
4278   case 1:
4279     if (!AM.HasBaseReg) // allow "r+i".
4280       break;
4281     return false; // disallow "r+r" or "r+r+i".
4282   default:
4283     return false;
4284   }
4285 
4286   return true;
4287 }
4288 
4289 bool
4290 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4291   // The Mips target isn't yet aware of offsets.
4292   return false;
4293 }
4294 
4295 EVT MipsTargetLowering::getOptimalMemOpType(
4296     const MemOp &Op, const AttributeList &FuncAttributes) const {
4297   if (Subtarget.hasMips64())
4298     return MVT::i64;
4299 
4300   return MVT::i32;
4301 }
4302 
4303 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
4304                                       bool ForCodeSize) const {
4305   if (VT != MVT::f32 && VT != MVT::f64)
4306     return false;
4307   if (Imm.isNegZero())
4308     return false;
4309   return Imm.isZero();
4310 }
4311 
4312 unsigned MipsTargetLowering::getJumpTableEncoding() const {
4313 
4314   // FIXME: For space reasons this should be: EK_GPRel32BlockAddress.
4315   if (ABI.IsN64() && isPositionIndependent())
4316     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
4317 
4318   return TargetLowering::getJumpTableEncoding();
4319 }
4320 
4321 bool MipsTargetLowering::useSoftFloat() const {
4322   return Subtarget.useSoftFloat();
4323 }
4324 
4325 void MipsTargetLowering::copyByValRegs(
4326     SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4327     SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4328     SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4329     unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4330     MipsCCState &State) const {
4331   MachineFunction &MF = DAG.getMachineFunction();
4332   MachineFrameInfo &MFI = MF.getFrameInfo();
4333   unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4334   unsigned NumRegs = LastReg - FirstReg;
4335   unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4336   unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4337   int FrameObjOffset;
4338   ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4339 
4340   if (RegAreaSize)
4341     FrameObjOffset =
4342         (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4343         (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4344   else
4345     FrameObjOffset = VA.getLocMemOffset();
4346 
4347   // Create frame object.
4348   EVT PtrTy = getPointerTy(DAG.getDataLayout());
4349   // Make the fixed object stored to mutable so that the load instructions
4350   // referencing it have their memory dependencies added.
4351   // Set the frame object as isAliased which clears the underlying objects
4352   // vector in ScheduleDAGInstrs::buildSchedGraph() resulting in addition of all
4353   // stores as dependencies for loads referencing this fixed object.
4354   int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, false, true);
4355   SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4356   InVals.push_back(FIN);
4357 
4358   if (!NumRegs)
4359     return;
4360 
4361   // Copy arg registers.
4362   MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4363   const TargetRegisterClass *RC = getRegClassFor(RegTy);
4364 
4365   for (unsigned I = 0; I < NumRegs; ++I) {
4366     unsigned ArgReg = ByValArgRegs[FirstReg + I];
4367     unsigned VReg = addLiveIn(MF, ArgReg, RC);
4368     unsigned Offset = I * GPRSizeInBytes;
4369     SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4370                                    DAG.getConstant(Offset, DL, PtrTy));
4371     SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4372                                  StorePtr, MachinePointerInfo(FuncArg, Offset));
4373     OutChains.push_back(Store);
4374   }
4375 }
4376 
4377 // Copy byVal arg to registers and stack.
4378 void MipsTargetLowering::passByValArg(
4379     SDValue Chain, const SDLoc &DL,
4380     std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4381     SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4382     MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4383     unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4384     const CCValAssign &VA) const {
4385   unsigned ByValSizeInBytes = Flags.getByValSize();
4386   unsigned OffsetInBytes = 0; // From beginning of struct
4387   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4388   Align Alignment =
4389       std::min(Flags.getNonZeroByValAlign(), Align(RegSizeInBytes));
4390   EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4391       RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4392   unsigned NumRegs = LastReg - FirstReg;
4393 
4394   if (NumRegs) {
4395     ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
4396     bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4397     unsigned I = 0;
4398 
4399     // Copy words to registers.
4400     for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4401       SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4402                                     DAG.getConstant(OffsetInBytes, DL, PtrTy));
4403       SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4404                                     MachinePointerInfo(), Alignment);
4405       MemOpChains.push_back(LoadVal.getValue(1));
4406       unsigned ArgReg = ArgRegs[FirstReg + I];
4407       RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4408     }
4409 
4410     // Return if the struct has been fully copied.
4411     if (ByValSizeInBytes == OffsetInBytes)
4412       return;
4413 
4414     // Copy the remainder of the byval argument with sub-word loads and shifts.
4415     if (LeftoverBytes) {
4416       SDValue Val;
4417 
4418       for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4419            OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4420         unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4421 
4422         if (RemainingSizeInBytes < LoadSizeInBytes)
4423           continue;
4424 
4425         // Load subword.
4426         SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4427                                       DAG.getConstant(OffsetInBytes, DL,
4428                                                       PtrTy));
4429         SDValue LoadVal = DAG.getExtLoad(
4430             ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4431             MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4432         MemOpChains.push_back(LoadVal.getValue(1));
4433 
4434         // Shift the loaded value.
4435         unsigned Shamt;
4436 
4437         if (isLittle)
4438           Shamt = TotalBytesLoaded * 8;
4439         else
4440           Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4441 
4442         SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4443                                     DAG.getConstant(Shamt, DL, MVT::i32));
4444 
4445         if (Val.getNode())
4446           Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4447         else
4448           Val = Shift;
4449 
4450         OffsetInBytes += LoadSizeInBytes;
4451         TotalBytesLoaded += LoadSizeInBytes;
4452         Alignment = std::min(Alignment, Align(LoadSizeInBytes));
4453       }
4454 
4455       unsigned ArgReg = ArgRegs[FirstReg + I];
4456       RegsToPass.push_back(std::make_pair(ArgReg, Val));
4457       return;
4458     }
4459   }
4460 
4461   // Copy remainder of byval arg to it with memcpy.
4462   unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4463   SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4464                             DAG.getConstant(OffsetInBytes, DL, PtrTy));
4465   SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4466                             DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
4467   Chain = DAG.getMemcpy(
4468       Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, DL, PtrTy),
4469       Align(Alignment), /*isVolatile=*/false, /*AlwaysInline=*/false,
4470       /*isTailCall=*/false, MachinePointerInfo(), MachinePointerInfo());
4471   MemOpChains.push_back(Chain);
4472 }
4473 
4474 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4475                                          SDValue Chain, const SDLoc &DL,
4476                                          SelectionDAG &DAG,
4477                                          CCState &State) const {
4478   ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
4479   unsigned Idx = State.getFirstUnallocated(ArgRegs);
4480   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4481   MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4482   const TargetRegisterClass *RC = getRegClassFor(RegTy);
4483   MachineFunction &MF = DAG.getMachineFunction();
4484   MachineFrameInfo &MFI = MF.getFrameInfo();
4485   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4486 
4487   // Offset of the first variable argument from stack pointer.
4488   int VaArgOffset;
4489 
4490   if (ArgRegs.size() == Idx)
4491     VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
4492   else {
4493     VaArgOffset =
4494         (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4495         (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4496   }
4497 
4498   // Record the frame index of the first variable argument
4499   // which is a value necessary to VASTART.
4500   int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4501   MipsFI->setVarArgsFrameIndex(FI);
4502 
4503   // Copy the integer registers that have not been used for argument passing
4504   // to the argument register save area. For O32, the save area is allocated
4505   // in the caller's stack frame, while for N32/64, it is allocated in the
4506   // callee's stack frame.
4507   for (unsigned I = Idx; I < ArgRegs.size();
4508        ++I, VaArgOffset += RegSizeInBytes) {
4509     unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4510     SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4511     FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4512     SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4513     SDValue Store =
4514         DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4515     cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4516         (Value *)nullptr);
4517     OutChains.push_back(Store);
4518   }
4519 }
4520 
4521 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
4522                                      Align Alignment) const {
4523   const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4524 
4525   assert(Size && "Byval argument's size shouldn't be 0.");
4526 
4527   Alignment = std::min(Alignment, TFL->getStackAlign());
4528 
4529   unsigned FirstReg = 0;
4530   unsigned NumRegs = 0;
4531 
4532   if (State->getCallingConv() != CallingConv::Fast) {
4533     unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4534     ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4535     // FIXME: The O32 case actually describes no shadow registers.
4536     const MCPhysReg *ShadowRegs =
4537         ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4538 
4539     // We used to check the size as well but we can't do that anymore since
4540     // CCState::HandleByVal() rounds up the size after calling this function.
4541     assert(
4542         Alignment >= Align(RegSizeInBytes) &&
4543         "Byval argument's alignment should be a multiple of RegSizeInBytes.");
4544 
4545     FirstReg = State->getFirstUnallocated(IntArgRegs);
4546 
4547     // If Alignment > RegSizeInBytes, the first arg register must be even.
4548     // FIXME: This condition happens to do the right thing but it's not the
4549     //        right way to test it. We want to check that the stack frame offset
4550     //        of the register is aligned.
4551     if ((Alignment > RegSizeInBytes) && (FirstReg % 2)) {
4552       State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4553       ++FirstReg;
4554     }
4555 
4556     // Mark the registers allocated.
4557     Size = alignTo(Size, RegSizeInBytes);
4558     for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4559          Size -= RegSizeInBytes, ++I, ++NumRegs)
4560       State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4561   }
4562 
4563   State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4564 }
4565 
4566 MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4567                                                         MachineBasicBlock *BB,
4568                                                         bool isFPCmp,
4569                                                         unsigned Opc) const {
4570   assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4571          "Subtarget already supports SELECT nodes with the use of"
4572          "conditional-move instructions.");
4573 
4574   const TargetInstrInfo *TII =
4575       Subtarget.getInstrInfo();
4576   DebugLoc DL = MI.getDebugLoc();
4577 
4578   // To "insert" a SELECT instruction, we actually have to insert the
4579   // diamond control-flow pattern.  The incoming instruction knows the
4580   // destination vreg to set, the condition code register to branch on, the
4581   // true/false values to select between, and a branch opcode to use.
4582   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4583   MachineFunction::iterator It = ++BB->getIterator();
4584 
4585   //  thisMBB:
4586   //  ...
4587   //   TrueVal = ...
4588   //   setcc r1, r2, r3
4589   //   bNE   r1, r0, copy1MBB
4590   //   fallthrough --> copy0MBB
4591   MachineBasicBlock *thisMBB  = BB;
4592   MachineFunction *F = BB->getParent();
4593   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4594   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
4595   F->insert(It, copy0MBB);
4596   F->insert(It, sinkMBB);
4597 
4598   // Transfer the remainder of BB and its successor edges to sinkMBB.
4599   sinkMBB->splice(sinkMBB->begin(), BB,
4600                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
4601   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4602 
4603   // Next, add the true and fallthrough blocks as its successors.
4604   BB->addSuccessor(copy0MBB);
4605   BB->addSuccessor(sinkMBB);
4606 
4607   if (isFPCmp) {
4608     // bc1[tf] cc, sinkMBB
4609     BuildMI(BB, DL, TII->get(Opc))
4610         .addReg(MI.getOperand(1).getReg())
4611         .addMBB(sinkMBB);
4612   } else {
4613     // bne rs, $0, sinkMBB
4614     BuildMI(BB, DL, TII->get(Opc))
4615         .addReg(MI.getOperand(1).getReg())
4616         .addReg(Mips::ZERO)
4617         .addMBB(sinkMBB);
4618   }
4619 
4620   //  copy0MBB:
4621   //   %FalseValue = ...
4622   //   # fallthrough to sinkMBB
4623   BB = copy0MBB;
4624 
4625   // Update machine-CFG edges
4626   BB->addSuccessor(sinkMBB);
4627 
4628   //  sinkMBB:
4629   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4630   //  ...
4631   BB = sinkMBB;
4632 
4633   BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4634       .addReg(MI.getOperand(2).getReg())
4635       .addMBB(thisMBB)
4636       .addReg(MI.getOperand(3).getReg())
4637       .addMBB(copy0MBB);
4638 
4639   MI.eraseFromParent(); // The pseudo instruction is gone now.
4640 
4641   return BB;
4642 }
4643 
4644 MachineBasicBlock *
4645 MipsTargetLowering::emitPseudoD_SELECT(MachineInstr &MI,
4646                                        MachineBasicBlock *BB) const {
4647   assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4648          "Subtarget already supports SELECT nodes with the use of"
4649          "conditional-move instructions.");
4650 
4651   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4652   DebugLoc DL = MI.getDebugLoc();
4653 
4654   // D_SELECT substitutes two SELECT nodes that goes one after another and
4655   // have the same condition operand. On machines which don't have
4656   // conditional-move instruction, it reduces unnecessary branch instructions
4657   // which are result of using two diamond patterns that are result of two
4658   // SELECT pseudo instructions.
4659   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4660   MachineFunction::iterator It = ++BB->getIterator();
4661 
4662   //  thisMBB:
4663   //  ...
4664   //   TrueVal = ...
4665   //   setcc r1, r2, r3
4666   //   bNE   r1, r0, copy1MBB
4667   //   fallthrough --> copy0MBB
4668   MachineBasicBlock *thisMBB = BB;
4669   MachineFunction *F = BB->getParent();
4670   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4671   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4672   F->insert(It, copy0MBB);
4673   F->insert(It, sinkMBB);
4674 
4675   // Transfer the remainder of BB and its successor edges to sinkMBB.
4676   sinkMBB->splice(sinkMBB->begin(), BB,
4677                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
4678   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4679 
4680   // Next, add the true and fallthrough blocks as its successors.
4681   BB->addSuccessor(copy0MBB);
4682   BB->addSuccessor(sinkMBB);
4683 
4684   // bne rs, $0, sinkMBB
4685   BuildMI(BB, DL, TII->get(Mips::BNE))
4686       .addReg(MI.getOperand(2).getReg())
4687       .addReg(Mips::ZERO)
4688       .addMBB(sinkMBB);
4689 
4690   //  copy0MBB:
4691   //   %FalseValue = ...
4692   //   # fallthrough to sinkMBB
4693   BB = copy0MBB;
4694 
4695   // Update machine-CFG edges
4696   BB->addSuccessor(sinkMBB);
4697 
4698   //  sinkMBB:
4699   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4700   //  ...
4701   BB = sinkMBB;
4702 
4703   // Use two PHI nodes to select two reults
4704   BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4705       .addReg(MI.getOperand(3).getReg())
4706       .addMBB(thisMBB)
4707       .addReg(MI.getOperand(5).getReg())
4708       .addMBB(copy0MBB);
4709   BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(1).getReg())
4710       .addReg(MI.getOperand(4).getReg())
4711       .addMBB(thisMBB)
4712       .addReg(MI.getOperand(6).getReg())
4713       .addMBB(copy0MBB);
4714 
4715   MI.eraseFromParent(); // The pseudo instruction is gone now.
4716 
4717   return BB;
4718 }
4719 
4720 // FIXME? Maybe this could be a TableGen attribute on some registers and
4721 // this table could be generated automatically from RegInfo.
4722 Register
4723 MipsTargetLowering::getRegisterByName(const char *RegName, LLT VT,
4724                                       const MachineFunction &MF) const {
4725   // The Linux kernel uses $28 and sp.
4726   if (Subtarget.isGP64bit()) {
4727     Register Reg = StringSwitch<Register>(RegName)
4728                        .Case("$28", Mips::GP_64)
4729                        .Case("sp", Mips::SP_64)
4730                        .Default(Register());
4731     if (Reg)
4732       return Reg;
4733   } else {
4734     Register Reg = StringSwitch<Register>(RegName)
4735                        .Case("$28", Mips::GP)
4736                        .Case("sp", Mips::SP)
4737                        .Default(Register());
4738     if (Reg)
4739       return Reg;
4740   }
4741   report_fatal_error("Invalid register name global variable");
4742 }
4743 
4744 MachineBasicBlock *MipsTargetLowering::emitLDR_W(MachineInstr &MI,
4745                                                  MachineBasicBlock *BB) const {
4746   MachineFunction *MF = BB->getParent();
4747   MachineRegisterInfo &MRI = MF->getRegInfo();
4748   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4749   const bool IsLittle = Subtarget.isLittle();
4750   DebugLoc DL = MI.getDebugLoc();
4751 
4752   Register Dest = MI.getOperand(0).getReg();
4753   Register Address = MI.getOperand(1).getReg();
4754   unsigned Imm = MI.getOperand(2).getImm();
4755 
4756   MachineBasicBlock::iterator I(MI);
4757 
4758   if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
4759     // Mips release 6 can load from adress that is not naturally-aligned.
4760     Register Temp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4761     BuildMI(*BB, I, DL, TII->get(Mips::LW))
4762         .addDef(Temp)
4763         .addUse(Address)
4764         .addImm(Imm);
4765     BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(Temp);
4766   } else {
4767     // Mips release 5 needs to use instructions that can load from an unaligned
4768     // memory address.
4769     Register LoadHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4770     Register LoadFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4771     Register Undef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4772     BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(Undef);
4773     BuildMI(*BB, I, DL, TII->get(Mips::LWR))
4774         .addDef(LoadHalf)
4775         .addUse(Address)
4776         .addImm(Imm + (IsLittle ? 0 : 3))
4777         .addUse(Undef);
4778     BuildMI(*BB, I, DL, TII->get(Mips::LWL))
4779         .addDef(LoadFull)
4780         .addUse(Address)
4781         .addImm(Imm + (IsLittle ? 3 : 0))
4782         .addUse(LoadHalf);
4783     BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(LoadFull);
4784   }
4785 
4786   MI.eraseFromParent();
4787   return BB;
4788 }
4789 
4790 MachineBasicBlock *MipsTargetLowering::emitLDR_D(MachineInstr &MI,
4791                                                  MachineBasicBlock *BB) const {
4792   MachineFunction *MF = BB->getParent();
4793   MachineRegisterInfo &MRI = MF->getRegInfo();
4794   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4795   const bool IsLittle = Subtarget.isLittle();
4796   DebugLoc DL = MI.getDebugLoc();
4797 
4798   Register Dest = MI.getOperand(0).getReg();
4799   Register Address = MI.getOperand(1).getReg();
4800   unsigned Imm = MI.getOperand(2).getImm();
4801 
4802   MachineBasicBlock::iterator I(MI);
4803 
4804   if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
4805     // Mips release 6 can load from adress that is not naturally-aligned.
4806     if (Subtarget.isGP64bit()) {
4807       Register Temp = MRI.createVirtualRegister(&Mips::GPR64RegClass);
4808       BuildMI(*BB, I, DL, TII->get(Mips::LD))
4809           .addDef(Temp)
4810           .addUse(Address)
4811           .addImm(Imm);
4812       BuildMI(*BB, I, DL, TII->get(Mips::FILL_D)).addDef(Dest).addUse(Temp);
4813     } else {
4814       Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
4815       Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4816       Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4817       BuildMI(*BB, I, DL, TII->get(Mips::LW))
4818           .addDef(Lo)
4819           .addUse(Address)
4820           .addImm(Imm + (IsLittle ? 0 : 4));
4821       BuildMI(*BB, I, DL, TII->get(Mips::LW))
4822           .addDef(Hi)
4823           .addUse(Address)
4824           .addImm(Imm + (IsLittle ? 4 : 0));
4825       BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(Lo);
4826       BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest)
4827           .addUse(Wtemp)
4828           .addUse(Hi)
4829           .addImm(1);
4830     }
4831   } else {
4832     // Mips release 5 needs to use instructions that can load from an unaligned
4833     // memory address.
4834     Register LoHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4835     Register LoFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4836     Register LoUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4837     Register HiHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4838     Register HiFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4839     Register HiUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4840     Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
4841     BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(LoUndef);
4842     BuildMI(*BB, I, DL, TII->get(Mips::LWR))
4843         .addDef(LoHalf)
4844         .addUse(Address)
4845         .addImm(Imm + (IsLittle ? 0 : 7))
4846         .addUse(LoUndef);
4847     BuildMI(*BB, I, DL, TII->get(Mips::LWL))
4848         .addDef(LoFull)
4849         .addUse(Address)
4850         .addImm(Imm + (IsLittle ? 3 : 4))
4851         .addUse(LoHalf);
4852     BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(HiUndef);
4853     BuildMI(*BB, I, DL, TII->get(Mips::LWR))
4854         .addDef(HiHalf)
4855         .addUse(Address)
4856         .addImm(Imm + (IsLittle ? 4 : 3))
4857         .addUse(HiUndef);
4858     BuildMI(*BB, I, DL, TII->get(Mips::LWL))
4859         .addDef(HiFull)
4860         .addUse(Address)
4861         .addImm(Imm + (IsLittle ? 7 : 0))
4862         .addUse(HiHalf);
4863     BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(LoFull);
4864     BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest)
4865         .addUse(Wtemp)
4866         .addUse(HiFull)
4867         .addImm(1);
4868   }
4869 
4870   MI.eraseFromParent();
4871   return BB;
4872 }
4873 
4874 MachineBasicBlock *MipsTargetLowering::emitSTR_W(MachineInstr &MI,
4875                                                  MachineBasicBlock *BB) const {
4876   MachineFunction *MF = BB->getParent();
4877   MachineRegisterInfo &MRI = MF->getRegInfo();
4878   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4879   const bool IsLittle = Subtarget.isLittle();
4880   DebugLoc DL = MI.getDebugLoc();
4881 
4882   Register StoreVal = MI.getOperand(0).getReg();
4883   Register Address = MI.getOperand(1).getReg();
4884   unsigned Imm = MI.getOperand(2).getImm();
4885 
4886   MachineBasicBlock::iterator I(MI);
4887 
4888   if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
4889     // Mips release 6 can store to adress that is not naturally-aligned.
4890     Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
4891     Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4892     BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(BitcastW).addUse(StoreVal);
4893     BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4894         .addDef(Tmp)
4895         .addUse(BitcastW)
4896         .addImm(0);
4897     BuildMI(*BB, I, DL, TII->get(Mips::SW))
4898         .addUse(Tmp)
4899         .addUse(Address)
4900         .addImm(Imm);
4901   } else {
4902     // Mips release 5 needs to use instructions that can store to an unaligned
4903     // memory address.
4904     Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4905     BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4906         .addDef(Tmp)
4907         .addUse(StoreVal)
4908         .addImm(0);
4909     BuildMI(*BB, I, DL, TII->get(Mips::SWR))
4910         .addUse(Tmp)
4911         .addUse(Address)
4912         .addImm(Imm + (IsLittle ? 0 : 3));
4913     BuildMI(*BB, I, DL, TII->get(Mips::SWL))
4914         .addUse(Tmp)
4915         .addUse(Address)
4916         .addImm(Imm + (IsLittle ? 3 : 0));
4917   }
4918 
4919   MI.eraseFromParent();
4920 
4921   return BB;
4922 }
4923 
4924 MachineBasicBlock *MipsTargetLowering::emitSTR_D(MachineInstr &MI,
4925                                                  MachineBasicBlock *BB) const {
4926   MachineFunction *MF = BB->getParent();
4927   MachineRegisterInfo &MRI = MF->getRegInfo();
4928   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4929   const bool IsLittle = Subtarget.isLittle();
4930   DebugLoc DL = MI.getDebugLoc();
4931 
4932   Register StoreVal = MI.getOperand(0).getReg();
4933   Register Address = MI.getOperand(1).getReg();
4934   unsigned Imm = MI.getOperand(2).getImm();
4935 
4936   MachineBasicBlock::iterator I(MI);
4937 
4938   if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
4939     // Mips release 6 can store to adress that is not naturally-aligned.
4940     if (Subtarget.isGP64bit()) {
4941       Register BitcastD = MRI.createVirtualRegister(&Mips::MSA128DRegClass);
4942       Register Lo = MRI.createVirtualRegister(&Mips::GPR64RegClass);
4943       BuildMI(*BB, I, DL, TII->get(Mips::COPY))
4944           .addDef(BitcastD)
4945           .addUse(StoreVal);
4946       BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_D))
4947           .addDef(Lo)
4948           .addUse(BitcastD)
4949           .addImm(0);
4950       BuildMI(*BB, I, DL, TII->get(Mips::SD))
4951           .addUse(Lo)
4952           .addUse(Address)
4953           .addImm(Imm);
4954     } else {
4955       Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
4956       Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4957       Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4958       BuildMI(*BB, I, DL, TII->get(Mips::COPY))
4959           .addDef(BitcastW)
4960           .addUse(StoreVal);
4961       BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4962           .addDef(Lo)
4963           .addUse(BitcastW)
4964           .addImm(0);
4965       BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4966           .addDef(Hi)
4967           .addUse(BitcastW)
4968           .addImm(1);
4969       BuildMI(*BB, I, DL, TII->get(Mips::SW))
4970           .addUse(Lo)
4971           .addUse(Address)
4972           .addImm(Imm + (IsLittle ? 0 : 4));
4973       BuildMI(*BB, I, DL, TII->get(Mips::SW))
4974           .addUse(Hi)
4975           .addUse(Address)
4976           .addImm(Imm + (IsLittle ? 4 : 0));
4977     }
4978   } else {
4979     // Mips release 5 needs to use instructions that can store to an unaligned
4980     // memory address.
4981     Register Bitcast = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
4982     Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4983     Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4984     BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(Bitcast).addUse(StoreVal);
4985     BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4986         .addDef(Lo)
4987         .addUse(Bitcast)
4988         .addImm(0);
4989     BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4990         .addDef(Hi)
4991         .addUse(Bitcast)
4992         .addImm(1);
4993     BuildMI(*BB, I, DL, TII->get(Mips::SWR))
4994         .addUse(Lo)
4995         .addUse(Address)
4996         .addImm(Imm + (IsLittle ? 0 : 3));
4997     BuildMI(*BB, I, DL, TII->get(Mips::SWL))
4998         .addUse(Lo)
4999         .addUse(Address)
5000         .addImm(Imm + (IsLittle ? 3 : 0));
5001     BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5002         .addUse(Hi)
5003         .addUse(Address)
5004         .addImm(Imm + (IsLittle ? 4 : 7));
5005     BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5006         .addUse(Hi)
5007         .addUse(Address)
5008         .addImm(Imm + (IsLittle ? 7 : 4));
5009   }
5010 
5011   MI.eraseFromParent();
5012   return BB;
5013 }
5014