LLVM  9.0.0svn
MipsISelLowering.cpp
Go to the documentation of this file.
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"
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"
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"
64 #include "llvm/Support/Compiler.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 
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.
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 
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 
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 
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 
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, ...).
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())
317 
318  // Load extented operations for i1 types must be promoted
319  for (MVT VT : MVT::integer_valuetypes()) {
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()) {
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 
341 
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.
349 
350  // Mips Custom Operations
366 
367  if (!(TM.Options.NoNaNsFPMath || Subtarget.inAbs2008Mode())) {
370  }
371 
372  if (Subtarget.isGP64bit()) {
385  }
386 
387  if (!Subtarget.isGP64bit()) {
391  }
392 
394  if (Subtarget.isGP64bit())
396 
405 
406  // Operations not directly supported by Mips.
420  if (Subtarget.hasCnMips()) {
423  } else {
426  }
433 
434  if (!Subtarget.hasMips32r2())
436 
437  if (!Subtarget.hasMips64r2())
439 
456 
457  // Lower f16 conversion operations into library calls
462 
464 
469 
470  // Use the default for now
473 
474  if (!Subtarget.isGP64bit()) {
477  }
478 
479  if (!Subtarget.hasMips32r2()) {
482  }
483 
484  // MIPS16 lacks MIPS32's clz and clo instructions.
487  if (!Subtarget.hasMips64())
489 
490  if (!Subtarget.hasMips32r2())
492  if (!Subtarget.hasMips64r2())
494 
495  if (Subtarget.isGP64bit()) {
500  }
501 
503 
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 
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 
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 *
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() &&
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 
563  EVT VT) const {
564  if (!VT.isVector())
565  return MVT::i32;
567 }
568 
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 :
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 
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.
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.
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 
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 
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 :
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 
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 
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 
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 
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 
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) ||
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 
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 
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 
1186  return Subtarget.hasMips32();
1187 }
1188 
1190  return Subtarget.hasMips32();
1191 }
1192 
1193 void
1196  SelectionDAG &DAG) const {
1197  SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1198 
1199  for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1200  Results.push_back(Res.getValue(I));
1201 }
1202 
1203 void
1206  SelectionDAG &DAG) const {
1207  return LowerOperationWrapper(N, Results, DAG);
1208 }
1209 
1212 {
1213  switch (Op.getOpcode())
1214  {
1215  case ISD::BRCOND: return lowerBRCOND(Op, DAG);
1216  case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
1217  case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
1218  case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
1219  case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
1220  case ISD::JumpTable: return lowerJumpTable(Op, DAG);
1221  case ISD::SELECT: return lowerSELECT(Op, DAG);
1222  case ISD::SETCC: return lowerSETCC(Op, DAG);
1223  case ISD::VASTART: return lowerVASTART(Op, DAG);
1224  case ISD::VAARG: return lowerVAARG(Op, DAG);
1225  case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
1226  case ISD::FABS: return lowerFABS(Op, DAG);
1227  case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
1228  case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
1229  case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
1230  case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
1231  case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
1232  case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
1233  case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
1234  case ISD::LOAD: return lowerLOAD(Op, DAG);
1235  case ISD::STORE: return lowerSTORE(Op, DAG);
1236  case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG);
1237  case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
1238  }
1239  return SDValue();
1240 }
1241 
1242 //===----------------------------------------------------------------------===//
1243 // Lower helper functions
1244 //===----------------------------------------------------------------------===//
1245 
1246 // addLiveIn - This helper function adds the specified physical register to the
1247 // MachineFunction as a live in value. It also creates a corresponding
1248 // virtual register for it.
1249 static unsigned
1250 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1251 {
1252  unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1253  MF.getRegInfo().addLiveIn(PReg, VReg);
1254  return VReg;
1255 }
1256 
1258  MachineBasicBlock &MBB,
1259  const TargetInstrInfo &TII,
1260  bool Is64Bit, bool IsMicroMips) {
1261  if (NoZeroDivCheck)
1262  return &MBB;
1263 
1264  // Insert instruction "teq $divisor_reg, $zero, 7".
1266  MachineInstrBuilder MIB;
1267  MachineOperand &Divisor = MI.getOperand(2);
1268  MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1269  TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ))
1270  .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1271  .addReg(Mips::ZERO)
1272  .addImm(7);
1273 
1274  // Use the 32-bit sub-register if this is a 64-bit division.
1275  if (Is64Bit)
1276  MIB->getOperand(0).setSubReg(Mips::sub_32);
1277 
1278  // Clear Divisor's kill flag.
1279  Divisor.setIsKill(false);
1280 
1281  // We would normally delete the original instruction here but in this case
1282  // we only needed to inject an additional instruction rather than replace it.
1283 
1284  return &MBB;
1285 }
1286 
1289  MachineBasicBlock *BB) const {
1290  switch (MI.getOpcode()) {
1291  default:
1292  llvm_unreachable("Unexpected instr type to insert");
1293  case Mips::ATOMIC_LOAD_ADD_I8:
1294  return emitAtomicBinaryPartword(MI, BB, 1);
1295  case Mips::ATOMIC_LOAD_ADD_I16:
1296  return emitAtomicBinaryPartword(MI, BB, 2);
1297  case Mips::ATOMIC_LOAD_ADD_I32:
1298  return emitAtomicBinary(MI, BB);
1299  case Mips::ATOMIC_LOAD_ADD_I64:
1300  return emitAtomicBinary(MI, BB);
1301 
1302  case Mips::ATOMIC_LOAD_AND_I8:
1303  return emitAtomicBinaryPartword(MI, BB, 1);
1304  case Mips::ATOMIC_LOAD_AND_I16:
1305  return emitAtomicBinaryPartword(MI, BB, 2);
1306  case Mips::ATOMIC_LOAD_AND_I32:
1307  return emitAtomicBinary(MI, BB);
1308  case Mips::ATOMIC_LOAD_AND_I64:
1309  return emitAtomicBinary(MI, BB);
1310 
1311  case Mips::ATOMIC_LOAD_OR_I8:
1312  return emitAtomicBinaryPartword(MI, BB, 1);
1313  case Mips::ATOMIC_LOAD_OR_I16:
1314  return emitAtomicBinaryPartword(MI, BB, 2);
1315  case Mips::ATOMIC_LOAD_OR_I32:
1316  return emitAtomicBinary(MI, BB);
1317  case Mips::ATOMIC_LOAD_OR_I64:
1318  return emitAtomicBinary(MI, BB);
1319 
1320  case Mips::ATOMIC_LOAD_XOR_I8:
1321  return emitAtomicBinaryPartword(MI, BB, 1);
1322  case Mips::ATOMIC_LOAD_XOR_I16:
1323  return emitAtomicBinaryPartword(MI, BB, 2);
1324  case Mips::ATOMIC_LOAD_XOR_I32:
1325  return emitAtomicBinary(MI, BB);
1326  case Mips::ATOMIC_LOAD_XOR_I64:
1327  return emitAtomicBinary(MI, BB);
1328 
1329  case Mips::ATOMIC_LOAD_NAND_I8:
1330  return emitAtomicBinaryPartword(MI, BB, 1);
1331  case Mips::ATOMIC_LOAD_NAND_I16:
1332  return emitAtomicBinaryPartword(MI, BB, 2);
1333  case Mips::ATOMIC_LOAD_NAND_I32:
1334  return emitAtomicBinary(MI, BB);
1335  case Mips::ATOMIC_LOAD_NAND_I64:
1336  return emitAtomicBinary(MI, BB);
1337 
1338  case Mips::ATOMIC_LOAD_SUB_I8:
1339  return emitAtomicBinaryPartword(MI, BB, 1);
1340  case Mips::ATOMIC_LOAD_SUB_I16:
1341  return emitAtomicBinaryPartword(MI, BB, 2);
1342  case Mips::ATOMIC_LOAD_SUB_I32:
1343  return emitAtomicBinary(MI, BB);
1344  case Mips::ATOMIC_LOAD_SUB_I64:
1345  return emitAtomicBinary(MI, BB);
1346 
1347  case Mips::ATOMIC_SWAP_I8:
1348  return emitAtomicBinaryPartword(MI, BB, 1);
1349  case Mips::ATOMIC_SWAP_I16:
1350  return emitAtomicBinaryPartword(MI, BB, 2);
1351  case Mips::ATOMIC_SWAP_I32:
1352  return emitAtomicBinary(MI, BB);
1353  case Mips::ATOMIC_SWAP_I64:
1354  return emitAtomicBinary(MI, BB);
1355 
1356  case Mips::ATOMIC_CMP_SWAP_I8:
1357  return emitAtomicCmpSwapPartword(MI, BB, 1);
1358  case Mips::ATOMIC_CMP_SWAP_I16:
1359  return emitAtomicCmpSwapPartword(MI, BB, 2);
1360  case Mips::ATOMIC_CMP_SWAP_I32:
1361  return emitAtomicCmpSwap(MI, BB);
1362  case Mips::ATOMIC_CMP_SWAP_I64:
1363  return emitAtomicCmpSwap(MI, BB);
1364  case Mips::PseudoSDIV:
1365  case Mips::PseudoUDIV:
1366  case Mips::DIV:
1367  case Mips::DIVU:
1368  case Mips::MOD:
1369  case Mips::MODU:
1370  return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1371  false);
1372  case Mips::SDIV_MM_Pseudo:
1373  case Mips::UDIV_MM_Pseudo:
1374  case Mips::SDIV_MM:
1375  case Mips::UDIV_MM:
1376  case Mips::DIV_MMR6:
1377  case Mips::DIVU_MMR6:
1378  case Mips::MOD_MMR6:
1379  case Mips::MODU_MMR6:
1380  return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true);
1381  case Mips::PseudoDSDIV:
1382  case Mips::PseudoDUDIV:
1383  case Mips::DDIV:
1384  case Mips::DDIVU:
1385  case Mips::DMOD:
1386  case Mips::DMODU:
1387  return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false);
1388 
1389  case Mips::PseudoSELECT_I:
1390  case Mips::PseudoSELECT_I64:
1391  case Mips::PseudoSELECT_S:
1392  case Mips::PseudoSELECT_D32:
1393  case Mips::PseudoSELECT_D64:
1394  return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1395  case Mips::PseudoSELECTFP_F_I:
1396  case Mips::PseudoSELECTFP_F_I64:
1397  case Mips::PseudoSELECTFP_F_S:
1398  case Mips::PseudoSELECTFP_F_D32:
1399  case Mips::PseudoSELECTFP_F_D64:
1400  return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1401  case Mips::PseudoSELECTFP_T_I:
1402  case Mips::PseudoSELECTFP_T_I64:
1403  case Mips::PseudoSELECTFP_T_S:
1404  case Mips::PseudoSELECTFP_T_D32:
1405  case Mips::PseudoSELECTFP_T_D64:
1406  return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1407  case Mips::PseudoD_SELECT_I:
1408  case Mips::PseudoD_SELECT_I64:
1409  return emitPseudoD_SELECT(MI, BB);
1410  }
1411 }
1412 
1413 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1414 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1416 MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1417  MachineBasicBlock *BB) const {
1418 
1419  MachineFunction *MF = BB->getParent();
1420  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1422  DebugLoc DL = MI.getDebugLoc();
1423 
1424  unsigned AtomicOp;
1425  switch (MI.getOpcode()) {
1426  case Mips::ATOMIC_LOAD_ADD_I32:
1427  AtomicOp = Mips::ATOMIC_LOAD_ADD_I32_POSTRA;
1428  break;
1429  case Mips::ATOMIC_LOAD_SUB_I32:
1430  AtomicOp = Mips::ATOMIC_LOAD_SUB_I32_POSTRA;
1431  break;
1432  case Mips::ATOMIC_LOAD_AND_I32:
1433  AtomicOp = Mips::ATOMIC_LOAD_AND_I32_POSTRA;
1434  break;
1435  case Mips::ATOMIC_LOAD_OR_I32:
1436  AtomicOp = Mips::ATOMIC_LOAD_OR_I32_POSTRA;
1437  break;
1438  case Mips::ATOMIC_LOAD_XOR_I32:
1439  AtomicOp = Mips::ATOMIC_LOAD_XOR_I32_POSTRA;
1440  break;
1441  case Mips::ATOMIC_LOAD_NAND_I32:
1442  AtomicOp = Mips::ATOMIC_LOAD_NAND_I32_POSTRA;
1443  break;
1444  case Mips::ATOMIC_SWAP_I32:
1445  AtomicOp = Mips::ATOMIC_SWAP_I32_POSTRA;
1446  break;
1447  case Mips::ATOMIC_LOAD_ADD_I64:
1448  AtomicOp = Mips::ATOMIC_LOAD_ADD_I64_POSTRA;
1449  break;
1450  case Mips::ATOMIC_LOAD_SUB_I64:
1451  AtomicOp = Mips::ATOMIC_LOAD_SUB_I64_POSTRA;
1452  break;
1453  case Mips::ATOMIC_LOAD_AND_I64:
1454  AtomicOp = Mips::ATOMIC_LOAD_AND_I64_POSTRA;
1455  break;
1456  case Mips::ATOMIC_LOAD_OR_I64:
1457  AtomicOp = Mips::ATOMIC_LOAD_OR_I64_POSTRA;
1458  break;
1459  case Mips::ATOMIC_LOAD_XOR_I64:
1460  AtomicOp = Mips::ATOMIC_LOAD_XOR_I64_POSTRA;
1461  break;
1462  case Mips::ATOMIC_LOAD_NAND_I64:
1463  AtomicOp = Mips::ATOMIC_LOAD_NAND_I64_POSTRA;
1464  break;
1465  case Mips::ATOMIC_SWAP_I64:
1466  AtomicOp = Mips::ATOMIC_SWAP_I64_POSTRA;
1467  break;
1468  default:
1469  llvm_unreachable("Unknown pseudo atomic for replacement!");
1470  }
1471 
1472  unsigned OldVal = MI.getOperand(0).getReg();
1473  unsigned Ptr = MI.getOperand(1).getReg();
1474  unsigned Incr = MI.getOperand(2).getReg();
1475  unsigned Scratch = RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1476 
1478 
1479  // The scratch registers here with the EarlyClobber | Define | Implicit
1480  // flags is used to persuade the register allocator and the machine
1481  // verifier to accept the usage of this register. This has to be a real
1482  // register which has an UNDEF value but is dead after the instruction which
1483  // is unique among the registers chosen for the instruction.
1484 
1485  // The EarlyClobber flag has the semantic properties that the operand it is
1486  // attached to is clobbered before the rest of the inputs are read. Hence it
1487  // must be unique among the operands to the instruction.
1488  // The Define flag is needed to coerce the machine verifier that an Undef
1489  // value isn't a problem.
1490  // The Dead flag is needed as the value in scratch isn't used by any other
1491  // instruction. Kill isn't used as Dead is more precise.
1492  // The implicit flag is here due to the interaction between the other flags
1493  // and the machine verifier.
1494 
1495  // For correctness purpose, a new pseudo is introduced here. We need this
1496  // new pseudo, so that FastRegisterAllocator does not see an ll/sc sequence
1497  // that is spread over >1 basic blocks. A register allocator which
1498  // introduces (or any codegen infact) a store, can violate the expectations
1499  // of the hardware.
1500  //
1501  // An atomic read-modify-write sequence starts with a linked load
1502  // instruction and ends with a store conditional instruction. The atomic
1503  // read-modify-write sequence fails if any of the following conditions
1504  // occur between the execution of ll and sc:
1505  // * A coherent store is completed by another process or coherent I/O
1506  // module into the block of synchronizable physical memory containing
1507  // the word. The size and alignment of the block is
1508  // implementation-dependent.
1509  // * A coherent store is executed between an LL and SC sequence on the
1510  // same processor to the block of synchornizable physical memory
1511  // containing the word.
1512  //
1513 
1514  unsigned PtrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Ptr));
1515  unsigned IncrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Incr));
1516 
1517  BuildMI(*BB, II, DL, TII->get(Mips::COPY), IncrCopy).addReg(Incr);
1518  BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1519 
1520  BuildMI(*BB, II, DL, TII->get(AtomicOp))
1521  .addReg(OldVal, RegState::Define | RegState::EarlyClobber)
1522  .addReg(PtrCopy)
1523  .addReg(IncrCopy)
1526 
1527  MI.eraseFromParent();
1528 
1529  return BB;
1530 }
1531 
1532 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1533  MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1534  unsigned SrcReg) const {
1536  const DebugLoc &DL = MI.getDebugLoc();
1537 
1538  if (Subtarget.hasMips32r2() && Size == 1) {
1539  BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1540  return BB;
1541  }
1542 
1543  if (Subtarget.hasMips32r2() && Size == 2) {
1544  BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1545  return BB;
1546  }
1547 
1548  MachineFunction *MF = BB->getParent();
1549  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1551  unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1552 
1553  assert(Size < 32);
1554  int64_t ShiftImm = 32 - (Size * 8);
1555 
1556  BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1557  BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1558 
1559  return BB;
1560 }
1561 
1562 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1563  MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1564  assert((Size == 1 || Size == 2) &&
1565  "Unsupported size for EmitAtomicBinaryPartial.");
1566 
1567  MachineFunction *MF = BB->getParent();
1568  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1570  const bool ArePtrs64bit = ABI.ArePtrs64bit();
1571  const TargetRegisterClass *RCp =
1572  getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1574  DebugLoc DL = MI.getDebugLoc();
1575 
1576  unsigned Dest = MI.getOperand(0).getReg();
1577  unsigned Ptr = MI.getOperand(1).getReg();
1578  unsigned Incr = MI.getOperand(2).getReg();
1579 
1580  unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1581  unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1582  unsigned Mask = RegInfo.createVirtualRegister(RC);
1583  unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1584  unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1585  unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1586  unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1587  unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1588  unsigned Scratch = RegInfo.createVirtualRegister(RC);
1589  unsigned Scratch2 = RegInfo.createVirtualRegister(RC);
1590  unsigned Scratch3 = RegInfo.createVirtualRegister(RC);
1591 
1592  unsigned AtomicOp = 0;
1593  switch (MI.getOpcode()) {
1594  case Mips::ATOMIC_LOAD_NAND_I8:
1595  AtomicOp = Mips::ATOMIC_LOAD_NAND_I8_POSTRA;
1596  break;
1597  case Mips::ATOMIC_LOAD_NAND_I16:
1598  AtomicOp = Mips::ATOMIC_LOAD_NAND_I16_POSTRA;
1599  break;
1600  case Mips::ATOMIC_SWAP_I8:
1601  AtomicOp = Mips::ATOMIC_SWAP_I8_POSTRA;
1602  break;
1603  case Mips::ATOMIC_SWAP_I16:
1604  AtomicOp = Mips::ATOMIC_SWAP_I16_POSTRA;
1605  break;
1606  case Mips::ATOMIC_LOAD_ADD_I8:
1607  AtomicOp = Mips::ATOMIC_LOAD_ADD_I8_POSTRA;
1608  break;
1609  case Mips::ATOMIC_LOAD_ADD_I16:
1610  AtomicOp = Mips::ATOMIC_LOAD_ADD_I16_POSTRA;
1611  break;
1612  case Mips::ATOMIC_LOAD_SUB_I8:
1613  AtomicOp = Mips::ATOMIC_LOAD_SUB_I8_POSTRA;
1614  break;
1615  case Mips::ATOMIC_LOAD_SUB_I16:
1616  AtomicOp = Mips::ATOMIC_LOAD_SUB_I16_POSTRA;
1617  break;
1618  case Mips::ATOMIC_LOAD_AND_I8:
1619  AtomicOp = Mips::ATOMIC_LOAD_AND_I8_POSTRA;
1620  break;
1621  case Mips::ATOMIC_LOAD_AND_I16:
1622  AtomicOp = Mips::ATOMIC_LOAD_AND_I16_POSTRA;
1623  break;
1624  case Mips::ATOMIC_LOAD_OR_I8:
1625  AtomicOp = Mips::ATOMIC_LOAD_OR_I8_POSTRA;
1626  break;
1627  case Mips::ATOMIC_LOAD_OR_I16:
1628  AtomicOp = Mips::ATOMIC_LOAD_OR_I16_POSTRA;
1629  break;
1630  case Mips::ATOMIC_LOAD_XOR_I8:
1631  AtomicOp = Mips::ATOMIC_LOAD_XOR_I8_POSTRA;
1632  break;
1633  case Mips::ATOMIC_LOAD_XOR_I16:
1634  AtomicOp = Mips::ATOMIC_LOAD_XOR_I16_POSTRA;
1635  break;
1636  default:
1637  llvm_unreachable("Unknown subword atomic pseudo for expansion!");
1638  }
1639 
1640  // insert new blocks after the current block
1641  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1642  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1644  MF->insert(It, exitMBB);
1645 
1646  // Transfer the remainder of BB and its successor edges to exitMBB.
1647  exitMBB->splice(exitMBB->begin(), BB,
1648  std::next(MachineBasicBlock::iterator(MI)), BB->end());
1649  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1650 
1651  BB->addSuccessor(exitMBB, BranchProbability::getOne());
1652 
1653  // thisMBB:
1654  // addiu masklsb2,$0,-4 # 0xfffffffc
1655  // and alignedaddr,ptr,masklsb2
1656  // andi ptrlsb2,ptr,3
1657  // sll shiftamt,ptrlsb2,3
1658  // ori maskupper,$0,255 # 0xff
1659  // sll mask,maskupper,shiftamt
1660  // nor mask2,$0,mask
1661  // sll incr2,incr,shiftamt
1662 
1663  int64_t MaskImm = (Size == 1) ? 255 : 65535;
1664  BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1665  .addReg(ABI.GetNullPtr()).addImm(-4);
1666  BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1667  .addReg(Ptr).addReg(MaskLSB2);
1668  BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1669  .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1670  if (Subtarget.isLittle()) {
1671  BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1672  } else {
1673  unsigned Off = RegInfo.createVirtualRegister(RC);
1674  BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1675  .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1676  BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1677  }
1678  BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1679  .addReg(Mips::ZERO).addImm(MaskImm);
1680  BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1681  .addReg(MaskUpper).addReg(ShiftAmt);
1682  BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1683  BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1684 
1685 
1686  // The purposes of the flags on the scratch registers is explained in
1687  // emitAtomicBinary. In summary, we need a scratch register which is going to
1688  // be undef, that is unique among registers chosen for the instruction.
1689 
1690  BuildMI(BB, DL, TII->get(AtomicOp))
1691  .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1692  .addReg(AlignedAddr)
1693  .addReg(Incr2)
1694  .addReg(Mask)
1695  .addReg(Mask2)
1696  .addReg(ShiftAmt)
1703 
1704  MI.eraseFromParent(); // The instruction is gone now.
1705 
1706  return exitMBB;
1707 }
1708 
1709 // Lower atomic compare and swap to a pseudo instruction, taking care to
1710 // define a scratch register for the pseudo instruction's expansion. The
1711 // instruction is expanded after the register allocator as to prevent
1712 // the insertion of stores between the linked load and the store conditional.
1713 
1715 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1716  MachineBasicBlock *BB) const {
1717 
1718  assert((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ||
1719  MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) &&
1720  "Unsupported atomic psseudo for EmitAtomicCmpSwap.");
1721 
1722  const unsigned Size = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ? 4 : 8;
1723 
1724  MachineFunction *MF = BB->getParent();
1726  const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1728  DebugLoc DL = MI.getDebugLoc();
1729 
1730  unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
1731  ? Mips::ATOMIC_CMP_SWAP_I32_POSTRA
1732  : Mips::ATOMIC_CMP_SWAP_I64_POSTRA;
1733  unsigned Dest = MI.getOperand(0).getReg();
1734  unsigned Ptr = MI.getOperand(1).getReg();
1735  unsigned OldVal = MI.getOperand(2).getReg();
1736  unsigned NewVal = MI.getOperand(3).getReg();
1737 
1738  unsigned Scratch = MRI.createVirtualRegister(RC);
1740 
1741  // We need to create copies of the various registers and kill them at the
1742  // atomic pseudo. If the copies are not made, when the atomic is expanded
1743  // after fast register allocation, the spills will end up outside of the
1744  // blocks that their values are defined in, causing livein errors.
1745 
1746  unsigned DestCopy = MRI.createVirtualRegister(MRI.getRegClass(Dest));
1747  unsigned PtrCopy = MRI.createVirtualRegister(MRI.getRegClass(Ptr));
1748  unsigned OldValCopy = MRI.createVirtualRegister(MRI.getRegClass(OldVal));
1749  unsigned NewValCopy = MRI.createVirtualRegister(MRI.getRegClass(NewVal));
1750 
1751  BuildMI(*BB, II, DL, TII->get(Mips::COPY), DestCopy).addReg(Dest);
1752  BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1753  BuildMI(*BB, II, DL, TII->get(Mips::COPY), OldValCopy).addReg(OldVal);
1754  BuildMI(*BB, II, DL, TII->get(Mips::COPY), NewValCopy).addReg(NewVal);
1755 
1756  // The purposes of the flags on the scratch registers is explained in
1757  // emitAtomicBinary. In summary, we need a scratch register which is going to
1758  // be undef, that is unique among registers chosen for the instruction.
1759 
1760  BuildMI(*BB, II, DL, TII->get(AtomicOp))
1761  .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1762  .addReg(PtrCopy, RegState::Kill)
1763  .addReg(OldValCopy, RegState::Kill)
1764  .addReg(NewValCopy, RegState::Kill)
1767 
1768  MI.eraseFromParent(); // The instruction is gone now.
1769 
1770  return BB;
1771 }
1772 
1773 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1774  MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1775  assert((Size == 1 || Size == 2) &&
1776  "Unsupported size for EmitAtomicCmpSwapPartial.");
1777 
1778  MachineFunction *MF = BB->getParent();
1779  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1781  const bool ArePtrs64bit = ABI.ArePtrs64bit();
1782  const TargetRegisterClass *RCp =
1783  getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1785  DebugLoc DL = MI.getDebugLoc();
1786 
1787  unsigned Dest = MI.getOperand(0).getReg();
1788  unsigned Ptr = MI.getOperand(1).getReg();
1789  unsigned CmpVal = MI.getOperand(2).getReg();
1790  unsigned NewVal = MI.getOperand(3).getReg();
1791 
1792  unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1793  unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1794  unsigned Mask = RegInfo.createVirtualRegister(RC);
1795  unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1796  unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1797  unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1798  unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1799  unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1800  unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1801  unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1802  unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1803  unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I8
1804  ? Mips::ATOMIC_CMP_SWAP_I8_POSTRA
1805  : Mips::ATOMIC_CMP_SWAP_I16_POSTRA;
1806 
1807  // The scratch registers here with the EarlyClobber | Define | Dead | Implicit
1808  // flags are used to coerce the register allocator and the machine verifier to
1809  // accept the usage of these registers.
1810  // The EarlyClobber flag has the semantic properties that the operand it is
1811  // attached to is clobbered before the rest of the inputs are read. Hence it
1812  // must be unique among the operands to the instruction.
1813  // The Define flag is needed to coerce the machine verifier that an Undef
1814  // value isn't a problem.
1815  // The Dead flag is needed as the value in scratch isn't used by any other
1816  // instruction. Kill isn't used as Dead is more precise.
1817  unsigned Scratch = RegInfo.createVirtualRegister(RC);
1818  unsigned Scratch2 = RegInfo.createVirtualRegister(RC);
1819 
1820  // insert new blocks after the current block
1821  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1822  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1824  MF->insert(It, exitMBB);
1825 
1826  // Transfer the remainder of BB and its successor edges to exitMBB.
1827  exitMBB->splice(exitMBB->begin(), BB,
1828  std::next(MachineBasicBlock::iterator(MI)), BB->end());
1829  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1830 
1831  BB->addSuccessor(exitMBB, BranchProbability::getOne());
1832 
1833  // thisMBB:
1834  // addiu masklsb2,$0,-4 # 0xfffffffc
1835  // and alignedaddr,ptr,masklsb2
1836  // andi ptrlsb2,ptr,3
1837  // xori ptrlsb2,ptrlsb2,3 # Only for BE
1838  // sll shiftamt,ptrlsb2,3
1839  // ori maskupper,$0,255 # 0xff
1840  // sll mask,maskupper,shiftamt
1841  // nor mask2,$0,mask
1842  // andi maskedcmpval,cmpval,255
1843  // sll shiftedcmpval,maskedcmpval,shiftamt
1844  // andi maskednewval,newval,255
1845  // sll shiftednewval,maskednewval,shiftamt
1846  int64_t MaskImm = (Size == 1) ? 255 : 65535;
1847  BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1848  .addReg(ABI.GetNullPtr()).addImm(-4);
1849  BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1850  .addReg(Ptr).addReg(MaskLSB2);
1851  BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1852  .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1853  if (Subtarget.isLittle()) {
1854  BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1855  } else {
1856  unsigned Off = RegInfo.createVirtualRegister(RC);
1857  BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1858  .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1859  BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1860  }
1861  BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1862  .addReg(Mips::ZERO).addImm(MaskImm);
1863  BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1864  .addReg(MaskUpper).addReg(ShiftAmt);
1865  BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1866  BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1867  .addReg(CmpVal).addImm(MaskImm);
1868  BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1869  .addReg(MaskedCmpVal).addReg(ShiftAmt);
1870  BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1871  .addReg(NewVal).addImm(MaskImm);
1872  BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1873  .addReg(MaskedNewVal).addReg(ShiftAmt);
1874 
1875  // The purposes of the flags on the scratch registers are explained in
1876  // emitAtomicBinary. In summary, we need a scratch register which is going to
1877  // be undef, that is unique among the register chosen for the instruction.
1878 
1879  BuildMI(BB, DL, TII->get(AtomicOp))
1880  .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1881  .addReg(AlignedAddr)
1882  .addReg(Mask)
1883  .addReg(ShiftedCmpVal)
1884  .addReg(Mask2)
1885  .addReg(ShiftedNewVal)
1886  .addReg(ShiftAmt)
1891 
1892  MI.eraseFromParent(); // The instruction is gone now.
1893 
1894  return exitMBB;
1895 }
1896 
1897 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1898  // The first operand is the chain, the second is the condition, the third is
1899  // the block to branch to if the condition is true.
1900  SDValue Chain = Op.getOperand(0);
1901  SDValue Dest = Op.getOperand(2);
1902  SDLoc DL(Op);
1903 
1905  SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1906 
1907  // Return if flag is not set by a floating point comparison.
1908  if (CondRes.getOpcode() != MipsISD::FPCmp)
1909  return Op;
1910 
1911  SDValue CCNode = CondRes.getOperand(2);
1912  Mips::CondCode CC =
1913  (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1914  unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1915  SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
1916  SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1917  return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1918  FCC0, Dest, CondRes);
1919 }
1920 
1921 SDValue MipsTargetLowering::
1922 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1923 {
1925  SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1926 
1927  // Return if flag is not set by a floating point comparison.
1928  if (Cond.getOpcode() != MipsISD::FPCmp)
1929  return Op;
1930 
1931  return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1932  SDLoc(Op));
1933 }
1934 
1935 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1937  SDValue Cond = createFPCmp(DAG, Op);
1938 
1939  assert(Cond.getOpcode() == MipsISD::FPCmp &&
1940  "Floating point operand expected.");
1941 
1942  SDLoc DL(Op);
1943  SDValue True = DAG.getConstant(1, DL, MVT::i32);
1944  SDValue False = DAG.getConstant(0, DL, MVT::i32);
1945 
1946  return createCMovFP(DAG, Cond, True, False, DL);
1947 }
1948 
1949 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1950  SelectionDAG &DAG) const {
1951  EVT Ty = Op.getValueType();
1952  GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1953  const GlobalValue *GV = N->getGlobal();
1954 
1955  if (!isPositionIndependent()) {
1956  const MipsTargetObjectFile *TLOF =
1957  static_cast<const MipsTargetObjectFile *>(
1959  const GlobalObject *GO = GV->getBaseObject();
1960  if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
1961  // %gp_rel relocation
1962  return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
1963 
1964  // %hi/%lo relocation
1965  return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
1966  // %highest/%higher/%hi/%lo relocation
1967  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
1968  }
1969 
1970  // Every other architecture would use shouldAssumeDSOLocal in here, but
1971  // mips is special.
1972  // * In PIC code mips requires got loads even for local statics!
1973  // * To save on got entries, for local statics the got entry contains the
1974  // page and an additional add instruction takes care of the low bits.
1975  // * It is legal to access a hidden symbol with a non hidden undefined,
1976  // so one cannot guarantee that all access to a hidden symbol will know
1977  // it is hidden.
1978  // * Mips linkers don't support creating a page and a full got entry for
1979  // the same symbol.
1980  // * Given all that, we have to use a full got entry for hidden symbols :-(
1981  if (GV->hasLocalLinkage())
1982  return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1983 
1984  if (LargeGOT)
1985  return getAddrGlobalLargeGOT(
1987  DAG.getEntryNode(),
1988  MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1989 
1990  return getAddrGlobal(
1991  N, SDLoc(N), Ty, DAG,
1993  DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1994 }
1995 
1996 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1997  SelectionDAG &DAG) const {
1998  BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1999  EVT Ty = Op.getValueType();
2000 
2001  if (!isPositionIndependent())
2002  return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2003  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2004 
2005  return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2006 }
2007 
2008 SDValue MipsTargetLowering::
2009 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2010 {
2011  // If the relocation model is PIC, use the General Dynamic TLS Model or
2012  // Local Dynamic TLS model, otherwise use the Initial Exec or
2013  // Local Exec TLS Model.
2014 
2015  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2016  if (DAG.getTarget().useEmulatedTLS())
2017  return LowerToTLSEmulatedModel(GA, DAG);
2018 
2019  SDLoc DL(GA);
2020  const GlobalValue *GV = GA->getGlobal();
2021  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2022 
2024 
2025  if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2026  // General Dynamic and Local Dynamic TLS Model.
2027  unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2028  : MipsII::MO_TLSGD;
2029 
2030  SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2031  SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2032  getGlobalReg(DAG, PtrVT), TGA);
2033  unsigned PtrSize = PtrVT.getSizeInBits();
2034  IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2035 
2036  SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2037 
2038  ArgListTy Args;
2039  ArgListEntry Entry;
2040  Entry.Node = Argument;
2041  Entry.Ty = PtrTy;
2042  Args.push_back(Entry);
2043 
2045  CLI.setDebugLoc(DL)
2046  .setChain(DAG.getEntryNode())
2047  .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2048  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2049 
2050  SDValue Ret = CallResult.first;
2051 
2052  if (model != TLSModel::LocalDynamic)
2053  return Ret;
2054 
2055  SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2057  SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2058  SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2060  SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2061  SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2062  return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2063  }
2064 
2065  SDValue Offset;
2066  if (model == TLSModel::InitialExec) {
2067  // Initial Exec TLS Model
2068  SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2070  TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2071  TGA);
2072  Offset =
2073  DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2074  } else {
2075  // Local Exec TLS Model
2076  assert(model == TLSModel::LocalExec);
2077  SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2079  SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2081  SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2082  SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2083  Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2084  }
2085 
2087  return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2088 }
2089 
2090 SDValue MipsTargetLowering::
2091 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2092 {
2093  JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2094  EVT Ty = Op.getValueType();
2095 
2096  if (!isPositionIndependent())
2097  return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2098  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2099 
2100  return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2101 }
2102 
2103 SDValue MipsTargetLowering::
2104 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2105 {
2106  ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2107  EVT Ty = Op.getValueType();
2108 
2109  if (!isPositionIndependent()) {
2110  const MipsTargetObjectFile *TLOF =
2111  static_cast<const MipsTargetObjectFile *>(
2113 
2114  if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2115  getTargetMachine()))
2116  // %gp_rel relocation
2117  return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2118 
2119  return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2120  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2121  }
2122 
2123  return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2124 }
2125 
2126 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2127  MachineFunction &MF = DAG.getMachineFunction();
2128  MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2129 
2130  SDLoc DL(Op);
2131  SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2132  getPointerTy(MF.getDataLayout()));
2133 
2134  // vastart just stores the address of the VarArgsFrameIndex slot into the
2135  // memory location argument.
2136  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2137  return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2138  MachinePointerInfo(SV));
2139 }
2140 
2141 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2142  SDNode *Node = Op.getNode();
2143  EVT VT = Node->getValueType(0);
2144  SDValue Chain = Node->getOperand(0);
2145  SDValue VAListPtr = Node->getOperand(1);
2146  unsigned Align = Node->getConstantOperandVal(3);
2147  const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2148  SDLoc DL(Node);
2149  unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2150 
2151  SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2152  VAListPtr, MachinePointerInfo(SV));
2153  SDValue VAList = VAListLoad;
2154 
2155  // Re-align the pointer if necessary.
2156  // It should only ever be necessary for 64-bit types on O32 since the minimum
2157  // argument alignment is the same as the maximum type alignment for N32/N64.
2158  //
2159  // FIXME: We currently align too often. The code generator doesn't notice
2160  // when the pointer is still aligned from the last va_arg (or pair of
2161  // va_args for the i64 on O32 case).
2162  if (Align > getMinStackArgumentAlignment()) {
2163  assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
2164 
2165  VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2166  DAG.getConstant(Align - 1, DL, VAList.getValueType()));
2167 
2168  VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
2169  DAG.getConstant(-(int64_t)Align, DL,
2170  VAList.getValueType()));
2171  }
2172 
2173  // Increment the pointer, VAList, to the next vaarg.
2174  auto &TD = DAG.getDataLayout();
2175  unsigned ArgSizeInBytes =
2176  TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
2177  SDValue Tmp3 =
2178  DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2179  DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2180  DL, VAList.getValueType()));
2181  // Store the incremented VAList to the legalized pointer
2182  Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2183  MachinePointerInfo(SV));
2184 
2185  // In big-endian mode we must adjust the pointer when the load size is smaller
2186  // than the argument slot size. We must also reduce the known alignment to
2187  // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2188  // the correct half of the slot, and reduce the alignment from 8 (slot
2189  // alignment) down to 4 (type alignment).
2190  if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2191  unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2192  VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2193  DAG.getIntPtrConstant(Adjustment, DL));
2194  }
2195  // Load the actual argument out of the pointer VAList
2196  return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2197 }
2198 
2200  bool HasExtractInsert) {
2201  EVT TyX = Op.getOperand(0).getValueType();
2202  EVT TyY = Op.getOperand(1).getValueType();
2203  SDLoc DL(Op);
2204  SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2205  SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2206  SDValue Res;
2207 
2208  // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2209  // to i32.
2210  SDValue X = (TyX == MVT::f32) ?
2211  DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2213  Const1);
2214  SDValue Y = (TyY == MVT::f32) ?
2215  DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2217  Const1);
2218 
2219  if (HasExtractInsert) {
2220  // ext E, Y, 31, 1 ; extract bit31 of Y
2221  // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2222  SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2223  Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2224  } else {
2225  // sll SllX, X, 1
2226  // srl SrlX, SllX, 1
2227  // srl SrlY, Y, 31
2228  // sll SllY, SrlX, 31
2229  // or Or, SrlX, SllY
2230  SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2231  SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2232  SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2233  SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2234  Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2235  }
2236 
2237  if (TyX == MVT::f32)
2238  return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2239 
2241  Op.getOperand(0),
2242  DAG.getConstant(0, DL, MVT::i32));
2243  return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2244 }
2245 
2247  bool HasExtractInsert) {
2248  unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2249  unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2250  EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2251  SDLoc DL(Op);
2252  SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2253 
2254  // Bitcast to integer nodes.
2255  SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2256  SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2257 
2258  if (HasExtractInsert) {
2259  // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2260  // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2261  SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2262  DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2263 
2264  if (WidthX > WidthY)
2265  E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2266  else if (WidthY > WidthX)
2267  E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2268 
2269  SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2270  DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2271  X);
2272  return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2273  }
2274 
2275  // (d)sll SllX, X, 1
2276  // (d)srl SrlX, SllX, 1
2277  // (d)srl SrlY, Y, width(Y)-1
2278  // (d)sll SllY, SrlX, width(Y)-1
2279  // or Or, SrlX, SllY
2280  SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2281  SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2282  SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2283  DAG.getConstant(WidthY - 1, DL, MVT::i32));
2284 
2285  if (WidthX > WidthY)
2286  SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2287  else if (WidthY > WidthX)
2288  SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2289 
2290  SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2291  DAG.getConstant(WidthX - 1, DL, MVT::i32));
2292  SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2293  return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2294 }
2295 
2296 SDValue
2297 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2298  if (Subtarget.isGP64bit())
2299  return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2300 
2301  return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2302 }
2303 
2305  bool HasExtractInsert) {
2306  SDLoc DL(Op);
2307  SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2308 
2309  // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2310  // to i32.
2311  SDValue X = (Op.getValueType() == MVT::f32)
2312  ? DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0))
2314  Op.getOperand(0), Const1);
2315 
2316  // Clear MSB.
2317  if (HasExtractInsert)
2318  Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2319  DAG.getRegister(Mips::ZERO, MVT::i32),
2320  DAG.getConstant(31, DL, MVT::i32), Const1, X);
2321  else {
2322  // TODO: Provide DAG patterns which transform (and x, cst)
2323  // back to a (shl (srl x (clz cst)) (clz cst)) sequence.
2324  SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2325  Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2326  }
2327 
2328  if (Op.getValueType() == MVT::f32)
2329  return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2330 
2331  // FIXME: For mips32r2, the sequence of (BuildPairF64 (ins (ExtractElementF64
2332  // Op 1), $zero, 31 1) (ExtractElementF64 Op 0)) and the Op has one use, we
2333  // should be able to drop the usage of mfc1/mtc1 and rewrite the register in
2334  // place.
2335  SDValue LowX =
2337  DAG.getConstant(0, DL, MVT::i32));
2338  return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2339 }
2340 
2342  bool HasExtractInsert) {
2343  SDLoc DL(Op);
2344  SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2345 
2346  // Bitcast to integer node.
2347  SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2348 
2349  // Clear MSB.
2350  if (HasExtractInsert)
2351  Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2352  DAG.getRegister(Mips::ZERO_64, MVT::i64),
2353  DAG.getConstant(63, DL, MVT::i32), Const1, X);
2354  else {
2355  SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2356  Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2357  }
2358 
2359  return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2360 }
2361 
2362 SDValue MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
2363  if ((ABI.IsN32() || ABI.IsN64()) && (Op.getValueType() == MVT::f64))
2364  return lowerFABS64(Op, DAG, Subtarget.hasExtractInsert());
2365 
2366  return lowerFABS32(Op, DAG, Subtarget.hasExtractInsert());
2367 }
2368 
2369 SDValue MipsTargetLowering::
2370 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2371  // check the depth
2372  assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2373  "Frame address can only be determined for current frame.");
2374 
2376  MFI.setFrameAddressIsTaken(true);
2377  EVT VT = Op.getValueType();
2378  SDLoc DL(Op);
2379  SDValue FrameAddr = DAG.getCopyFromReg(
2380  DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2381  return FrameAddr;
2382 }
2383 
2384 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2385  SelectionDAG &DAG) const {
2387  return SDValue();
2388 
2389  // check the depth
2390  assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2391  "Return address can be determined only for current frame.");
2392 
2393  MachineFunction &MF = DAG.getMachineFunction();
2394  MachineFrameInfo &MFI = MF.getFrameInfo();
2395  MVT VT = Op.getSimpleValueType();
2396  unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2397  MFI.setReturnAddressIsTaken(true);
2398 
2399  // Return RA, which contains the return address. Mark it an implicit live-in.
2400  unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2401  return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2402 }
2403 
2404 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2405 // generated from __builtin_eh_return (offset, handler)
2406 // The effect of this is to adjust the stack pointer by "offset"
2407 // and then branch to "handler".
2408 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2409  const {
2410  MachineFunction &MF = DAG.getMachineFunction();
2411  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2412 
2413  MipsFI->setCallsEhReturn();
2414  SDValue Chain = Op.getOperand(0);
2415  SDValue Offset = Op.getOperand(1);
2416  SDValue Handler = Op.getOperand(2);
2417  SDLoc DL(Op);
2418  EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2419 
2420  // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2421  // EH_RETURN nodes, so that instructions are emitted back-to-back.
2422  unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2423  unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2424  Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2425  Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2426  return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2427  DAG.getRegister(OffsetReg, Ty),
2428  DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2429  Chain.getValue(1));
2430 }
2431 
2432 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2433  SelectionDAG &DAG) const {
2434  // FIXME: Need pseudo-fence for 'singlethread' fences
2435  // FIXME: Set SType for weaker fences where supported/appropriate.
2436  unsigned SType = 0;
2437  SDLoc DL(Op);
2438  return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2439  DAG.getConstant(SType, DL, MVT::i32));
2440 }
2441 
2442 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2443  SelectionDAG &DAG) const {
2444  SDLoc DL(Op);
2446 
2447  SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2448  SDValue Shamt = Op.getOperand(2);
2449  // if shamt < (VT.bits):
2450  // lo = (shl lo, shamt)
2451  // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2452  // else:
2453  // lo = 0
2454  // hi = (shl lo, shamt[4:0])
2455  SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2456  DAG.getConstant(-1, DL, MVT::i32));
2457  SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2458  DAG.getConstant(1, DL, VT));
2459  SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2460  SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2461  SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2462  SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2463  SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2464  DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2465  Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2466  DAG.getConstant(0, DL, VT), ShiftLeftLo);
2467  Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2468 
2469  SDValue Ops[2] = {Lo, Hi};
2470  return DAG.getMergeValues(Ops, DL);
2471 }
2472 
2473 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2474  bool IsSRA) const {
2475  SDLoc DL(Op);
2476  SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2477  SDValue Shamt = Op.getOperand(2);
2479 
2480  // if shamt < (VT.bits):
2481  // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2482  // if isSRA:
2483  // hi = (sra hi, shamt)
2484  // else:
2485  // hi = (srl hi, shamt)
2486  // else:
2487  // if isSRA:
2488  // lo = (sra hi, shamt[4:0])
2489  // hi = (sra hi, 31)
2490  // else:
2491  // lo = (srl hi, shamt[4:0])
2492  // hi = 0
2493  SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2494  DAG.getConstant(-1, DL, MVT::i32));
2495  SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2496  DAG.getConstant(1, DL, VT));
2497  SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2498  SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2499  SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2500  SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2501  DL, VT, Hi, Shamt);
2502  SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2503  DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2504  SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2505  DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2506 
2507  if (!(Subtarget.hasMips4() || Subtarget.hasMips32())) {
2508  SDVTList VTList = DAG.getVTList(VT, VT);
2509  return DAG.getNode(Subtarget.isGP64bit() ? Mips::PseudoD_SELECT_I64
2510  : Mips::PseudoD_SELECT_I,
2511  DL, VTList, Cond, ShiftRightHi,
2512  IsSRA ? Ext : DAG.getConstant(0, DL, VT), Or,
2513  ShiftRightHi);
2514  }
2515 
2516  Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2517  Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2518  IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2519 
2520  SDValue Ops[2] = {Lo, Hi};
2521  return DAG.getMergeValues(Ops, DL);
2522 }
2523 
2524 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2525  SDValue Chain, SDValue Src, unsigned Offset) {
2526  SDValue Ptr = LD->getBasePtr();
2527  EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2528  EVT BasePtrVT = Ptr.getValueType();
2529  SDLoc DL(LD);
2530  SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2531 
2532  if (Offset)
2533  Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2534  DAG.getConstant(Offset, DL, BasePtrVT));
2535 
2536  SDValue Ops[] = { Chain, Ptr, Src };
2537  return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2538  LD->getMemOperand());
2539 }
2540 
2541 // Expand an unaligned 32 or 64-bit integer load node.
2543  LoadSDNode *LD = cast<LoadSDNode>(Op);
2544  EVT MemVT = LD->getMemoryVT();
2545 
2547  return Op;
2548 
2549  // Return if load is aligned or if MemVT is neither i32 nor i64.
2550  if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2551  ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2552  return SDValue();
2553 
2554  bool IsLittle = Subtarget.isLittle();
2555  EVT VT = Op.getValueType();
2557  SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2558 
2559  assert((VT == MVT::i32) || (VT == MVT::i64));
2560 
2561  // Expand
2562  // (set dst, (i64 (load baseptr)))
2563  // to
2564  // (set tmp, (ldl (add baseptr, 7), undef))
2565  // (set dst, (ldr baseptr, tmp))
2566  if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2567  SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2568  IsLittle ? 7 : 0);
2569  return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2570  IsLittle ? 0 : 7);
2571  }
2572 
2573  SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2574  IsLittle ? 3 : 0);
2575  SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2576  IsLittle ? 0 : 3);
2577 
2578  // Expand
2579  // (set dst, (i32 (load baseptr))) or
2580  // (set dst, (i64 (sextload baseptr))) or
2581  // (set dst, (i64 (extload baseptr)))
2582  // to
2583  // (set tmp, (lwl (add baseptr, 3), undef))
2584  // (set dst, (lwr baseptr, tmp))
2585  if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2586  (ExtType == ISD::EXTLOAD))
2587  return LWR;
2588 
2589  assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2590 
2591  // Expand
2592  // (set dst, (i64 (zextload baseptr)))
2593  // to
2594  // (set tmp0, (lwl (add baseptr, 3), undef))
2595  // (set tmp1, (lwr baseptr, tmp0))
2596  // (set tmp2, (shl tmp1, 32))
2597  // (set dst, (srl tmp2, 32))
2598  SDLoc DL(LD);
2599  SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2600  SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2601  SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2602  SDValue Ops[] = { SRL, LWR.getValue(1) };
2603  return DAG.getMergeValues(Ops, DL);
2604 }
2605 
2606 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2607  SDValue Chain, unsigned Offset) {
2608  SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2609  EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2610  SDLoc DL(SD);
2611  SDVTList VTList = DAG.getVTList(MVT::Other);
2612 
2613  if (Offset)
2614  Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2615  DAG.getConstant(Offset, DL, BasePtrVT));
2616 
2617  SDValue Ops[] = { Chain, Value, Ptr };
2618  return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2619  SD->getMemOperand());
2620 }
2621 
2622 // Expand an unaligned 32 or 64-bit integer store node.
2624  bool IsLittle) {
2625  SDValue Value = SD->getValue(), Chain = SD->getChain();
2626  EVT VT = Value.getValueType();
2627 
2628  // Expand
2629  // (store val, baseptr) or
2630  // (truncstore val, baseptr)
2631  // to
2632  // (swl val, (add baseptr, 3))
2633  // (swr val, baseptr)
2634  if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2635  SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2636  IsLittle ? 3 : 0);
2637  return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2638  }
2639 
2640  assert(VT == MVT::i64);
2641 
2642  // Expand
2643  // (store val, baseptr)
2644  // to
2645  // (sdl val, (add baseptr, 7))
2646  // (sdr val, baseptr)
2647  SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2648  return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2649 }
2650 
2651 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2653  bool SingleFloat) {
2654  SDValue Val = SD->getValue();
2655 
2656  if (Val.getOpcode() != ISD::FP_TO_SINT ||
2657  (Val.getValueSizeInBits() > 32 && SingleFloat))
2658  return SDValue();
2659 
2661  SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2662  Val.getOperand(0));
2663  return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2664  SD->getPointerInfo(), SD->getAlignment(),
2665  SD->getMemOperand()->getFlags());
2666 }
2667 
2669  StoreSDNode *SD = cast<StoreSDNode>(Op);
2670  EVT MemVT = SD->getMemoryVT();
2671 
2672  // Lower unaligned integer stores.
2674  (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2675  ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2676  return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2677 
2678  return lowerFP_TO_SINT_STORE(SD, DAG, Subtarget.isSingleFloat());
2679 }
2680 
2681 SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2682  SelectionDAG &DAG) const {
2683 
2684  // Return a fixed StackObject with offset 0 which points to the old stack
2685  // pointer.
2687  EVT ValTy = Op->getValueType(0);
2688  int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2689  return DAG.getFrameIndex(FI, ValTy);
2690 }
2691 
2692 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2693  SelectionDAG &DAG) const {
2694  if (Op.getValueSizeInBits() > 32 && Subtarget.isSingleFloat())
2695  return SDValue();
2696 
2698  SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2699  Op.getOperand(0));
2700  return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2701 }
2702 
2703 //===----------------------------------------------------------------------===//
2704 // Calling Convention Implementation
2705 //===----------------------------------------------------------------------===//
2706 
2707 //===----------------------------------------------------------------------===//
2708 // TODO: Implement a generic logic using tblgen that can support this.
2709 // Mips O32 ABI rules:
2710 // ---
2711 // i32 - Passed in A0, A1, A2, A3 and stack
2712 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2713 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2714 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2715 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2716 // not used, it must be shadowed. If only A3 is available, shadow it and
2717 // go to stack.
2718 // vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
2719 // vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
2720 // with the remainder spilled to the stack.
2721 // vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
2722 // spilling the remainder to the stack.
2723 //
2724 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2725 //===----------------------------------------------------------------------===//
2726 
2727 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2728  CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2729  CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2730  const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2731  State.getMachineFunction().getSubtarget());
2732 
2733  static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2734 
2735  const MipsCCState * MipsState = static_cast<MipsCCState *>(&State);
2736 
2737  static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2738 
2739  static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 };
2740 
2741  // Do not process byval args here.
2742  if (ArgFlags.isByVal())
2743  return true;
2744 
2745  // Promote i8 and i16
2746  if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2747  if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2748  LocVT = MVT::i32;
2749  if (ArgFlags.isSExt())
2750  LocInfo = CCValAssign::SExtUpper;
2751  else if (ArgFlags.isZExt())
2752  LocInfo = CCValAssign::ZExtUpper;
2753  else
2754  LocInfo = CCValAssign::AExtUpper;
2755  }
2756  }
2757 
2758  // Promote i8 and i16
2759  if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2760  LocVT = MVT::i32;
2761  if (ArgFlags.isSExt())
2762  LocInfo = CCValAssign::SExt;
2763  else if (ArgFlags.isZExt())
2764  LocInfo = CCValAssign::ZExt;
2765  else
2766  LocInfo = CCValAssign::AExt;
2767  }
2768 
2769  unsigned Reg;
2770 
2771  // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2772  // is true: function is vararg, argument is 3rd or higher, there is previous
2773  // argument which is not f32 or f64.
2774  bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2775  State.getFirstUnallocated(F32Regs) != ValNo;
2776  unsigned OrigAlign = ArgFlags.getOrigAlign();
2777  bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2778  bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo);
2779 
2780  // The MIPS vector ABI for floats passes them in a pair of registers
2781  if (ValVT == MVT::i32 && isVectorFloat) {
2782  // This is the start of an vector that was scalarized into an unknown number
2783  // of components. It doesn't matter how many there are. Allocate one of the
2784  // notional 8 byte aligned registers which map onto the argument stack, and
2785  // shadow the register lost to alignment requirements.
2786  if (ArgFlags.isSplit()) {
2787  Reg = State.AllocateReg(FloatVectorIntRegs);
2788  if (Reg == Mips::A2)
2789  State.AllocateReg(Mips::A1);
2790  else if (Reg == 0)
2791  State.AllocateReg(Mips::A3);
2792  } else {
2793  // If we're an intermediate component of the split, we can just attempt to
2794  // allocate a register directly.
2795  Reg = State.AllocateReg(IntRegs);
2796  }
2797  } else if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2798  Reg = State.AllocateReg(IntRegs);
2799  // If this is the first part of an i64 arg,
2800  // the allocated register must be either A0 or A2.
2801  if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2802  Reg = State.AllocateReg(IntRegs);
2803  LocVT = MVT::i32;
2804  } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2805  // Allocate int register and shadow next int register. If first
2806  // available register is Mips::A1 or Mips::A3, shadow it too.
2807  Reg = State.AllocateReg(IntRegs);
2808  if (Reg == Mips::A1 || Reg == Mips::A3)
2809  Reg = State.AllocateReg(IntRegs);
2810  State.AllocateReg(IntRegs);
2811  LocVT = MVT::i32;
2812  } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2813  // we are guaranteed to find an available float register
2814  if (ValVT == MVT::f32) {
2815  Reg = State.AllocateReg(F32Regs);
2816  // Shadow int register
2817  State.AllocateReg(IntRegs);
2818  } else {
2819  Reg = State.AllocateReg(F64Regs);
2820  // Shadow int registers
2821  unsigned Reg2 = State.AllocateReg(IntRegs);
2822  if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2823  State.AllocateReg(IntRegs);
2824  State.AllocateReg(IntRegs);
2825  }
2826  } else
2827  llvm_unreachable("Cannot handle this ValVT.");
2828 
2829  if (!Reg) {
2830  unsigned Offset = State.AllocateStack(ValVT.getStoreSize(), OrigAlign);
2831  State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2832  } else
2833  State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2834 
2835  return false;
2836 }
2837 
2838 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2839  MVT LocVT, CCValAssign::LocInfo LocInfo,
2840  ISD::ArgFlagsTy ArgFlags, CCState &State) {
2841  static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2842 
2843  return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2844 }
2845 
2846 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2847  MVT LocVT, CCValAssign::LocInfo LocInfo,
2848  ISD::ArgFlagsTy ArgFlags, CCState &State) {
2849  static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2850 
2851  return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2852 }
2853 
2854 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2855  CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2857 
2858 #include "MipsGenCallingConv.inc"
2859 
2861  return CC_Mips;
2862  }
2863 
2865  return RetCC_Mips;
2866  }
2867 //===----------------------------------------------------------------------===//
2868 // Call Calling Convention Implementation
2869 //===----------------------------------------------------------------------===//
2870 
2871 // Return next O32 integer argument register.
2872 static unsigned getNextIntArgReg(unsigned Reg) {
2873  assert((Reg == Mips::A0) || (Reg == Mips::A2));
2874  return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2875 }
2876 
2877 SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2878  SDValue Chain, SDValue Arg,
2879  const SDLoc &DL, bool IsTailCall,
2880  SelectionDAG &DAG) const {
2881  if (!IsTailCall) {
2882  SDValue PtrOff =
2883  DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2884  DAG.getIntPtrConstant(Offset, DL));
2885  return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
2886  }
2887 
2889  int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2890  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2891  return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2892  /* Alignment = */ 0, MachineMemOperand::MOVolatile);
2893 }
2894 
2897  std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
2898  bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2899  bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2900  SDValue Chain) const {
2901  // Insert node "GP copy globalreg" before call to function.
2902  //
2903  // R_MIPS_CALL* operators (emitted when non-internal functions are called
2904  // in PIC mode) allow symbols to be resolved via lazy binding.
2905  // The lazy binding stub requires GP to point to the GOT.
2906  // Note that we don't need GP to point to the GOT for indirect calls
2907  // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2908  // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2909  // used for the function (that is, Mips linker doesn't generate lazy binding
2910  // stub for a function whose address is taken in the program).
2911  if (IsPICCall && !InternalLinkage && IsCallReloc) {
2912  unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2913  EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2914  RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2915  }
2916 
2917  // Build a sequence of copy-to-reg nodes chained together with token
2918  // chain and flag operands which copy the outgoing args into registers.
2919  // The InFlag in necessary since all emitted instructions must be
2920  // stuck together.
2921  SDValue InFlag;
2922 
2923  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2924  Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2925  RegsToPass[i].second, InFlag);
2926  InFlag = Chain.getValue(1);
2927  }
2928 
2929  // Add argument registers to the end of the list so that they are
2930  // known live into the call.
2931  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2932  Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2933  RegsToPass[i].second.getValueType()));
2934 
2935  // Add a register mask operand representing the call-preserved registers.
2937  const uint32_t *Mask =
2939  assert(Mask && "Missing call preserved mask for calling convention");
2940  if (Subtarget.inMips16HardFloat()) {
2941  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2942  StringRef Sym = G->getGlobal()->getName();
2943  Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2944  if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2946  }
2947  }
2948  }
2949  Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2950 
2951  if (InFlag.getNode())
2952  Ops.push_back(InFlag);
2953 }
2954 
2956  SDNode *Node) const {
2957  switch (MI.getOpcode()) {
2958  default:
2959  return;
2960  case Mips::JALR:
2961  case Mips::JALRPseudo:
2962  case Mips::JALR64:
2963  case Mips::JALR64Pseudo:
2964  case Mips::JALR16_MM:
2965  case Mips::JALRC16_MMR6:
2966  case Mips::TAILCALLREG:
2967  case Mips::TAILCALLREG64:
2968  case Mips::TAILCALLR6REG:
2969  case Mips::TAILCALL64R6REG:
2970  case Mips::TAILCALLREG_MM:
2971  case Mips::TAILCALLREG_MMR6: {
2972  if (!EmitJalrReloc ||
2973  Subtarget.inMips16Mode() ||
2974  !isPositionIndependent() ||
2975  Node->getNumOperands() < 1 ||
2976  Node->getOperand(0).getNumOperands() < 2) {
2977  return;
2978  }
2979  // We are after the callee address, set by LowerCall().
2980  // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the
2981  // symbol.
2982  const SDValue TargetAddr = Node->getOperand(0).getOperand(1);
2983  StringRef Sym;
2984  if (const GlobalAddressSDNode *G =
2985  dyn_cast_or_null<const GlobalAddressSDNode>(TargetAddr)) {
2986  Sym = G->getGlobal()->getName();
2987  }
2988  else if (const ExternalSymbolSDNode *ES =
2989  dyn_cast_or_null<const ExternalSymbolSDNode>(TargetAddr)) {
2990  Sym = ES->getSymbol();
2991  }
2992 
2993  if (Sym.empty())
2994  return;
2995 
2996  MachineFunction *MF = MI.getParent()->getParent();
2997  MCSymbol *S = MF->getContext().getOrCreateSymbol(Sym);
2999  }
3000  }
3001 }
3002 
3003 /// LowerCall - functions arguments are copied from virtual regs to
3004 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3005 SDValue
3006 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3007  SmallVectorImpl<SDValue> &InVals) const {
3008  SelectionDAG &DAG = CLI.DAG;
3009  SDLoc DL = CLI.DL;
3011  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3013  SDValue Chain = CLI.Chain;
3014  SDValue Callee = CLI.Callee;
3015  bool &IsTailCall = CLI.IsTailCall;
3016  CallingConv::ID CallConv = CLI.CallConv;
3017  bool IsVarArg = CLI.IsVarArg;
3018 
3019  MachineFunction &MF = DAG.getMachineFunction();
3020  MachineFrameInfo &MFI = MF.getFrameInfo();
3022  MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
3023  bool IsPIC = isPositionIndependent();
3024 
3025  // Analyze operands of the call, assigning locations to each operand.
3027  MipsCCState CCInfo(
3028  CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
3030 
3031  const ExternalSymbolSDNode *ES =
3032  dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
3033 
3034  // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which
3035  // is during the lowering of a call with a byval argument which produces
3036  // a call to memcpy. For the O32 case, this causes the caller to allocate
3037  // stack space for the reserved argument area for the callee, then recursively
3038  // again for the memcpy call. In the NEWABI case, this doesn't occur as those
3039  // ABIs mandate that the callee allocates the reserved argument area. We do
3040  // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though.
3041  //
3042  // If the callee has a byval argument and memcpy is used, we are mandated
3043  // to already have produced a reserved argument area for the callee for O32.
3044  // Therefore, the reserved argument area can be reused for both calls.
3045  //
3046  // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START
3047  // present, as we have yet to hook that node onto the chain.
3048  //
3049  // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this
3050  // case. GCC does a similar trick, in that wherever possible, it calculates
3051  // the maximum out going argument area (including the reserved area), and
3052  // preallocates the stack space on entrance to the caller.
3053  //
3054  // FIXME: We should do the same for efficiency and space.
3055 
3056  // Note: The check on the calling convention below must match
3057  // MipsABIInfo::GetCalleeAllocdArgSizeInBytes().
3058  bool MemcpyInByVal = ES &&
3059  StringRef(ES->getSymbol()) == StringRef("memcpy") &&
3060  CallConv != CallingConv::Fast &&
3061  Chain.getOpcode() == ISD::CALLSEQ_START;
3062 
3063  // Allocate the reserved argument area. It seems strange to do this from the
3064  // caller side but removing it breaks the frame size calculation.
3065  unsigned ReservedArgArea =
3066  MemcpyInByVal ? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv);
3067  CCInfo.AllocateStack(ReservedArgArea, 1);
3068 
3069  CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
3070  ES ? ES->getSymbol() : nullptr);
3071 
3072  // Get a count of how many bytes are to be pushed on the stack.
3073  unsigned NextStackOffset = CCInfo.getNextStackOffset();
3074 
3075  // Check if it's really possible to do a tail call. Restrict it to functions
3076  // that are part of this compilation unit.
3077  bool InternalLinkage = false;
3078  if (IsTailCall) {
3079  IsTailCall = isEligibleForTailCallOptimization(
3080  CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
3081  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3082  InternalLinkage = G->getGlobal()->hasInternalLinkage();
3083  IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
3084  G->getGlobal()->hasPrivateLinkage() ||
3085  G->getGlobal()->hasHiddenVisibility() ||
3086  G->getGlobal()->hasProtectedVisibility());
3087  }
3088  }
3089  if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3090  report_fatal_error("failed to perform tail call elimination on a call "
3091  "site marked musttail");
3092 
3093  if (IsTailCall)
3094  ++NumTailCalls;
3095 
3096  // Chain is the output chain of the last Load/Store or CopyToReg node.
3097  // ByValChain is the output chain of the last Memcpy node created for copying
3098  // byval arguments to the stack.
3099  unsigned StackAlignment = TFL->getStackAlignment();
3100  NextStackOffset = alignTo(NextStackOffset, StackAlignment);
3101  SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
3102 
3103  if (!(IsTailCall || MemcpyInByVal))
3104  Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL);
3105 
3106  SDValue StackPtr =
3107  DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
3108  getPointerTy(DAG.getDataLayout()));
3109 
3110  std::deque<std::pair<unsigned, SDValue>> RegsToPass;
3111  SmallVector<SDValue, 8> MemOpChains;
3112 
3113  CCInfo.rewindByValRegsInfo();
3114 
3115  // Walk the register/memloc assignments, inserting copies/loads.
3116  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3117  SDValue Arg = OutVals[i];
3118  CCValAssign &VA = ArgLocs[i];
3119  MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3120  ISD::ArgFlagsTy Flags = Outs[i].Flags;
3121  bool UseUpperBits = false;
3122 
3123  // ByVal Arg.
3124  if (Flags.isByVal()) {
3125  unsigned FirstByValReg, LastByValReg;
3126  unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3127  CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3128 
3129  assert(Flags.getByValSize() &&
3130  "ByVal args of size 0 should have been ignored by front-end.");
3131  assert(ByValIdx < CCInfo.getInRegsParamsCount());
3132  assert(!IsTailCall &&
3133  "Do not tail-call optimize if there is a byval argument.");
3134  passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3135  FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3136  VA);
3137  CCInfo.nextInRegsParam();
3138  continue;
3139  }
3140 
3141  // Promote the value if needed.
3142  switch (VA.getLocInfo()) {
3143  default:
3144  llvm_unreachable("Unknown loc info!");
3145  case CCValAssign::Full:
3146  if (VA.isRegLoc()) {
3147  if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3148  (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3149  (ValVT == MVT::i64 && LocVT == MVT::f64))
3150  Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3151  else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3153  Arg, DAG.getConstant(0, DL, MVT::i32));
3155  Arg, DAG.getConstant(1, DL, MVT::i32));
3156  if (!Subtarget.isLittle())
3157  std::swap(Lo, Hi);
3158  unsigned LocRegLo = VA.getLocReg();
3159  unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3160  RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3161  RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3162  continue;
3163  }
3164  }
3165  break;
3166  case CCValAssign::BCvt:
3167  Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3168  break;
3170  UseUpperBits = true;
3172  case CCValAssign::SExt:
3173  Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3174  break;
3176  UseUpperBits = true;
3178  case CCValAssign::ZExt:
3179  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3180  break;
3182  UseUpperBits = true;
3184  case CCValAssign::AExt:
3185  Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3186  break;
3187  }
3188 
3189  if (UseUpperBits) {
3190  unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3191  unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3192  Arg = DAG.getNode(
3193  ISD::SHL, DL, VA.getLocVT(), Arg,
3194  DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3195  }
3196 
3197  // Arguments that can be passed on register must be kept at
3198  // RegsToPass vector
3199  if (VA.isRegLoc()) {
3200  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3201  continue;
3202  }
3203 
3204  // Register can't get to this point...
3205  assert(VA.isMemLoc());
3206 
3207  // emit ISD::STORE whichs stores the
3208  // parameter value to a stack Location
3209  MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3210  Chain, Arg, DL, IsTailCall, DAG));
3211  }
3212 
3213  // Transform all store nodes into one single node because all store
3214  // nodes are independent of each other.
3215  if (!MemOpChains.empty())
3216  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3217 
3218  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3219  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3220  // node so that legalize doesn't hack it.
3221 
3222  EVT Ty = Callee.getValueType();
3223  bool GlobalOrExternal = false, IsCallReloc = false;
3224 
3225  // The long-calls feature is ignored in case of PIC.
3226  // While we do not support -mshared / -mno-shared properly,
3227  // ignore long-calls in case of -mabicalls too.
3228  if (!Subtarget.isABICalls() && !IsPIC) {
3229  // If the function should be called using "long call",
3230  // get its address into a register to prevent using
3231  // of the `jal` instruction for the direct call.
3232  if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3233  if (Subtarget.useLongCalls())
3234  Callee = Subtarget.hasSym32()
3235  ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3236  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3237  } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) {
3238  bool UseLongCalls = Subtarget.useLongCalls();
3239  // If the function has long-call/far/near attribute
3240  // it overrides command line switch pased to the backend.
3241  if (auto *F = dyn_cast<Function>(N->getGlobal())) {
3242  if (F->hasFnAttribute("long-call"))
3243  UseLongCalls = true;
3244  else if (F->hasFnAttribute("short-call"))
3245  UseLongCalls = false;
3246  }
3247  if (UseLongCalls)
3248  Callee = Subtarget.hasSym32()
3249  ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3250  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3251  }
3252  }
3253 
3254  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3255  if (IsPIC) {
3256  const GlobalValue *Val = G->getGlobal();
3257  InternalLinkage = Val->hasInternalLinkage();
3258 
3259  if (InternalLinkage)
3260  Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3261  else if (LargeGOT) {
3262  Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3263  MipsII::MO_CALL_LO16, Chain,
3264  FuncInfo->callPtrInfo(Val));
3265  IsCallReloc = true;
3266  } else {
3267  Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3268  FuncInfo->callPtrInfo(Val));
3269  IsCallReloc = true;
3270  }
3271  } else
3272  Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3273  getPointerTy(DAG.getDataLayout()), 0,
3275  GlobalOrExternal = true;
3276  }
3277  else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3278  const char *Sym = S->getSymbol();
3279 
3280  if (!IsPIC) // static
3281  Callee = DAG.getTargetExternalSymbol(
3283  else if (LargeGOT) {
3284  Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3285  MipsII::MO_CALL_LO16, Chain,
3286  FuncInfo->callPtrInfo(Sym));
3287  IsCallReloc = true;
3288  } else { // PIC
3289  Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3290  FuncInfo->callPtrInfo(Sym));
3291  IsCallReloc = true;
3292  }
3293 
3294  GlobalOrExternal = true;
3295  }
3296 
3297  SmallVector<SDValue, 8> Ops(1, Chain);
3298  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3299 
3300  getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3301  IsCallReloc, CLI, Callee, Chain);
3302 
3303  if (IsTailCall) {
3305  return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3306  }
3307 
3308  Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3309  SDValue InFlag = Chain.getValue(1);
3310 
3311  // Create the CALLSEQ_END node in the case of where it is not a call to
3312  // memcpy.
3313  if (!(MemcpyInByVal)) {
3314  Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3315  DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3316  InFlag = Chain.getValue(1);
3317  }
3318 
3319  // Handle result values, copying them out of physregs into vregs that we
3320  // return.
3321  return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3322  InVals, CLI);
3323 }
3324 
3325 /// LowerCallResult - Lower the result values of a call into the
3326 /// appropriate copies out of appropriate physical registers.
3327 SDValue MipsTargetLowering::LowerCallResult(
3328  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
3329  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3330  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3331  TargetLowering::CallLoweringInfo &CLI) const {
3332  // Assign locations to each value returned by this call.
3334  MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3335  *DAG.getContext());
3336 
3337  const ExternalSymbolSDNode *ES =
3338  dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3339  CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3340  ES ? ES->getSymbol() : nullptr);
3341 
3342  // Copy all of the result registers out of their specified physreg.
3343  for (unsigned i = 0; i != RVLocs.size(); ++i) {
3344  CCValAssign &VA = RVLocs[i];
3345  assert(VA.isRegLoc() && "Can only return in registers!");
3346 
3347  SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3348  RVLocs[i].getLocVT(), InFlag);
3349  Chain = Val.getValue(1);
3350  InFlag = Val.getValue(2);
3351 
3352  if (VA.isUpperBitsInLoc()) {
3353  unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3354  unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3355  unsigned Shift =
3357  Val = DAG.getNode(
3358  Shift, DL, VA.getLocVT(), Val,
3359  DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3360  }
3361 
3362  switch (VA.getLocInfo()) {
3363  default:
3364  llvm_unreachable("Unknown loc info!");
3365  case CCValAssign::Full:
3366  break;
3367  case CCValAssign::BCvt:
3368  Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3369  break;
3370  case CCValAssign::AExt:
3372  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3373  break;
3374  case CCValAssign::ZExt:
3376  Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3377  DAG.getValueType(VA.getValVT()));
3378  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3379  break;
3380  case CCValAssign::SExt:
3382  Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3383  DAG.getValueType(VA.getValVT()));
3384  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3385  break;
3386  }
3387 
3388  InVals.push_back(Val);
3389  }
3390 
3391  return Chain;
3392 }
3393 
3395  EVT ArgVT, const SDLoc &DL,
3396  SelectionDAG &DAG) {
3397  MVT LocVT = VA.getLocVT();
3398  EVT ValVT = VA.getValVT();
3399 
3400  // Shift into the upper bits if necessary.
3401  switch (VA.getLocInfo()) {
3402  default:
3403  break;
3406  case CCValAssign::ZExtUpper: {
3407  unsigned ValSizeInBits = ArgVT.getSizeInBits();
3408  unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3409  unsigned Opcode =
3411  Val = DAG.getNode(
3412  Opcode, DL, VA.getLocVT(), Val,
3413  DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3414  break;
3415  }
3416  }
3417 
3418  // If this is an value smaller than the argument slot size (32-bit for O32,
3419  // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3420  // size. Extract the value and insert any appropriate assertions regarding
3421  // sign/zero extension.
3422  switch (VA.getLocInfo()) {
3423  default:
3424  llvm_unreachable("Unknown loc info!");
3425  case CCValAssign::Full:
3426  break;
3428  case CCValAssign::AExt:
3429  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3430  break;
3432  case CCValAssign::SExt:
3433  Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3434  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3435  break;
3437  case CCValAssign::ZExt:
3438  Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3439  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3440  break;
3441  case CCValAssign::BCvt:
3442  Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3443  break;
3444  }
3445 
3446  return Val;
3447 }
3448 
3449 //===----------------------------------------------------------------------===//
3450 // Formal Arguments Calling Convention Implementation
3451 //===----------------------------------------------------------------------===//
3452 /// LowerFormalArguments - transform physical registers into virtual registers
3453 /// and generate load operations for arguments places on the stack.
3454 SDValue MipsTargetLowering::LowerFormalArguments(
3455  SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3456  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3457  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3458  MachineFunction &MF = DAG.getMachineFunction();
3459  MachineFrameInfo &MFI = MF.getFrameInfo();
3460  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3461 
3462  MipsFI->setVarArgsFrameIndex(0);
3463 
3464  // Used with vargs to acumulate store chains.
3465  std::vector<SDValue> OutChains;
3466 
3467  // Assign locations to all of the incoming arguments.
3469  MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3470  *DAG.getContext());
3471  CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
3472  const Function &Func = DAG.getMachineFunction().getFunction();
3473  Function::const_arg_iterator FuncArg = Func.arg_begin();
3474 
3475  if (Func.hasFnAttribute("interrupt") && !Func.arg_empty())
3477  "Functions with the interrupt attribute cannot have arguments!");
3478 
3479  CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3480  MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3481  CCInfo.getInRegsParamsCount() > 0);
3482 
3483  unsigned CurArgIdx = 0;
3484  CCInfo.rewindByValRegsInfo();
3485 
3486  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3487  CCValAssign &VA = ArgLocs[i];
3488  if (Ins[i].isOrigArg()) {
3489  std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3490  CurArgIdx = Ins[i].getOrigArgIndex();
3491  }
3492  EVT ValVT = VA.getValVT();
3493  ISD::ArgFlagsTy Flags = Ins[i].Flags;
3494  bool IsRegLoc = VA.isRegLoc();
3495 
3496  if (Flags.isByVal()) {
3497  assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
3498  unsigned FirstByValReg, LastByValReg;
3499  unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3500  CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3501 
3502  assert(Flags.getByValSize() &&
3503  "ByVal args of size 0 should have been ignored by front-end.");
3504  assert(ByValIdx < CCInfo.getInRegsParamsCount());
3505  copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3506  FirstByValReg, LastByValReg, VA, CCInfo);
3507  CCInfo.nextInRegsParam();
3508  continue;
3509  }
3510 
3511  // Arguments stored on registers
3512  if (IsRegLoc) {
3513  MVT RegVT = VA.getLocVT();
3514  unsigned ArgReg = VA.getLocReg();
3515  const TargetRegisterClass *RC = getRegClassFor(RegVT);
3516 
3517  // Transform the arguments stored on
3518  // physical registers into virtual ones
3519  unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3520  SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3521 
3522  ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3523 
3524  // Handle floating point arguments passed in integer registers and
3525  // long double arguments passed in floating point registers.
3526  if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3527  (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3528  (RegVT == MVT::f64 && ValVT == MVT::i64))
3529  ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3530  else if (ABI.IsO32() && RegVT == MVT::i32 &&
3531  ValVT == MVT::f64) {
3532  unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3533  getNextIntArgReg(ArgReg), RC);
3534  SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3535  if (!Subtarget.isLittle())
3536  std::swap(ArgValue, ArgValue2);
3537  ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3538  ArgValue, ArgValue2);
3539  }
3540 
3541  InVals.push_back(ArgValue);
3542  } else { // VA.isRegLoc()
3543  MVT LocVT = VA.getLocVT();
3544 
3545  if (ABI.IsO32()) {
3546  // We ought to be able to use LocVT directly but O32 sets it to i32
3547  // when allocating floating point values to integer registers.
3548  // This shouldn't influence how we load the value into registers unless
3549  // we are targeting softfloat.
3551  LocVT = VA.getValVT();
3552  }
3553 
3554  // sanity check
3555  assert(VA.isMemLoc());
3556 
3557  // The stack pointer offset is relative to the caller stack frame.
3558  int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3559  VA.getLocMemOffset(), true);
3560 
3561  // Create load nodes to retrieve arguments from the stack
3562  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3563  SDValue ArgValue = DAG.getLoad(
3564  LocVT, DL, Chain, FIN,
3566  OutChains.push_back(ArgValue.getValue(1));
3567 
3568  ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3569 
3570  InVals.push_back(ArgValue);
3571  }
3572  }
3573 
3574  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3575  // The mips ABIs for returning structs by value requires that we copy
3576  // the sret argument into $v0 for the return. Save the argument into
3577  // a virtual register so that we can access it from the return points.
3578  if (Ins[i].Flags.isSRet()) {
3579  unsigned Reg = MipsFI->getSRetReturnReg();
3580  if (!Reg) {
3581  Reg = MF.getRegInfo().createVirtualRegister(
3583  MipsFI->setSRetReturnReg(Reg);
3584  }
3585  SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3586  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3587  break;
3588  }
3589  }
3590 
3591  if (IsVarArg)
3592  writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3593 
3594  // All stores are grouped in one node to allow the matching between
3595  // the size of Ins and InVals. This only happens when on varg functions
3596  if (!OutChains.empty()) {
3597  OutChains.push_back(Chain);
3598  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3599  }
3600 
3601  return Chain;
3602 }
3603 
3604 //===----------------------------------------------------------------------===//
3605 // Return Value Calling Convention Implementation
3606 //===----------------------------------------------------------------------===//
3607 
3608 bool
3609 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3610  MachineFunction &MF, bool IsVarArg,
3611  const SmallVectorImpl<ISD::OutputArg> &Outs,
3612  LLVMContext &Context) const {
3614  MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3615  return CCInfo.CheckReturn(Outs, RetCC_Mips);
3616 }
3617 
3618 bool
3619 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3620  if ((ABI.IsN32() || ABI.IsN64()) && Type == MVT::i32)
3621  return true;
3622 
3623  return IsSigned;
3624 }
3625 
3626 SDValue
3627 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3628  const SDLoc &DL,
3629  SelectionDAG &DAG) const {
3630  MachineFunction &MF = DAG.getMachineFunction();
3631  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3632 
3633  MipsFI->setISR();
3634 
3635  return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3636 }
3637 
3638 SDValue
3639 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3640  bool IsVarArg,
3641  const SmallVectorImpl<ISD::OutputArg> &Outs,
3642  const SmallVectorImpl<SDValue> &OutVals,
3643  const SDLoc &DL, SelectionDAG &DAG) const {
3644  // CCValAssign - represent the assignment of
3645  // the return value to a location
3647  MachineFunction &MF = DAG.getMachineFunction();
3648 
3649  // CCState - Info about the registers and stack slot.
3650  MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3651 
3652  // Analyze return values.
3653  CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3654 
3655  SDValue Flag;
3656  SmallVector<SDValue, 4> RetOps(1, Chain);
3657 
3658  // Copy the result values into the output registers.
3659  for (unsigned i = 0; i != RVLocs.size(); ++i) {
3660  SDValue Val = OutVals[i];
3661  CCValAssign &VA = RVLocs[i];
3662  assert(VA.isRegLoc() && "Can only return in registers!");
3663  bool UseUpperBits = false;
3664 
3665  switch (VA.getLocInfo()) {
3666  default:
3667  llvm_unreachable("Unknown loc info!");
3668  case CCValAssign::Full:
3669  break;
3670  case CCValAssign::BCvt:
3671  Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3672  break;
3674  UseUpperBits = true;
3676  case CCValAssign::AExt:
3677  Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3678  break;
3680  UseUpperBits = true;
3682  case CCValAssign::ZExt:
3683  Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3684  break;
3686  UseUpperBits = true;
3688  case CCValAssign::SExt:
3689  Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3690  break;
3691  }
3692 
3693  if (UseUpperBits) {
3694  unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3695  unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3696  Val = DAG.getNode(
3697  ISD::SHL, DL, VA.getLocVT(), Val,
3698  DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3699  }
3700 
3701  Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3702 
3703  // Guarantee that all emitted copies are stuck together with flags.
3704  Flag = Chain.getValue(1);
3705  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3706  }
3707 
3708  // The mips ABIs for returning structs by value requires that we copy
3709  // the sret argument into $v0 for the return. We saved the argument into
3710  // a virtual register in the entry block, so now we copy the value out
3711  // and into $v0.
3712  if (MF.getFunction().hasStructRetAttr()) {
3713  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3714  unsigned Reg = MipsFI->getSRetReturnReg();
3715 
3716  if (!Reg)
3717  llvm_unreachable("sret virtual register not created in the entry block");
3718  SDValue Val =
3719  DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3720  unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3721 
3722  Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3723  Flag = Chain.getValue(1);
3724  RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3725  }
3726 
3727  RetOps[0] = Chain; // Update chain.
3728 
3729  // Add the flag if we have it.
3730  if (Flag.getNode())
3731  RetOps.push_back(Flag);
3732 
3733  // ISRs must use "eret".
3734  if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt"))
3735  return LowerInterruptReturn(RetOps, DL, DAG);
3736 
3737  // Standard return on Mips is a "jr $ra"
3738  return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3739 }
3740 
3741 //===----------------------------------------------------------------------===//
3742 // Mips Inline Assembly Support
3743 //===----------------------------------------------------------------------===//
3744 
3745 /// getConstraintType - Given a constraint letter, return the type of
3746 /// constraint it is for this target.
3748 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3749  // Mips specific constraints
3750  // GCC config/mips/constraints.md
3751  //
3752  // 'd' : An address register. Equivalent to r
3753  // unless generating MIPS16 code.
3754  // 'y' : Equivalent to r; retained for
3755  // backwards compatibility.
3756  // 'c' : A register suitable for use in an indirect
3757  // jump. This will always be $25 for -mabicalls.
3758  // 'l' : The lo register. 1 word storage.
3759  // 'x' : The hilo register pair. Double word storage.
3760  if (Constraint.size() == 1) {
3761  switch (Constraint[0]) {
3762  default : break;
3763  case 'd':
3764  case 'y':
3765  case 'f':
3766  case 'c':
3767  case 'l':
3768  case 'x':
3769  return C_RegisterClass;
3770  case 'R':
3771  return C_Memory;
3772  }
3773  }
3774 
3775  if (Constraint == "ZC")
3776  return C_Memory;
3777 
3778  return TargetLowering::getConstraintType(Constraint);
3779 }
3780 
3781 /// Examine constraint type and operand type and determine a weight value.
3782 /// This object must already have been set up with the operand type
3783 /// and the current alternative constraint selected.
3785 MipsTargetLowering::getSingleConstraintMatchWeight(
3786  AsmOperandInfo &info, const char *constraint) const {
3787  ConstraintWeight weight = CW_Invalid;
3788  Value *CallOperandVal = info.CallOperandVal;
3789  // If we don't have a value, we can't do a match,
3790  // but allow it at the lowest weight.
3791  if (!CallOperandVal)
3792  return CW_Default;
3793  Type *type = CallOperandVal->getType();
3794  // Look at the constraint type.
3795  switch (*constraint) {
3796  default:
3797  weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3798  break;
3799  case 'd':
3800  case 'y':
3801  if (type->isIntegerTy())
3802  weight = CW_Register;
3803  break;
3804  case 'f': // FPU or MSA register
3805  if (Subtarget.hasMSA() && type->isVectorTy() &&
3806  cast<VectorType>(type)->getBitWidth() == 128)
3807  weight = CW_Register;
3808  else if (type->isFloatTy())
3809  weight = CW_Register;
3810  break;
3811  case 'c': // $25 for indirect jumps
3812  case 'l': // lo register
3813  case 'x': // hilo register pair
3814  if (type->isIntegerTy())
3815  weight = CW_SpecificReg;
3816  break;
3817  case 'I': // signed 16 bit immediate
3818  case 'J': // integer zero
3819  case 'K': // unsigned 16 bit immediate
3820  case 'L': // signed 32 bit immediate where lower 16 bits are 0
3821  case 'N': // immediate in the range of -65535 to -1 (inclusive)
3822  case 'O': // signed 15 bit immediate (+- 16383)
3823  case 'P': // immediate in the range of 65535 to 1 (inclusive)
3824  if (isa<ConstantInt>(CallOperandVal))
3825  weight = CW_Constant;
3826  break;
3827  case 'R':
3828  weight = CW_Memory;
3829  break;
3830  }
3831  return weight;
3832 }
3833 
3834 /// This is a helper function to parse a physical register string and split it
3835 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3836 /// that is returned indicates whether parsing was successful. The second flag
3837 /// is true if the numeric part exists.
3838 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3839  unsigned long long &Reg) {
3840  if (C.front() != '{' || C.back() != '}')
3841  return std::make_pair(false, false);
3842 
3843  // Search for the first numeric character.
3844  StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3845  I = std::find_if(B, E, isdigit);
3846 
3847  Prefix = StringRef(B, I - B);
3848 
3849  // The second flag is set to false if no numeric characters were found.
3850  if (I == E)
3851  return std::make_pair(true, false);
3852 
3853  // Parse the numeric characters.
3854  return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3855  true);
3856 }
3857 
3859  ISD::NodeType) const {
3860  bool Cond = !Subtarget.isABI_O32() && VT.getSizeInBits() == 32;
3861  EVT MinVT = getRegisterType(Context, Cond ? MVT::i64 : MVT::i32);
3862  return VT.bitsLT(MinVT) ? MinVT : VT;
3863 }
3864 
3865 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3866 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3867  const TargetRegisterInfo *TRI =
3869  const TargetRegisterClass *RC;
3870  StringRef Prefix;
3871  unsigned long long Reg;
3872 
3873  std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3874 
3875  if (!R.first)
3876  return std::make_pair(0U, nullptr);
3877 
3878  if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3879  // No numeric characters follow "hi" or "lo".
3880  if (R.second)
3881  return std::make_pair(0U, nullptr);
3882 
3883  RC = TRI->getRegClass(Prefix == "hi" ?
3884  Mips::HI32RegClassID : Mips::LO32RegClassID);
3885  return std::make_pair(*(RC->begin()), RC);
3886  } else if (Prefix.startswith("$msa")) {
3887  // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3888 
3889  // No numeric characters follow the name.
3890  if (R.second)
3891  return std::make_pair(0U, nullptr);
3892 
3894  .Case("$msair", Mips::MSAIR)
3895  .Case("$msacsr", Mips::MSACSR)
3896  .Case("$msaaccess", Mips::MSAAccess)
3897  .Case("$msasave", Mips::MSASave)
3898  .Case("$msamodify", Mips::MSAModify)
3899  .Case("$msarequest", Mips::MSARequest)
3900  .Case("$msamap", Mips::MSAMap)
3901  .Case("$msaunmap", Mips::MSAUnmap)
3902  .Default(0);
3903 
3904  if (!Reg)
3905  return std::make_pair(0U, nullptr);
3906 
3907  RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3908  return std::make_pair(Reg, RC);
3909  }
3910 
3911  if (!R.second)
3912  return std::make_pair(0U, nullptr);
3913 
3914  if (Prefix == "$f") { // Parse $f0-$f31.
3915  // If the size of FP registers is 64-bit or Reg is an even number, select
3916  // the 64-bit register class. Otherwise, select the 32-bit register class.
3917  if (VT == MVT::Other)
3918  VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3919 
3920  RC = getRegClassFor(VT);
3921 
3922  if (RC == &Mips::AFGR64RegClass) {
3923  assert(Reg % 2 == 0);
3924  Reg >>= 1;
3925  }
3926  } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3927  RC = TRI->getRegClass(Mips::FCCRegClassID);
3928  else if (Prefix == "$w") { // Parse $w0-$w31.
3929  RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3930  } else { // Parse $0-$31.
3931  assert(Prefix == "$");
3932  RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3933  }
3934 
3935  assert(Reg < RC->getNumRegs());
3936  return std::make_pair(*(RC->begin() + Reg), RC);
3937 }
3938 
3939 /// Given a register class constraint, like 'r', if this corresponds directly
3940 /// to an LLVM register class, return a register of 0 and the register class
3941 /// pointer.
3942 std::pair<unsigned, const TargetRegisterClass *>
3943 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3944  StringRef Constraint,
3945  MVT VT) const {
3946  if (Constraint.size() == 1) {
3947  switch (Constraint[0]) {
3948  case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3949  case 'y': // Same as 'r'. Exists for compatibility.
3950  case 'r':
3951  if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3952  if (Subtarget.inMips16Mode())
3953  return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3954  return std::make_pair(0U, &Mips::GPR32RegClass);
3955  }
3956  if (VT == MVT::i64 && !Subtarget.isGP64bit())
3957  return std::make_pair(0U, &Mips::GPR32RegClass);
3958  if (VT == MVT::i64 && Subtarget.isGP64bit())
3959  return std::make_pair(0U, &Mips::GPR64RegClass);
3960  // This will generate an error message
3961  return std::make_pair(0U, nullptr);
3962  case 'f': // FPU or MSA register
3963  if (VT == MVT::v16i8)
3964  return std::make_pair(0U, &Mips::MSA128BRegClass);
3965  else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3966  return std::make_pair(0U, &Mips::MSA128HRegClass);
3967  else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3968  return std::make_pair(0U, &Mips::MSA128WRegClass);
3969  else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3970  return std::make_pair(0U, &Mips::MSA128DRegClass);
3971  else if (VT == MVT::f32)
3972  return std::make_pair(0U, &Mips::FGR32RegClass);
3973  else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3974  if (Subtarget.isFP64bit())
3975  return std::make_pair(0U, &Mips::FGR64RegClass);
3976  return std::make_pair(0U, &Mips::AFGR64RegClass);
3977  }
3978  break;
3979  case 'c': // register suitable for indirect jump
3980  if (VT == MVT::i32)
3981  return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3982  if (VT == MVT::i64)
3983  return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3984  // This will generate an error message
3985  return std::make_pair(0U, nullptr);
3986  case 'l': // use the `lo` register to store values
3987  // that are no bigger than a word
3988  if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
3989  return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3990  return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3991  case 'x': // use the concatenated `hi` and `lo` registers
3992  // to store doubleword values
3993  // Fixme: Not triggering the use of both hi and low
3994  // This will generate an error message
3995  return std::make_pair(0U, nullptr);
3996  }
3997  }
3998 
3999  std::pair<unsigned, const TargetRegisterClass *> R;
4000  R = parseRegForInlineAsmConstraint(Constraint, VT);
4001 
4002  if (R.second)
4003  return R;
4004 
4005  return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4006 }
4007 
4008 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4009 /// vector. If it is invalid, don't add anything to Ops.
4010 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4011  std::string &Constraint,
4012  std::vector<SDValue>&Ops,
4013  SelectionDAG &DAG) const {
4014  SDLoc DL(Op);
4015  SDValue Result;
4016 
4017  // Only support length 1 constraints for now.
4018  if (Constraint.length() > 1) return;
4019 
4020  char ConstraintLetter = Constraint[0];
4021  switch (ConstraintLetter) {
4022  default: break; // This will fall through to the generic implementation
4023  case 'I': // Signed 16 bit constant
4024  // If this fails, the parent routine will give an error
4025  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4026  EVT Type = Op.getValueType();
4027  int64_t Val = C->getSExtValue();
4028  if (isInt<16>(Val)) {
4029  Result = DAG.getTargetConstant(Val, DL, Type);
4030  break;
4031  }
4032  }
4033  return;
4034  case 'J': // integer zero
4035  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4036  EVT Type = Op.getValueType();
4037  int64_t Val = C->getZExtValue();
4038  if (Val == 0) {
4039  Result = DAG.getTargetConstant(0, DL, Type);
4040  break;
4041  }
4042  }
4043  return;
4044  case 'K': // unsigned 16 bit immediate
4045  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4046  EVT Type = Op.getValueType();
4047  uint64_t Val = (uint64_t)C->getZExtValue();
4048  if (isUInt<16>(Val)) {
4049  Result = DAG.getTargetConstant(Val, DL, Type);
4050  break;
4051  }
4052  }
4053  return;
4054  case 'L': // signed 32 bit immediate where lower 16 bits are 0
4055  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4056  EVT Type = Op.getValueType();
4057  int64_t Val = C->getSExtValue();
4058  if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
4059  Result = DAG.getTargetConstant(Val, DL, Type);
4060  break;
4061  }
4062  }
4063  return;
4064  case 'N': // immediate in the range of -65535 to -1 (inclusive)
4065  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4066  EVT Type = Op.getValueType();
4067  int64_t Val = C->getSExtValue();
4068  if ((Val >= -65535) && (Val <= -1)) {
4069  Result = DAG.getTargetConstant(Val, DL, Type);
4070  break;
4071  }
4072  }
4073  return;
4074  case 'O': // signed 15 bit immediate
4075  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4076  EVT Type = Op.getValueType();
4077  int64_t Val = C->getSExtValue();
4078  if ((isInt<15>(Val))) {
4079  Result = DAG.getTargetConstant(Val, DL, Type);
4080  break;
4081  }
4082  }
4083  return;
4084  case 'P': // immediate in the range of 1 to 65535 (inclusive)
4085  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4086  EVT Type = Op.getValueType();
4087  int64_t Val = C->getSExtValue();
4088  if ((Val <= 65535) && (Val >= 1)) {
4089  Result = DAG.getTargetConstant(Val, DL, Type);
4090  break;
4091  }
4092  }
4093  return;
4094  }
4095 
4096  if (Result.getNode()) {
4097  Ops.push_back(Result);
4098  return;
4099  }
4100 
4101  TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4102 }
4103 
4104 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
4105  const AddrMode &AM, Type *Ty,
4106  unsigned AS, Instruction *I) const {
4107  // No global is ever allowed as a base.
4108  if (AM.BaseGV)
4109  return false;
4110 
4111  switch (AM.Scale) {
4112  case 0: // "r+i" or just "i", depending on HasBaseReg.
4113  break;
4114  case 1:
4115  if (!AM.HasBaseReg) // allow "r+i".
4116  break;
4117  return false; // disallow "r+r" or "r+r+i".
4118  default:
4119  return false;
4120  }
4121 
4122  return true;
4123 }
4124 
4125 bool
4126 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4127  // The Mips target isn't yet aware of offsets.
4128  return false;
4129 }
4130 
4131 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
4132  unsigned SrcAlign,
4133  bool IsMemset, bool ZeroMemset,
4134  bool MemcpyStrSrc,
4135  MachineFunction &MF) const {
4136  if (Subtarget.hasMips64())
4137  return MVT::i64;
4138 
4139  return MVT::i32;
4140 }
4141 
4142 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4143  if (VT != MVT::f32 && VT != MVT::f64)
4144  return false;
4145  if (Imm.isNegZero())
4146  return false;
4147  return Imm.isZero();
4148 }
4149 
4150 unsigned MipsTargetLowering::getJumpTableEncoding() const {
4151 
4152  // FIXME: For space reasons this should be: EK_GPRel32BlockAddress.
4153  if (ABI.IsN64() && isPositionIndependent())
4155 
4157 }
4158 
4159 bool MipsTargetLowering::useSoftFloat() const {
4160  return Subtarget.useSoftFloat();
4161 }
4162 
4163 void MipsTargetLowering::copyByValRegs(
4164  SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4165  SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4166  SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4167  unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4168  MipsCCState &State) const {
4169  MachineFunction &MF = DAG.getMachineFunction();
4170  MachineFrameInfo &MFI = MF.getFrameInfo();
4171  unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4172  unsigned NumRegs = LastReg - FirstReg;
4173  unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4174  unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4175  int FrameObjOffset;
4176  ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4177 
4178  if (RegAreaSize)
4179  FrameObjOffset =
4181  (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4182  else
4183  FrameObjOffset = VA.getLocMemOffset();
4184 
4185  // Create frame object.
4186  EVT PtrTy = getPointerTy(DAG.getDataLayout());
4187  // Make the fixed object stored to mutable so that the load instructions
4188  // referencing it have their memory dependencies added.
4189  // Set the frame object as isAliased which clears the underlying objects
4190  // vector in ScheduleDAGInstrs::buildSchedGraph() resulting in addition of all
4191  // stores as dependencies for loads referencing this fixed object.
4192  int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, false, true);
4193  SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4194  InVals.push_back(FIN);
4195 
4196  if (!NumRegs)
4197  return;
4198 
4199  // Copy arg registers.
4200  MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4201  const TargetRegisterClass *RC = getRegClassFor(RegTy);
4202 
4203  for (unsigned I = 0; I < NumRegs; ++I) {
4204  unsigned ArgReg = ByValArgRegs[FirstReg + I];
4205  unsigned VReg = addLiveIn(MF, ArgReg, RC);
4206  unsigned Offset = I * GPRSizeInBytes;
4207  SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4208  DAG.getConstant(Offset, DL, PtrTy));
4209  SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4210  StorePtr, MachinePointerInfo(FuncArg, Offset));
4211  OutChains.push_back(Store);
4212  }
4213 }
4214 
4215 // Copy byVal arg to registers and stack.
4216 void MipsTargetLowering::passByValArg(
4217  SDValue Chain, const SDLoc &DL,
4218  std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4219  SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4220  MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4221  unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4222  const CCValAssign &VA) const {
4223  unsigned ByValSizeInBytes = Flags.getByValSize();
4224  unsigned OffsetInBytes = 0; // From beginning of struct
4225  unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4226  unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
4227  EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4228  RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4229  unsigned NumRegs = LastReg - FirstReg;
4230 
4231  if (NumRegs) {
4233  bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4234  unsigned I = 0;
4235 
4236  // Copy words to registers.
4237  for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4238  SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4239  DAG.getConstant(OffsetInBytes, DL, PtrTy));
4240  SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4241  MachinePointerInfo(), Alignment);
4242  MemOpChains.push_back(LoadVal.getValue(1));
4243  unsigned ArgReg = ArgRegs[FirstReg + I];
4244  RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4245  }
4246 
4247  // Return if the struct has been fully copied.
4248  if (ByValSizeInBytes == OffsetInBytes)
4249  return;
4250 
4251  // Copy the remainder of the byval argument with sub-word loads and shifts.
4252  if (LeftoverBytes) {
4253  SDValue Val;
4254 
4255  for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4256  OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4257  unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4258 
4259  if (RemainingSizeInBytes < LoadSizeInBytes)
4260  continue;
4261 
4262  // Load subword.
4263  SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4264  DAG.getConstant(OffsetInBytes, DL,
4265  PtrTy));
4266  SDValue LoadVal = DAG.getExtLoad(
4267  ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4268  MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4269  MemOpChains.push_back(LoadVal.getValue(1));
4270 
4271  // Shift the loaded value.
4272  unsigned Shamt;
4273 
4274  if (isLittle)
4275  Shamt = TotalBytesLoaded * 8;
4276  else
4277  Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4278 
4279  SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4280  DAG.getConstant(Shamt, DL, MVT::i32));
4281 
4282  if (Val.getNode())
4283  Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4284  else
4285  Val = Shift;
4286 
4287  OffsetInBytes += LoadSizeInBytes;
4288  TotalBytesLoaded += LoadSizeInBytes;
4289  Alignment = std::min(Alignment, LoadSizeInBytes);
4290  }
4291 
4292  unsigned ArgReg = ArgRegs[FirstReg + I];
4293  RegsToPass.push_back(std::make_pair(ArgReg, Val));
4294  return;
4295  }
4296  }
4297 
4298  // Copy remainder of byval arg to it with memcpy.
4299  unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4300  SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4301  DAG.getConstant(OffsetInBytes, DL, PtrTy));
4302  SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4303  DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
4304  Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4305  DAG.getConstant(MemCpySize, DL, PtrTy),
4306  Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
4307  /*isTailCall=*/false,
4309  MemOpChains.push_back(Chain);
4310 }
4311 
4312 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4313  SDValue Chain, const SDLoc &DL,
4314  SelectionDAG &DAG,
4315  CCState &State) const {
4317  unsigned Idx = State.getFirstUnallocated(ArgRegs);
4318  unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4319  MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4320  const TargetRegisterClass *RC = getRegClassFor(RegTy);
4321  MachineFunction &MF = DAG.getMachineFunction();
4322  MachineFrameInfo &MFI = MF.getFrameInfo();
4323  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4324 
4325  // Offset of the first variable argument from stack pointer.
4326  int VaArgOffset;
4327 
4328  if (ArgRegs.size() == Idx)
4329  VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
4330  else {
4331  VaArgOffset =
4333  (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4334  }
4335 
4336  // Record the frame index of the first variable argument
4337  // which is a value necessary to VASTART.
4338  int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4339  MipsFI->setVarArgsFrameIndex(FI);
4340 
4341  // Copy the integer registers that have not been used for argument passing
4342  // to the argument register save area. For O32, the save area is allocated
4343  // in the caller's stack frame, while for N32/64, it is allocated in the
4344  // callee's stack frame.
4345  for (unsigned I = Idx; I < ArgRegs.size();
4346  ++I, VaArgOffset += RegSizeInBytes) {
4347  unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4348  SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4349  FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4350  SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4351  SDValue Store =
4352  DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4353  cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4354  (Value *)nullptr);
4355  OutChains.push_back(Store);
4356  }
4357 }
4358 
4359 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
4360  unsigned Align) const {
4362 
4363  assert(Size && "Byval argument's size shouldn't be 0.");
4364 
4365  Align = std::min(Align, TFL->getStackAlignment());
4366 
4367  unsigned FirstReg = 0;
4368  unsigned NumRegs = 0;
4369 
4370  if (State->getCallingConv() != CallingConv::Fast) {
4371  unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4372  ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4373  // FIXME: The O32 case actually describes no shadow registers.
4374  const MCPhysReg *ShadowRegs =
4375  ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4376 
4377  // We used to check the size as well but we can't do that anymore since
4378  // CCState::HandleByVal() rounds up the size after calling this function.
4379  assert(!(Align % RegSizeInBytes) &&
4380  "Byval argument's alignment should be a multiple of"
4381  "RegSizeInBytes.");
4382 
4383  FirstReg = State->getFirstUnallocated(IntArgRegs);
4384 
4385  // If Align > RegSizeInBytes, the first arg register must be even.
4386  // FIXME: This condition happens to do the right thing but it's not the
4387  // right way to test it. We want to check that the stack frame offset
4388  // of the register is aligned.
4389  if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
4390  State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4391  ++FirstReg;
4392  }
4393 
4394  // Mark the registers allocated.
4395  Size = alignTo(Size, RegSizeInBytes);
4396  for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4397  Size -= RegSizeInBytes, ++I, ++NumRegs)
4398  State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4399  }
4400 
4401  State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4402 }
4403 
4404 MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4405  MachineBasicBlock *BB,
4406  bool isFPCmp,
4407  unsigned Opc) const {
4409  "Subtarget already supports SELECT nodes with the use of"
4410  "conditional-move instructions.");
4411 
4412  const TargetInstrInfo *TII =
4414  DebugLoc DL = MI.getDebugLoc();
4415 
4416  // To "insert" a SELECT instruction, we actually have to insert the
4417  // diamond control-flow pattern. The incoming instruction knows the
4418  // destination vreg to set, the condition code register to branch on, the
4419  // true/false values to select between, and a branch opcode to use.
4420  const BasicBlock *LLVM_BB = BB->getBasicBlock();
4422 
4423  // thisMBB:
4424  // ...
4425  // TrueVal = ...
4426  // setcc r1, r2, r3
4427  // bNE r1, r0, copy1MBB
4428  // fallthrough --> copy0MBB
4429  MachineBasicBlock *thisMBB = BB;
4430  MachineFunction *F = BB->getParent();
4431  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4432  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4433  F->insert(It, copy0MBB);
4434  F->insert(It, sinkMBB);
4435 
4436  // Transfer the remainder of BB and its successor edges to sinkMBB.
4437  sinkMBB->splice(sinkMBB->begin(), BB,
4438  std::next(MachineBasicBlock::iterator(MI)), BB->end());
4439  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4440 
4441  // Next, add the true and fallthrough blocks as its successors.
4442  BB->addSuccessor(copy0MBB);
4443  BB->addSuccessor(sinkMBB);
4444 
4445  if (isFPCmp) {
4446  // bc1[tf] cc, sinkMBB
4447  BuildMI(BB, DL, TII->get(Opc))
4448  .addReg(MI.getOperand(1).getReg())
4449  .addMBB(sinkMBB);
4450  } else {
4451  // bne rs, $0, sinkMBB
4452  BuildMI(BB, DL, TII->get(Opc))
4453  .addReg(MI.getOperand(1).getReg())
4454  .addReg(Mips::ZERO)
4455  .addMBB(sinkMBB);
4456  }
4457 
4458  // copy0MBB:
4459  // %FalseValue = ...
4460  // # fallthrough to sinkMBB
4461  BB = copy0MBB;
4462 
4463  // Update machine-CFG edges
4464  BB->addSuccessor(sinkMBB);
4465 
4466  // sinkMBB:
4467  // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4468  // ...
4469  BB = sinkMBB;
4470 
4471  BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.get