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