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